Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Logger, replace existing logging #193

Merged
merged 4 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/main/java/io/beanmapper/config/OverrideField.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.util.function.Supplier;

import io.beanmapper.utils.BeanMapperPerformanceLogger;

public class OverrideField<T> {

private final Supplier<T> supplier;
Expand Down Expand Up @@ -31,9 +33,10 @@ public T get() {
if (this.block) {
return null;
}
return this.value == null ?
this.supplier.get() :
this.value;
if (this.value == null) {
this.value = BeanMapperPerformanceLogger.runTimedTask("Retrieving nested configuration field.", this.supplier);
}
return value;
}

}
}
13 changes: 8 additions & 5 deletions src/main/java/io/beanmapper/config/StrictMappingProperties.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.beanmapper.core.unproxy.BeanUnproxy;
import io.beanmapper.core.unproxy.SkippingBeanUnproxy;
import io.beanmapper.utils.BeanMapperPerformanceLogger;

public class StrictMappingProperties {

Expand Down Expand Up @@ -79,18 +80,20 @@ public void setApplyStrictMappingConvention(boolean applyStrictMappingConvention
}

public BeanPair createBeanPair(Class<?> sourceClass, Class<?> targetClass) {
sourceClass = beanUnproxy.unproxy(sourceClass);
targetClass = beanUnproxy.unproxy(targetClass);
BeanPair beanPair = new BeanPair(sourceClass, targetClass);
BeanPair beanPair = BeanMapperPerformanceLogger.runTimedTask("Creating BeanPair, and unproxying source %s-class and target %s-class.".formatted(sourceClass.getCanonicalName(), targetClass.getCanonicalName()), () -> {
Class<?> unproxiedSource = beanUnproxy.unproxy(sourceClass);
Class<?> unproxiedTarget = beanUnproxy.unproxy(targetClass);
return new BeanPair(unproxiedSource, unproxiedTarget);
});
if (!isApplyStrictMappingConvention()) {
return beanPair;
}
if (strictSourceSuffix != null &&
sourceClass.getCanonicalName().endsWith(strictSourceSuffix)) {
beanPair.getSourceClass().getCanonicalName().endsWith(strictSourceSuffix)) {
beanPair = beanPair.withStrictSource();
}
if (strictTargetSuffix != null &&
targetClass.getCanonicalName().endsWith(strictTargetSuffix)) {
beanPair.getTargetClass().getCanonicalName().endsWith(strictTargetSuffix)) {
beanPair = beanPair.withStrictTarget();
}
return beanPair;
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/io/beanmapper/core/BeanMatch.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@
import io.beanmapper.config.BeanPair;
import io.beanmapper.exceptions.BeanNoSuchPropertyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanMatch {

private static final Logger log = LoggerFactory.getLogger(BeanMatch.class);

private final BeanPair beanPair;

private final Map<String, BeanProperty> sourceNodes;
Expand Down Expand Up @@ -106,6 +111,7 @@ private void checkForMandatoryUnmatchedNodes(String side, Class<?> containingCla
for (Map.Entry<String, BeanProperty> entry : nodes.entrySet()) {
BeanProperty currentField = entry.getValue();
if (currentField.isUnmatched()) {
log.error("{} {} has no match for property {}", side, containingClass.isAnonymousClass(), entry.getKey());
sptdevos marked this conversation as resolved.
Show resolved Hide resolved
throw new BeanNoSuchPropertyException(side + " " + containingClass.getCanonicalName() + " has no match for property " + entry.getKey());
}
}
Expand Down
12 changes: 4 additions & 8 deletions src/main/java/io/beanmapper/core/BeanMatchStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,11 @@
import io.beanmapper.exceptions.BeanMissingPathException;
import io.beanmapper.exceptions.BeanNoSuchPropertyException;
import io.beanmapper.exceptions.FieldShadowingException;
import io.beanmapper.utils.BeanMapperTraceLogger;
import io.beanmapper.utils.Trinary;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanMatchStore {

private final Logger logger = LoggerFactory.getLogger(getClass());

private final CollectionHandlerStore collectionHandlerStore;

private final BeanUnproxy beanUnproxy;
Expand Down Expand Up @@ -287,11 +283,11 @@ private BeanPropertyWrapper dealWithBeanProperty(BeanPropertyMatchupDirection ma
new BeanPropertyCreator(matchupDirection.getInverse(), otherType, wrapper.getName())
.determineNodesForPath());
} catch (BeanNoSuchPropertyException err) {
if (logger.isDebugEnabled()) {
logger.debug("""

BeanMapperTraceLogger.log("""
BeanNoSuchPropertyException thrown by BeanMatchStore#dealWithBeanProperty(BeanPropertyMatchupDirection, Map<String, BeanProperty>, Class, PropertyAccessor), for {}.
{}""", wrapper.getName(), err.getMessage());
}

}
}
return wrapper;
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/io/beanmapper/core/BeanPropertyCreator.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@
import io.beanmapper.core.inspector.PropertyAccessors;
import io.beanmapper.exceptions.BeanNoSuchPropertyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanPropertyCreator {

private static final Logger log = LoggerFactory.getLogger(BeanPropertyCreator.class);

private final BeanPropertyMatchupDirection matchupDirection;

private final Class<?> baseClass;
Expand Down Expand Up @@ -68,6 +73,7 @@ private void traversePath(Stack<BeanProperty> beanProperties) {
for (String node : route.getRoute()) {
final PropertyAccessor property = PropertyAccessors.findProperty(currentBaseClass, node);
if (property == null) {
log.error("Property '{}' does not exist in: {}", node, currentBaseClass.getSimpleName());
throw new BeanNoSuchPropertyException("Property '" + node + "' does not exist in: " + currentBaseClass.getSimpleName());
}
beanProperties.push(new BeanProperty(
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/io/beanmapper/core/BeanPropertyMatch.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
import io.beanmapper.exceptions.BeanMappingException;
import io.beanmapper.exceptions.BeanNoLogicSecuredCheckSetException;
import io.beanmapper.exceptions.BeanNoRoleSecuredCheckSetException;
import io.beanmapper.utils.BeanMapperTraceLogger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanPropertyMatch {

protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final Logger log = LoggerFactory.getLogger(BeanPropertyMatch.class);

private final BeanMatch beanMatch;
private final Object source;
Expand Down Expand Up @@ -81,7 +82,7 @@
if (enforcedSecuredProperties) {
throw new BeanNoLogicSecuredCheckSetException(message);
}
logger.warn(message);
BeanMapperTraceLogger.log(message);

Check warning on line 85 in src/main/java/io/beanmapper/core/BeanPropertyMatch.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/io/beanmapper/core/BeanPropertyMatch.java#L85

Added line #L85 was not covered by tests
return true;
}
return logicSecuredCheck.isAllowed(source, target);
Expand All @@ -96,7 +97,7 @@
if (enforcedSecuredProperties) {
throw new BeanNoRoleSecuredCheckSetException(message);
}
logger.warn(message);
log.warn(message);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import java.util.Collections;
import java.util.List;

import io.beanmapper.utils.BeanMapperTraceLogger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BeanStrictMappingRequirementsException extends RuntimeException {

protected final transient Logger logger = LoggerFactory.getLogger(getClass());

private static final Logger log = LoggerFactory.getLogger(BeanStrictMappingRequirementsException.class);
private final List<BeanMatchValidationMessage> validationMessages;

public BeanStrictMappingRequirementsException(BeanMatchValidationMessage validationMessage) {
Expand All @@ -26,7 +27,7 @@ private void logErrors(List<BeanMatchValidationMessage> validationMessages) {
if (validationMessage.isLogged()) {
continue;
}
logger.error("""
log.error("""
Missing matching properties for source [{}] {} > target [{}] {} for fields:
""",
validationMessage.getSourceClass().getCanonicalName(),
Expand All @@ -35,7 +36,7 @@ private void logErrors(List<BeanMatchValidationMessage> validationMessages) {
(validationMessage.isTargetStrict() ? "*" : ""));

for (BeanProperty field : validationMessage.getFields()) {
logger.error("""
log.error("""
> {}.{}
""",
validationMessage.getStrictClass().getSimpleName(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import io.beanmapper.config.CollectionFlusher;
import io.beanmapper.core.constructor.DefaultBeanInitializer;
import io.beanmapper.exceptions.BeanCollectionUnassignableTargetCollectionTypeException;
import io.beanmapper.utils.BeanMapperPerformanceLogger;
import io.beanmapper.utils.Classes;

public abstract class AbstractCollectionHandler<C> implements CollectionHandler<C> {
Expand Down Expand Up @@ -32,14 +33,16 @@ public Object mapItem(
BeanMapper beanMapper,
Class<?> collectionElementClass,
Object source) {

return beanMapper
.wrap()
return BeanMapperPerformanceLogger.runTimedTask("Recursively calling BeanMapper#map(Object), to map collection elements of type %s, to %s."
.formatted(source != null
? source.getClass().getCanonicalName()
: "null", collectionElementClass.getCanonicalName()),
() -> beanMapper.wrap()
.setTargetClass(collectionElementClass)
.setCollectionClass(null)
.setConverterChoosable(true)
.build()
.map(source);
.map(source));
}

@Override
Expand Down Expand Up @@ -90,4 +93,4 @@ public int getGenericParameterIndex() {
return 0;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@
import io.beanmapper.BeanMapper;
import io.beanmapper.config.BeanMapperBuilder;
import io.beanmapper.strategy.ConstructorArguments;
import io.beanmapper.utils.BeanMapperTraceLogger;
import io.beanmapper.utils.DefaultValues;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultBeanInitializer implements BeanInitializer {

private final Logger logger = LoggerFactory.getLogger(getClass());
private static final Logger log = LoggerFactory.getLogger(DefaultBeanInitializer.class);

/**
* {@inheritDoc}
*/
@Override
public <T> T instantiate(Class<T> beanClass, ConstructorArguments arguments) {
BeanMapperTraceLogger.log("Creating a new instance of type %s, using reflection.".formatted(beanClass));
try {
if (arguments == null) {
return beanClass.getConstructor().newInstance();
Expand All @@ -34,7 +36,7 @@
var constructorParameterTypes = Arrays.stream(constructor.getParameters()).map(Parameter::getParameterizedType).toArray(Type[]::new);
return beanClass.getConstructor(arguments.getTypes()).newInstance(mapParameterizedArguments(constructorParameterTypes, arguments.getValues()));
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
logger.error("Could not instantiate bean of class %s. Returning the default value associated with the given type. %s".formatted(beanClass.getName(),
log.error("Could not instantiate bean of class %s. Returning the default value associated with the given type. %s".formatted(beanClass.getName(),

Check warning on line 39 in src/main/java/io/beanmapper/core/constructor/DefaultBeanInitializer.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/io/beanmapper/core/constructor/DefaultBeanInitializer.java#L39

Added line #L39 was not covered by tests
e.getMessage()));
return DefaultValues.defaultValueFor(beanClass);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.beanmapper.core.BeanPropertyMatch;
import io.beanmapper.core.collections.CollectionHandler;
import io.beanmapper.core.converter.BeanConverter;
import io.beanmapper.utils.BeanMapperPerformanceLogger;

public class CollectionConverter implements BeanConverter {

Expand All @@ -24,7 +25,11 @@ public <R, U> U convert(
return targetClass.cast(source);
}

return beanMapper.wrap()
return BeanMapperPerformanceLogger.runTimedTask("Calling BeanMapper#map(Object) recursively, to convert object of type %s, to type %s."
.formatted(source != null
? source.getClass().getCanonicalName()
: "null", targetClass.getCanonicalName()),
() -> beanMapper.wrap()
.setCollectionClass(collectionHandler.getType())
.setCollectionUsage(beanPropertyMatch.getCollectionInstructions().getBeanCollectionUsage())
.setPreferredCollectionClass(beanPropertyMatch.getCollectionInstructions().getPreferredCollectionClass().getAnnotationClass())
Expand All @@ -33,7 +38,7 @@ public <R, U> U convert(
.setTarget(beanPropertyMatch.getTargetObject())
.setUseNullValue()
.build()
.map(source);
.map(source));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
import io.beanmapper.core.converter.BeanConverter;
import io.beanmapper.exceptions.BeanNoSuchPropertyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This converter facilitates the conversion of an object to an Optional wrapping another object. This converter does
* not support the conversion of complex datastructures, such as Collections, to Optionals. If that functionality is
Expand All @@ -18,6 +21,8 @@
*/
public class ObjectToOptionalConverter implements BeanConverter {

private static final Logger log = LoggerFactory.getLogger(ObjectToOptionalConverter.class);

@Override
public <S, T> T convert(BeanMapper beanMapper, S source, Class<T> targetClass, BeanPropertyMatch beanPropertyMatch) {
if (source == null) {
Expand All @@ -28,6 +33,7 @@
try {
targetField = beanPropertyMatch.getTarget().getClass().getDeclaredField(beanPropertyMatch.getTargetFieldName());
} catch (NoSuchFieldException e) {
log.error(e.getMessage());

Check warning on line 36 in src/main/java/io/beanmapper/core/converter/impl/ObjectToOptionalConverter.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/io/beanmapper/core/converter/impl/ObjectToOptionalConverter.java#L36

Added line #L36 was not covered by tests
throw new BeanNoSuchPropertyException(e.getMessage());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@
import io.beanmapper.BeanMapper;
import io.beanmapper.core.BeanPropertyMatch;
import io.beanmapper.core.converter.BeanConverter;
import io.beanmapper.utils.BeanMapperTraceLogger;
import io.beanmapper.utils.Classes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This converter facilitates the conversion of an arbitrary amount of Optional wrappers, however, support for complex
* datastructures, such as Maps, Sets, List, etc. is limited to a single layer. As such, if the user requires support
Expand All @@ -25,8 +23,6 @@
*/
public class OptionalToObjectConverter implements BeanConverter {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

/**
* {@inheritDoc}
*/
Expand All @@ -35,13 +31,11 @@ public <S, T> T convert(BeanMapper beanMapper, S source, Class<T> targetClass, B
Object obj = ((Optional<?>) source).orElse(null);

if (targetClass.equals(Optional.class)) {
if (logger.isDebugEnabled()) {
// Not always possible to get the actual source class, so just report the name of the field. Debug log will show the call stack.
logger.debug("Converting Optional to Optional. Perhaps the target does not need to be an Optional?\nSource-field: {}\nTarget: {}.{}",
beanPropertyMatch.getSourceFieldName(),
beanPropertyMatch.getTarget().getClass(),
beanPropertyMatch.getTargetFieldName());
}
// Not always possible to get the actual source class, so just report the name of the field. Debug log will show the call stack.
BeanMapperTraceLogger.log("Converting Optional to Optional. Perhaps the target does not need to be an Optional?\nSource-field: {}\nTarget: {}.{}",
beanPropertyMatch.getSourceFieldName(),
beanPropertyMatch.getTarget().getClass(),
beanPropertyMatch.getTargetFieldName());
return targetClass.cast(convertToOptional(beanMapper, (Optional<?>) source, beanPropertyMatch));
} else if (obj == null) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.util.HashSet;
import java.util.Set;

import io.beanmapper.utils.BeanMapperTraceLogger;

/**
* Unproxy that allows you to configure classes to skip.
*
Expand All @@ -31,6 +33,7 @@ public SkippingBeanUnproxy(BeanUnproxy delegate) {
*/
@Override
public Class<?> unproxy(Class<?> beanClass) {
BeanMapperTraceLogger.log("Unproxying class %s.".formatted(beanClass != null ? beanClass.getCanonicalName() : "null"));
if (isSkippedProxyClass(beanClass)) {
return beanClass;
}
Expand Down
Loading
Loading