proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/PropertyReferenceCollector.java
PropertyReferenceCollector
collect
class PropertyReferenceCollector { private final InheritingConfiguration config; private final ExplicitMappingBuilder.MappingOptions options; private final List<Accessor> accessors; private final List<Mutator> mutators; // This field will be set with a value if the mapping is map from source private Class<?> sourceType; // This field will be set with a value if the mapping is map from constant private Object constant; private final Errors errors; private final Errors proxyErrors; public static <S, D> List<Accessor> collect(TypeMapImpl<S, D> typeMap, TypeSafeSourceGetter<S, ?> sourceGetter) {<FILL_FUNCTION_BODY>} PropertyReferenceCollector(InheritingConfiguration config, ExplicitMappingBuilder.MappingOptions options) { this.config = config; this.options = options; this.accessors = new ArrayList<Accessor>(); this.mutators = new ArrayList<Mutator>(); this.errors = new Errors(); this.proxyErrors = new Errors(); } public final class SourceInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) { visitSource(proxy.getClass(), method); if (Void.class.isAssignableFrom(method.getReturnType())) return null; try { return ProxyFactory.proxyFor(resolveReturnType(method), this, proxyErrors); } catch (ErrorsException e) { return null; } } } public final class DestinationInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) { visitDestination(proxy.getClass(), method); if (Void.class.isAssignableFrom(method.getReturnType())) return null; try { return ProxyFactory.proxyFor(resolveReturnType(method), this, proxyErrors); } catch (ErrorsException e) { return null; } } } private static Class<?> resolveReturnType(Method method) { Accessor accessor = new MethodAccessor(method.getDeclaringClass(), method, method.getName()); return accessor.getType(); } SourceInterceptor newSourceInterceptor() { return new SourceInterceptor(); } DestinationInterceptor newDestinationInterceptor() { return new DestinationInterceptor(); } private void visitSource(Class<?> type, Method method) { if (PropertyInfoResolver.ACCESSORS.isValid(method)) { String propertyName = config.getSourceNameTransformer().transform(method.getName(), NameableType.METHOD); accessors.add(PropertyInfoRegistry.accessorFor(type, method, config, propertyName)); } else errors.addMessage("Illegal SourceGetter method: %s.%s", type.getName(), method.getName()); } private void visitDestination(Class<?> type, Method method) { if (PropertyInfoResolver.MUTATORS.isValid(method)) { String propertyName = config.getDestinationNameTransformer().transform(method.getName(), NameableType.METHOD); mutators.add(PropertyInfoRegistry.mutatorFor(type, method, config, propertyName)); } else if (PropertyInfoResolver.ACCESSORS.isValid(method)) { Mutator mutator = TypeInfoRegistry.typeInfoFor(type, config).mutatorForAccessorMethod( method.getName()); if (mutator != null) mutators.add(mutator); else errors.addMessage("No setter found: %s.%s", type.getName(), method.getName()); } else errors.addMessage("Illegal DestinationSetter method: %s.%s", type.getName(), method.getName()); } MappingImpl collect() { if (mutators.isEmpty()) errors.addMessage("Illegal DestinationSetter defined"); if (options.skipType == 1 && options.condition != null && accessors.isEmpty()) errors.addMessage("Source properties must be provided when conditional skip, please use when().skip(sourceGetter, destinationSetter) instead"); errors.throwConfigurationExceptionIfErrorsExist(); if (sourceType != null) return new SourceMappingImpl(sourceType, new ArrayList<Mutator>(mutators), options); if (accessors.isEmpty()) return new ConstantMappingImpl(constant, new ArrayList<Mutator>(mutators), options); return new PropertyMappingImpl(new ArrayList<Accessor>(accessors), new ArrayList<Mutator>(mutators), options); } void reset() { mutators.clear(); accessors.clear(); options.reset(); sourceType = null; constant = null; } public Errors getErrors() { return errors; } Errors getProxyErrors() { return proxyErrors; } void mapFromSource(Class<?> sourceType) { this.sourceType = sourceType; } void mapFromConstant(Object constant) { this.constant = constant; } boolean isNoSourceGetter() { return accessors.isEmpty(); } }
PropertyReferenceCollector collector = new PropertyReferenceCollector(typeMap.configuration, null); try { S source = ProxyFactory.proxyFor(typeMap.getSourceType(), collector.newSourceInterceptor(), collector.getProxyErrors()); Object sourceProperty = sourceGetter.get(source); if (source == sourceProperty) collector.mapFromSource(typeMap.getSourceType()); if (collector.isNoSourceGetter()) collector.mapFromConstant(sourceProperty); } catch (NullPointerException e) { if (collector.getProxyErrors().hasErrors()) throw collector.getProxyErrors().toException(); throw e; } catch (ErrorsException e) { throw e.getErrors().toConfigurationException(); } return collector.accessors;
1,337
198
1,535
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/ProxyFactory.java
ProxyFactory
chooseClassLoadingStrategy
class ProxyFactory { private static final Objenesis OBJENESIS = new ObjenesisStd(); private static final ByteBuddy BYTEBUDDY = new ByteBuddy() .with(new NamingStrategy.SuffixingRandom("ByteBuddy", NO_PREFIX)); private static final ElementMatcher<? super MethodDescription> METHOD_FILTER = not( named("hashCode").or(named("equals"))); private static final Method PRIVATE_LOOKUP_IN; private static final Object LOOKUP; static { Method privateLookupIn; Object lookup; try { Class<?> methodHandles = Class.forName("java.lang.invoke.MethodHandles"); lookup = methodHandles.getMethod("lookup").invoke(null); privateLookupIn = methodHandles.getMethod( "privateLookupIn", Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup") ); } catch (Exception e) { privateLookupIn = null; lookup = null; } PRIVATE_LOOKUP_IN = privateLookupIn; LOOKUP = lookup; } /** * @throws ErrorsException if the proxy for {@code type} cannot be generated or instantiated */ static <T> T proxyFor(Class<T> type, InvocationHandler interceptor, Errors errors) throws ErrorsException { return proxyFor(type, interceptor, errors, Boolean.FALSE); } /** * @throws ErrorsException if the proxy for {@code type} cannot be generated or instantiated */ static <T> T proxyFor(Class<T> type, InvocationHandler interceptor, Errors errors, boolean useOSGiClassLoaderBridging) throws ErrorsException { if (Primitives.isPrimitive(type)) return Primitives.defaultValueForWrapper(type); if (isProxyUnsupported(type)) return null; if (Modifier.isFinal(type.getModifiers())) throw errors.invocationAgainstFinalClass(type).toException(); try { final DynamicType.Unloaded<T> unloaded = BYTEBUDDY .subclass(type) .method(METHOD_FILTER) .intercept(InvocationHandlerAdapter.of(interceptor)) .make(); final ClassLoadingStrategy<ClassLoader> classLoadingStrategy = chooseClassLoadingStrategy(type); final ClassLoader classLoader = useOSGiClassLoaderBridging ? BridgeClassLoaderFactory.getClassLoader(type) : type.getClassLoader(); if (classLoadingStrategy != null) { return OBJENESIS.newInstance(unloaded .load(classLoader, classLoadingStrategy) .getLoaded()); } else { return OBJENESIS.newInstance(unloaded .load(classLoader) .getLoaded()); } } catch (Throwable t) { throw errors.errorInstantiatingProxy(type, t).toException(); } } private static boolean isProxyUnsupported(Class<?> type) { return type.equals(String.class) || type.equals(Object.class) || Collection.class.isAssignableFrom(type) || Number.class.isAssignableFrom(type); } private static <T> ClassLoadingStrategy<ClassLoader> chooseClassLoadingStrategy(Class<T> type) {<FILL_FUNCTION_BODY>} }
try { final ClassLoadingStrategy<ClassLoader> strategy; if (ClassInjector.UsingLookup.isAvailable() && PRIVATE_LOOKUP_IN != null && LOOKUP != null) { Object privateLookup = PRIVATE_LOOKUP_IN.invoke(null, type, LOOKUP); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } return strategy; } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); }
903
258
1,161
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/ReferenceMapExpressionImpl.java
ReferenceMapExpressionImpl
visitDestination
class ReferenceMapExpressionImpl<S, D> implements ReferenceMapExpression<S, D> { private final TypeMapImpl<S, D> typeMap; private final MappingOptions options; private final PropertyReferenceCollector collector; private final S source; private final D destination; ReferenceMapExpressionImpl(TypeMapImpl<S, D> typeMap) { this(typeMap, new MappingOptions()); } ReferenceMapExpressionImpl(TypeMapImpl<S, D> typeMap, MappingOptions options) { this.typeMap = typeMap; this.options = options; this.collector = new PropertyReferenceCollector(typeMap.configuration, options); try { this.source = ProxyFactory.proxyFor(typeMap.getSourceType(), collector.newSourceInterceptor(), collector.getProxyErrors()); this.destination = ProxyFactory .proxyFor(typeMap.getDestinationType(), collector.newDestinationInterceptor(), collector.getProxyErrors()); } catch (ErrorsException e) { throw e.getErrors().toConfigurationException(); } } @Override public <V> void map(SourceGetter<S> sourceGetter, DestinationSetter<D, V> destinationSetter) { visitSource(sourceGetter); visitDestination(destinationSetter); skipMapping(collector.collect()); collector.reset(); } @Override public <V> void skip(DestinationSetter<D, V> destinationSetter) { options.skipType = 1; visitDestination(destinationSetter); skipMapping(collector.collect()); collector.reset(); } private void skipMapping(MappingImpl skipMapping) { String prefix = skipMapping.getPath(); List<String> conflictPaths = typeMap.getMappings().stream() .map(Mapping::getPath) .filter(path -> path.startsWith(prefix) && !path.equals(prefix)) .collect(toList()); if (conflictPaths.isEmpty()) { typeMap.addMapping(skipMapping); } else { collector.getErrors().skipConflict(skipMapping.getPath(), conflictPaths); collector.getErrors().throwConfigurationExceptionIfErrorsExist(); } } @Override public <V> void skip(SourceGetter<S> sourceGetter, DestinationSetter<D, V> destinationSetter) { options.skipType = 1; visitSource(sourceGetter); visitDestination(destinationSetter); skipMapping(collector.collect()); collector.reset(); } private void visitSource(SourceGetter<S> sourceGetter) { notNull(sourceGetter, "sourceGetter"); try { Object sourceProperty = sourceGetter.get(source); if (source == sourceProperty) collector.mapFromSource(typeMap.getSourceType()); if (collector.isNoSourceGetter()) collector.mapFromConstant(sourceProperty); } catch (NullPointerException e) { if (collector.getProxyErrors().hasErrors()) throw collector.getProxyErrors().toException(); throw e; } catch (ErrorsException e) { throw e.getErrors().toConfigurationException(); } } private <V> void visitDestination(DestinationSetter<D, V> destinationSetter) {<FILL_FUNCTION_BODY>} private <V> V destinationValue(DestinationSetter<D, V> destinationSetter) { Class<?>[] typeArguments = TypeResolver.resolveRawArguments(DestinationSetter.class, destinationSetter.getClass()); if (typeArguments != null) { Class<?> valueClass = typeArguments[1]; if (Primitives.isPrimitive(valueClass)) { return Primitives.defaultValue(Primitives.primitiveFor(valueClass)); } } return null; } }
notNull(destinationSetter, "destinationSetter"); try { destinationSetter.accept(destination, destinationValue(destinationSetter)); } catch (NullPointerException e) { if (collector.getProxyErrors().hasErrors()) throw collector.getProxyErrors().toException(); throw e; } catch (ErrorsException e) { throw e.getErrors().toConfigurationException(); }
1,000
109
1,109
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/SourceMappingImpl.java
SourceMappingImpl
createMergedCopy
class SourceMappingImpl extends MappingImpl implements SourceMapping { private final Class<?> sourceType; /** * Creates an explicit SourceMappingImpl. */ SourceMappingImpl(Class<?> sourceType, List<Mutator> destinationMutators, MappingOptions options) { super(destinationMutators, options); this.sourceType = sourceType; } @Override public Class<?> getSourceType() { return sourceType; } @Override public String toString() { return String.format("SourceMapping[%s -> %s]", sourceType, Strings.joinWithFirstType(getDestinationProperties())); } @Override public InternalMapping createMergedCopy(List<? extends PropertyInfo> mergedAccessors, List<? extends PropertyInfo> mergedMutators) {<FILL_FUNCTION_BODY>} }
List<PropertyInfo> mutators = new ArrayList<PropertyInfo>(); mutators.addAll(mergedMutators); mutators.addAll(getDestinationProperties()); return new PropertyMappingImpl(mergedAccessors, mutators, getOptions());
252
70
322
<methods>public int compareTo(org.modelmapper.internal.MappingImpl) ,public boolean equals(java.lang.Object) ,public Condition<?,?> getCondition() ,public Converter<?,?> getConverter() ,public List<? extends org.modelmapper.spi.PropertyInfo> getDestinationProperties() ,public org.modelmapper.spi.PropertyInfo getLastDestinationProperty() ,public java.lang.String getPath() ,public Provider<?> getProvider() ,public int hashCode() ,public boolean isExplicit() ,public boolean isSkipped() <variables>private Condition<?,?> condition,protected Converter<?,?> converter,private final non-sealed List<org.modelmapper.spi.PropertyInfo> destinationMutators,private final non-sealed boolean explicit,private final non-sealed java.lang.String path,protected Provider<?> provider,private int skipType
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/TypeInfoImpl.java
TypeInfoImpl
getMutators
class TypeInfoImpl<T> implements TypeInfo<T> { /** Source object from which memberNames are read. */ private final T source; private final Class<T> type; private final InheritingConfiguration configuration; private volatile Map<String, Accessor> accessors; private volatile Map<String, Mutator> mutators; TypeInfoImpl(T source, Class<T> sourceType, InheritingConfiguration configuration) { this.source = source; this.type = sourceType; this.configuration = configuration; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof TypeInfo)) return false; TypeInfo<?> typeInfo = (TypeInfo<?>) obj; return type.equals(typeInfo.getType()) && configuration.equals(typeInfo.getConfiguration()); } /** * Lazily initializes and gets accessors. */ public Map<String, Accessor> getAccessors() { if (accessors == null) synchronized (this) { if (accessors == null) accessors = PropertyInfoSetResolver.resolveAccessors(source, type, configuration); } return accessors; } public Configuration getConfiguration() { return configuration; } /** * Lazily initializes and gets mutators. */ public Map<String, Mutator> getMutators() {<FILL_FUNCTION_BODY>} public Class<T> getType() { return type; } @Override public int hashCode() { return type.hashCode() * 31 + configuration.hashCode(); } @Override public String toString() { return type.toString(); } Mutator mutatorForAccessorMethod(String accessorMethodName) { return getMutators().get( configuration.getSourceNameTransformer().transform(accessorMethodName, NameableType.METHOD)); } }
if (mutators == null) synchronized (this) { if (mutators == null) mutators = PropertyInfoSetResolver.resolveMutators(type, configuration); } return mutators;
579
65
644
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/TypeInfoRegistry.java
TypeInfoKey
typeInfoFor
class TypeInfoKey { private final Class<?> type; private final Configuration configuration; TypeInfoKey(Class<?> type, Configuration configuration) { this.type = type; this.configuration = configuration; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof TypeInfoKey)) return false; TypeInfoKey other = (TypeInfoKey) o; return type.equals(other.type) && configuration.equals(other.configuration); } @Override public int hashCode() { int result = 31 * type.hashCode(); return 31 * result + configuration.hashCode(); } } @SuppressWarnings("unchecked") static <T> TypeInfoImpl<T> typeInfoFor(Accessor accessor, InheritingConfiguration configuration) { return TypeInfoRegistry.typeInfoFor(null, (Class<T>) accessor.getType(), configuration); } /** * Returns a non-cached TypeInfoImpl instance if there is no supported ValueAccessReader for the * {@code sourceType}, else a cached TypeInfoImpl instance is returned. */ static <T> TypeInfoImpl<T> typeInfoFor(T source, Class<T> sourceType, InheritingConfiguration configuration) { if (configuration.valueAccessStore.getFirstSupportedReader(sourceType) != null && source != null) return new TypeInfoImpl<T>(source, sourceType, configuration); return typeInfoFor(sourceType, configuration); } /** * Returns a statically cached TypeInfoImpl instance for the given criteria. */ @SuppressWarnings("unchecked") static <T> TypeInfoImpl<T> typeInfoFor(Class<T> sourceType, InheritingConfiguration configuration) {<FILL_FUNCTION_BODY>
TypeInfoKey pair = new TypeInfoKey(sourceType, configuration); TypeInfoImpl<T> typeInfo = (TypeInfoImpl<T>) cache.get(pair); if (typeInfo == null) { synchronized (cache) { typeInfo = (TypeInfoImpl<T>) cache.get(pair); if (typeInfo == null) { typeInfo = new TypeInfoImpl<T>(null, sourceType, configuration); cache.put(pair, typeInfo); } } } return typeInfo;
524
155
679
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/TypePair.java
TypePair
equals
class TypePair<S, D> { private final Class<S> sourceType; private final Class<D> destinationType; private final String name; private final int hashCode; private TypePair(Class<S> sourceType, Class<D> destinationType, String name) { this.sourceType = sourceType; this.destinationType = destinationType; this.name = name; hashCode = computeHashCode(); } static <T1, T2> TypePair<T1, T2> of(Class<T1> sourceType, Class<T2> destinationType, String name) { return new TypePair<T1, T2>(sourceType, destinationType, name); } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override public final int hashCode() { return hashCode; } @Override public String toString() { String str = sourceType.getName() + " to " + destinationType.getName(); if (name != null) str += " as " + name; return str; } Class<D> getDestinationType() { return destinationType; } Class<S> getSourceType() { return sourceType; } private int computeHashCode() { final int prime = 31; int result = 1; result = prime * result + sourceType.hashCode(); result = prime * result + destinationType.hashCode(); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } }
if (other == this) return true; if (!(other instanceof TypePair<?, ?>)) return false; TypePair<?, ?> otherPair = (TypePair<?, ?>) other; if (name == null) { if (otherPair.name != null) return false; } else if (!name.equals(otherPair.name)) return false; return sourceType.equals(otherPair.sourceType) && destinationType.equals(otherPair.destinationType);
468
144
612
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/TypeResolvingList.java
TypeResolvingList
addAll
class TypeResolvingList<T> extends AbstractList<T> { private final Map<T, Class<?>> elements = new CopyOnWriteLinkedHashMap<T, Class<?>>(); private final Class<? super T> valueAccessorType; public TypeResolvingList(Class<? super T> valueAccessorType) { this.valueAccessorType = valueAccessorType; } @Override public void add(int index, T element) { addElement(element); } @Override public int size() { return elements.size(); } @Override public boolean add(T element) { return addElement(element); } @Override public T get(int index) { Iterator<T> iterator = elements.keySet().iterator(); for (int i = 0; i < index; i++) { iterator.next(); } return iterator.next(); } @Override public boolean addAll(Collection<? extends T> c) {<FILL_FUNCTION_BODY>} @Override public boolean addAll(int index, Collection<? extends T> c) { throw new UnsupportedOperationException(); } @Override public void clear() { elements.clear(); } @Override public T remove(int index) { T element = get(index); elements.remove(element); return element; } @Override public boolean remove(Object o) { elements.remove(o); return true; } @Override public boolean removeAll(Collection<?> c) { for (Object e : c) { @SuppressWarnings("unchecked") T t = (T) e; elements.remove(t); } return true; } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public T set(int index, T element) { throw new UnsupportedOperationException(); } @Override public List<T> subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException(); } private boolean addElement(T element) { Assert.notNull(element, "element"); Class<?> typeArgument = TypeResolver.resolveRawArgument(valueAccessorType, element.getClass()); if (typeArgument == null) { throw new IllegalArgumentException("Must declare source type argument <T> for the " + valueAccessorType.getSimpleName()); } elements.put(element, typeArgument); return true; } public T first(Class<?> type) { for (Map.Entry<T, Class<?>> entry : elements.entrySet()) if (entry.getValue().isAssignableFrom(type)) return entry.getKey(); return null; } }
boolean changed = false; for (T e : c) { changed = addElement(e) || changed; } return changed;
851
48
899
<methods>public boolean add(T) ,public void add(int, T) ,public boolean addAll(int, Collection<? extends T>) ,public void clear() ,public boolean equals(java.lang.Object) ,public abstract T get(int) ,public int hashCode() ,public int indexOf(java.lang.Object) ,public Iterator<T> iterator() ,public int lastIndexOf(java.lang.Object) ,public ListIterator<T> listIterator() ,public ListIterator<T> listIterator(int) ,public T remove(int) ,public T set(int, T) ,public List<T> subList(int, int) <variables>protected transient int modCount
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/ArrayConverter.java
ArrayConverter
createDestination
class ArrayConverter implements ConditionalConverter<Object, Object> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Iterables.isIterable(sourceType) && destinationType.isArray() ? MatchResult.FULL : MatchResult.NONE; } @Override public Object convert(MappingContext<Object, Object> context) { Object source = context.getSource(); if (source == null) return null; boolean destinationProvided = context.getDestination() != null; Object destination = createDestination(context); Class<?> elementType = getElementType(context); int index = 0; for (Iterator<Object> iterator = Iterables.iterator(source); iterator.hasNext(); index++) { Object sourceElement = iterator.next(); Object element = null; if (destinationProvided) element = Iterables.getElement(destination, index); if (sourceElement != null) { MappingContext<?, ?> elementContext = element == null ? context.create(sourceElement, elementType) : context.create(sourceElement, element); element = context.getMappingEngine().map(elementContext); } Array.set(destination, index, element); } return destination; } @SuppressWarnings("all") private Object createDestination(MappingContext<Object, Object> context) {<FILL_FUNCTION_BODY>} private Class<?> getElementType(MappingContext<Object, Object> context) { if (context.getGenericDestinationType() instanceof GenericArrayType) return Types.rawTypeFor(context.getGenericDestinationType()) .getComponentType(); return context.getDestinationType().getComponentType(); } }
int sourceLength = Iterables.getLength(context.getSource()); int destinationLength = context.getDestination() != null ? Iterables.getLength(context.getDestination()) : 0; int newLength = Math.max(sourceLength, destinationLength); Object originalDestination = context.getDestination(); Class<?> destType = context.getDestinationType(); Object destination = Array.newInstance(destType.isArray() ? destType.getComponentType() : destType, newLength); if (originalDestination != null) System.arraycopy(originalDestination, 0, destination, 0, destinationLength); return destination;
507
178
685
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/AssignableConverter.java
AssignableConverter
convert
class AssignableConverter implements ConditionalConverter<Object, Object> { public Object convert(MappingContext<Object, Object> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return destinationType.isAssignableFrom(sourceType) ? MatchResult.FULL : MatchResult.NONE; } }
MappingContextImpl<Object, Object> contextImpl = (MappingContextImpl<Object, Object>) context; return (!contextImpl.isProvidedDestination() && context.getDestination() != null) ? context.getDestination() : context.getSource();
106
69
175
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/BooleanConverter.java
BooleanConverter
convert
class BooleanConverter implements ConditionalConverter<Object, Boolean> { private static final String[] TRUE_STRINGS = { "true", "yes", "y", "on", "1" }; private static final String[] FALSE_STRINGSS = { "false", "no", "n", "off", "0" }; public Boolean convert(MappingContext<Object, Boolean> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { boolean destMatch = destinationType == Boolean.class || destinationType == Boolean.TYPE; return destMatch ? sourceType == Boolean.class || sourceType == Boolean.TYPE ? MatchResult.FULL : MatchResult.PARTIAL : MatchResult.NONE; } }
Object source = context.getSource(); if (source == null) return null; String stringValue = source.toString().toLowerCase(); if (stringValue.length() == 0) return null; for (int i = 0; i < TRUE_STRINGS.length; i++) if (TRUE_STRINGS[i].equals(stringValue)) return Boolean.TRUE; for (int i = 0; i < FALSE_STRINGSS.length; i++) if (FALSE_STRINGSS[i].equals(stringValue)) return Boolean.FALSE; throw new Errors().errorMapping(context.getSource(), context.getDestinationType()) .toMappingException();
200
197
397
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/CalendarConverter.java
CalendarConverter
convert
class CalendarConverter implements ConditionalConverter<Object, Object> { private static DatatypeFactory dataTypeFactory; private static DatatypeFactory getDataTypeFactory() { if (dataTypeFactory == null) { try { dataTypeFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new Errors().addMessage(e, "Failed to create DataTypeFactory required for XMLGregorianCalendar conversion") .toMappingException(); } } return dataTypeFactory; } public Object convert(MappingContext<Object, Object> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return (Calendar.class.isAssignableFrom(destinationType) || destinationType == XMLGregorianCalendar.class) && (Date.class.isAssignableFrom(sourceType) || Calendar.class.isAssignableFrom(sourceType) || sourceType == XMLGregorianCalendar.class || sourceType == Long.class || sourceType == Long.TYPE) ? MatchResult.FULL : MatchResult.NONE; } }
Object source = context.getSource(); if (source == null) return null; Class<?> destinationType = context.getDestinationType(); if (!Calendar.class.isAssignableFrom(destinationType) && !destinationType.equals(XMLGregorianCalendar.class)) throw new Errors().errorMapping(source, destinationType).toMappingException(); GregorianCalendar calendar = new GregorianCalendar(); if (source instanceof Date) calendar.setTimeInMillis(((Date) source).getTime()); else if (source instanceof Calendar) { Calendar cal = (Calendar) source; calendar.setTimeZone(cal.getTimeZone()); calendar.setTimeInMillis(cal.getTime().getTime()); } else if (source instanceof XMLGregorianCalendar) { XMLGregorianCalendar xmlCal = (XMLGregorianCalendar) source; GregorianCalendar cal = xmlCal.toGregorianCalendar(); calendar.setTimeZone(cal.getTimeZone()); calendar.setTimeInMillis(cal.getTime().getTime()); } else if (source instanceof Long) calendar.setTimeInMillis(((Long) source).longValue()); return destinationType.equals(XMLGregorianCalendar.class) ? getDataTypeFactory().newXMLGregorianCalendar( calendar) : calendar;
326
378
704
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/CharacterConverter.java
CharacterConverter
convert
class CharacterConverter implements ConditionalConverter<Object, Character> { public Character convert(MappingContext<Object, Character> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { boolean destMatch = destinationType == Character.class || destinationType == Character.TYPE; return destMatch ? sourceType == Character.class || sourceType == Character.TYPE ? MatchResult.FULL : MatchResult.PARTIAL : MatchResult.NONE; } }
Object source = context.getSource(); if (source == null) return null; String stringValue = source.toString(); if (stringValue.length() == 0) return null; return Character.valueOf(stringValue.charAt(0));
141
79
220
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/ConverterStore.java
ConverterStore
replaceConverter
class ConverterStore { private static final ConditionalConverter<?, ?>[] DEFAULT_CONVERTERS = new ConditionalConverter<?, ?>[] { new ArrayConverter(), new MergingCollectionConverter(), new MapConverter(), new FromOptionalConverter(),new OptionalConverter(), new ToOptionalConverter(), new AssignableConverter(), new StringConverter(), new EnumConverter(), new NumberConverter(), new BooleanConverter(), new CharacterConverter(), new DateConverter(), new CalendarConverter(), new UuidConverter(), }; private final List<ConditionalConverter<?, ?>> converters; public ConverterStore() { this(new CopyOnWriteArrayList<>(DEFAULT_CONVERTERS)); } ConverterStore(List<ConditionalConverter<?, ?>> converters) { this.converters = converters; } /** * Returns the first converter that supports converting from {@code sourceType} to * {@code destinationType}. It will select converter that was full match first. * Then it will select {@code MatchResult.PARTIAL} if there is no full match converter * exists. */ @SuppressWarnings("unchecked") public <S, D> ConditionalConverter<S, D> getFirstSupported(Class<?> sourceType, Class<?> destinationType) { ConditionalConverter<S, D> firstPartialMatchConverter = null; for (ConditionalConverter<?, ?> converter : converters) { MatchResult matchResult = converter.match(sourceType, destinationType); if (matchResult == MatchResult.FULL) return (ConditionalConverter<S, D>) converter; if (firstPartialMatchConverter == null && matchResult == MatchResult.PARTIAL) firstPartialMatchConverter = (ConditionalConverter<S, D>) converter; } return firstPartialMatchConverter; } public List<ConditionalConverter<?, ?>> getConverters() { return converters; } public ConverterStore removeConverter(Class<? extends ConditionalConverter<?, ?>> converterClass) { ConditionalConverter<?, ?> matchConverter = getConverterByType(converterClass); if (matchConverter != null) converters.remove(matchConverter); return this; } public boolean hasConverter(Class<? extends ConditionalConverter<?, ?>> converterClass) { return getConverterByType(converterClass) != null; } public ConverterStore addConverter(ConditionalConverter<?, ?> converter) { converters.add(converter); return this; } /** * Replaces the converter of specified class with the given instance. * <p> * If the converter to replace is not found than no replace is performed, * the converters are left untouched. * * @param converterClass to replace * @param converter instance with which to replace it * @return converter store itself */ public ConverterStore replaceConverter(Class<? extends ConditionalConverter<?, ?>> converterClass, ConditionalConverter<?, ?> converter) {<FILL_FUNCTION_BODY>} private ConditionalConverter<?, ?> getConverterByType(Class<? extends ConditionalConverter<?, ?>> converterClass) { for (ConditionalConverter<?, ?> converter : converters) { if (converter.getClass().equals(converterClass)) return converter; } return null; } }
ConditionalConverter<?, ?> matchConverter = getConverterByType(converterClass); if (matchConverter != null) { int idx = converters.indexOf(matchConverter); if (idx != -1) { // because of concurrency do not use List#set(int, T obj) to avoid to replace a wrong converter converters.remove(matchConverter); converters.add(idx, converter); } } return this;
937
128
1,065
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/DateConverter.java
DateConverter
convert
class DateConverter implements ConditionalConverter<Object, Date> { public Date convert(MappingContext<Object, Date> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Date.class.isAssignableFrom(destinationType) && (Date.class.isAssignableFrom(sourceType) || Calendar.class.isAssignableFrom(sourceType) || sourceType == XMLGregorianCalendar.class || sourceType == Long.class || sourceType == Long.TYPE || sourceType == String.class) ? MatchResult.FULL : MatchResult.NONE; } Date dateFor(long source, Class<?> destinationType) { if (destinationType.equals(Date.class)) return new Date(source); if (destinationType.equals(java.sql.Date.class)) return new java.sql.Date(source); if (destinationType.equals(Time.class)) return new Time(source); if (destinationType.equals(Timestamp.class)) return new Timestamp(source); throw new Errors().errorMapping(source, destinationType).toMappingException(); } Date dateFor(String source, Class<?> destinationType) { String sourceString = toString().trim(); if (sourceString.length() == 0) throw new Errors().errorMapping(source, destinationType).toMappingException(); if (destinationType.equals(java.sql.Date.class)) { try { return java.sql.Date.valueOf(source); } catch (IllegalArgumentException e) { throw new Errors().addMessage( "String must be in JDBC format [yyyy-MM-dd] to create a java.sql.Date") .toMappingException(); } } if (destinationType.equals(Time.class)) { try { return Time.valueOf(source); } catch (IllegalArgumentException e) { throw new Errors().addMessage( "String must be in JDBC format [HH:mm:ss] to create a java.sql.Time") .toMappingException(); } } if (destinationType.equals(Timestamp.class)) { try { return Timestamp.valueOf(source); } catch (IllegalArgumentException e) { throw new Errors().addMessage( "String must be in JDBC format [yyyy-MM-dd HH:mm:ss.fffffffff] " + "to create a java.sql.Timestamp").toMappingException(); } } if (destinationType.equals(java.util.Date.class)) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.parse(source); } catch (ParseException e) { throw new Errors().addMessage( "String must be in DATE format [yyyy-MM-dd] to create a java.util.Date") .toMappingException(); } } throw new Errors().errorMapping(source, destinationType).toMappingException(); } }
Object source = context.getSource(); if (source == null) return null; Class<?> destinationType = context.getDestinationType(); if (source instanceof Date) return dateFor(((Date) source).getTime(), destinationType); if (source instanceof Calendar) return dateFor(((Calendar) source).getTimeInMillis(), destinationType); if (source instanceof XMLGregorianCalendar) return dateFor(((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis(), destinationType); if (source instanceof Long) return dateFor(((Long) source).longValue(), destinationType); return dateFor(source.toString(), context.getDestinationType());
879
203
1,082
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/EnumConverter.java
EnumConverter
convert
class EnumConverter implements ConditionalConverter<Object, Enum<?>> { @SuppressWarnings({ "unchecked", "rawtypes" }) public Enum<?> convert(MappingContext<Object, Enum<?>> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return isEnum(destinationType) && (isEnum(sourceType) || sourceType == String.class) ? MatchResult.FULL : MatchResult.NONE; } private boolean isEnum( Class<?> type ) { return type.isAnonymousClass() ? isEnum( type.getSuperclass() ) : type.isEnum(); } }
Object source = context.getSource(); if (source == null) return null; String name = source.getClass() == String.class ? (String) source : ((Enum<?>) source).name(); if (name != null) try { return Enum.valueOf((Class) context.getDestinationType(), name); } catch (IllegalArgumentException ignore) { } return null;
197
125
322
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/FromOptionalConverter.java
FromOptionalConverter
convert
class FromOptionalConverter implements ConditionalConverter<Optional<Object>, Object> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return (Optional.class.equals(sourceType) && !Optional.class.equals(destinationType)) ? MatchResult.FULL : MatchResult.NONE; } @Override public Object convert(MappingContext<Optional<Object>, Object> mappingContext) {<FILL_FUNCTION_BODY>} }
if (mappingContext.getSource() == null || !mappingContext.getSource().isPresent()) { return null; } MappingContext<Object, Object> propertyContext = mappingContext.create( mappingContext.getSource().get(), mappingContext.getDestinationType()); return mappingContext.getMappingEngine().map(propertyContext);
128
87
215
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/MapConverter.java
MapConverter
convert
class MapConverter implements ConditionalConverter<Map<?, ?>, Map<Object, Object>> { public Map<Object, Object> convert(MappingContext<Map<?, ?>, Map<Object, Object>> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Map.class.isAssignableFrom(sourceType) && Map.class.isAssignableFrom(destinationType) ? MatchResult.FULL : MatchResult.NONE; } protected Map<Object, Object> createDestination( MappingContext<Map<?, ?>, Map<Object, Object>> context) { if (!context.getDestinationType().isInterface()) return context.getMappingEngine().createDestination(context); if (SortedMap.class.isAssignableFrom(context.getDestinationType())) return new TreeMap<Object, Object>(); return new HashMap<Object, Object>(); } }
Map<?, ?> source = context.getSource(); if (source == null) return null; Map<Object, Object> destination = context.getDestination() == null ? createDestination(context) : context.getDestination(); Mapping mapping = context.getMapping(); Type keyElementType = Object.class; Type valueElementType = Object.class; if (mapping instanceof PropertyMapping) { PropertyInfo destInfo = mapping.getLastDestinationProperty(); Class<?>[] elementTypes = TypeResolver.resolveRawArguments(destInfo.getGenericType(), Map.class); if (elementTypes != null && elementTypes.length == 2) { keyElementType = elementTypes[0] == Unknown.class ? Object.class : elementTypes[0]; valueElementType = elementTypes[1] == Unknown.class ? Object.class : elementTypes[1]; } } else if (context.getGenericDestinationType() instanceof ParameterizedType) { Type[] elementTypes = ((ParameterizedType) context.getGenericDestinationType()).getActualTypeArguments(); keyElementType = elementTypes[0]; valueElementType = elementTypes[1]; } for (Entry<?, ?> entry : source.entrySet()) { Object key = null; if (entry.getKey() != null) { MappingContext<?, ?> keyContext = context.create(entry.getKey(), keyElementType); key = context.getMappingEngine().map(keyContext); } Object value = null; if (entry.getValue() != null) { MappingContext<?, ?> valueContext = context.create(entry.getValue(), valueElementType); value = context.getMappingEngine().map(valueContext); } destination.put(key, value); } return destination;
267
503
770
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/MergingCollectionConverter.java
MergingCollectionConverter
convert
class MergingCollectionConverter implements ConditionalConverter<Object, Collection<Object>> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Iterables.isIterable(sourceType) && Collection.class.isAssignableFrom(destinationType) ? MatchResult.FULL : MatchResult.NONE; } @Override public Collection<Object> convert(MappingContext<Object, Collection<Object>> context) {<FILL_FUNCTION_BODY>} }
Object source = context.getSource(); if (source == null) return null; int sourceLength = Iterables.getLength(source); Collection<Object> originalDestination = context.getDestination(); Collection<Object> destination = MappingContextHelper.createCollection(context); Class<?> elementType = MappingContextHelper.resolveDestinationGenericType(context); int index = 0; for (Iterator<Object> iterator = Iterables.iterator(source); iterator.hasNext(); index++) { Object sourceElement = iterator.next(); Object element = null; if (originalDestination != null) element = Iterables.getElement(originalDestination, index); if (sourceElement != null) { MappingContext<?, ?> elementContext = element == null ? context.create(sourceElement, elementType) : context.create(sourceElement, element); element = context.getMappingEngine().map(elementContext); } destination.add(element); } for (Object element : Iterables.subIterable(originalDestination, sourceLength)) destination.add(element); return destination;
140
320
460
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/NonMergingCollectionConverter.java
NonMergingCollectionConverter
convert
class NonMergingCollectionConverter implements ConditionalConverter<Object, Collection<Object>> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Iterables.isIterable(sourceType) && Collection.class.isAssignableFrom(destinationType) ? MatchResult.FULL : MatchResult.NONE; } @Override public Collection<Object> convert(MappingContext<Object, Collection<Object>> context) {<FILL_FUNCTION_BODY>} }
Object source = context.getSource(); if (source == null) return null; Collection<Object> originalDestination = context.getDestination(); Collection<Object> destination = MappingContextHelper.createCollection(context); Class<?> elementType = MappingContextHelper.resolveDestinationGenericType(context); int index = 0; for (Iterator<Object> iterator = Iterables.iterator(source); iterator.hasNext(); index++) { Object sourceElement = iterator.next(); Object element = null; if (originalDestination != null) element = Iterables.getElement(originalDestination, index); if (sourceElement != null) { MappingContext<?, ?> elementContext = element == null ? context.create(sourceElement, elementType) : context.create(sourceElement, element); element = context.getMappingEngine().map(elementContext); } destination.add(element); } return destination;
132
249
381
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/NumberConverter.java
NumberConverter
numberFor
class NumberConverter implements ConditionalConverter<Object, Number> { public Number convert(MappingContext<Object, Number> context) { Object source = context.getSource(); if (source == null) return null; Class<?> destinationType = Primitives.wrapperFor(context.getDestinationType()); if (source instanceof Number) return numberFor((Number) source, destinationType); if (source instanceof Boolean) return numberFor(((Boolean) source).booleanValue() ? 1 : 0, destinationType); if (source instanceof Date && Long.class.equals(destinationType)) return Long.valueOf(((Date) source).getTime()); if (source instanceof Calendar && Long.class.equals(destinationType)) return Long.valueOf(((Calendar) source).getTime().getTime()); if (source instanceof XMLGregorianCalendar && Long.class.equals(destinationType)) return ((XMLGregorianCalendar) source).toGregorianCalendar().getTimeInMillis(); return numberFor(source.toString(), destinationType); } public MatchResult match(Class<?> sourceType, Class<?> destinationType) { boolean destMatch = Number.class.isAssignableFrom(Primitives.wrapperFor(destinationType)); if (destMatch) { return Number.class.isAssignableFrom(Primitives.wrapperFor(sourceType)) || sourceType == Boolean.class || sourceType == Boolean.TYPE || sourceType == String.class || Date.class.isAssignableFrom(sourceType) || Calendar.class.isAssignableFrom(sourceType) || XMLGregorianCalendar.class.isAssignableFrom(sourceType) ? MatchResult.FULL : MatchResult.PARTIAL; } else return MatchResult.NONE; } /** * Creates a Number for the {@code source} and {@code destinationType}. */ Number numberFor(Number source, Class<?> destinationType) {<FILL_FUNCTION_BODY>} /** * Creates a Number for the {@code source} and {@code destinationType}. */ Number numberFor(String source, Class<?> destinationType) { String sourceString = source.trim(); if (sourceString.length() == 0) return null; try { if (destinationType.equals(Byte.class)) return Byte.valueOf(source); if (destinationType.equals(Short.class)) return Short.valueOf(source); if (destinationType.equals(Integer.class)) return Integer.valueOf(source); if (destinationType.equals(Long.class)) return Long.valueOf(source); if (destinationType.equals(Float.class)) return Float.valueOf(source); if (destinationType.equals(Double.class)) return Double.valueOf(source); if (destinationType.equals(BigDecimal.class)) return new BigDecimal(source); if (destinationType.equals(BigInteger.class)) return new BigInteger(source); } catch (Exception e) { throw new Errors().errorMapping(source, destinationType, e).toMappingException(); } throw new Errors().errorMapping(source, destinationType).toMappingException(); } }
if (destinationType.equals(source.getClass())) return source; if (destinationType.equals(Byte.class)) { long longValue = source.longValue(); if (longValue > Byte.MAX_VALUE) throw new Errors().errorTooLarge(source, destinationType).toMappingException(); if (longValue < Byte.MIN_VALUE) throw new Errors().errorTooSmall(source, destinationType).toMappingException(); return Byte.valueOf(source.byteValue()); } if (destinationType.equals(Short.class)) { long longValue = source.longValue(); if (longValue > Short.MAX_VALUE) throw new Errors().errorTooLarge(source, destinationType).toMappingException(); if (longValue < Short.MIN_VALUE) throw new Errors().errorTooSmall(source, destinationType).toMappingException(); return Short.valueOf(source.shortValue()); } if (destinationType.equals(Integer.class)) { long longValue = source.longValue(); if (longValue > Integer.MAX_VALUE) throw new Errors().errorTooLarge(source, destinationType).toMappingException(); if (longValue < Integer.MIN_VALUE) throw new Errors().errorTooSmall(source, destinationType).toMappingException(); return Integer.valueOf(source.intValue()); } if (destinationType.equals(Long.class)) return Long.valueOf(source.longValue()); if (destinationType.equals(Float.class)) { if (source.doubleValue() > Float.MAX_VALUE) throw new Errors().errorTooLarge(source, destinationType).toMappingException(); return Float.valueOf(source.floatValue()); } if (destinationType.equals(Double.class)) return Double.valueOf(source.doubleValue()); if (destinationType.equals(BigDecimal.class)) { if (source instanceof Float || source instanceof Double) return new BigDecimal(source.toString()); else if (source instanceof BigInteger) return new BigDecimal((BigInteger) source); else return BigDecimal.valueOf(source.longValue()); } if (destinationType.equals(BigInteger.class)) { if (source instanceof BigDecimal) return ((BigDecimal) source).toBigInteger(); else return BigInteger.valueOf(source.longValue()); } throw new Errors().errorMapping(source, destinationType).toMappingException();
902
711
1,613
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/OptionalConverter.java
OptionalConverter
convert
class OptionalConverter implements ConditionalConverter<Optional<?>, Optional<?>> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return (Optional.class.equals(sourceType) && Optional.class.equals(destinationType)) ? MatchResult.FULL : MatchResult.NONE; } @Override @SuppressWarnings("all") public Optional<?> convert(MappingContext<Optional<?>, Optional<?>> mappingContext) {<FILL_FUNCTION_BODY>} private Class<?> getElementType(MappingContext<Optional<?>, Optional<?>> mappingContext) { Mapping mapping = mappingContext.getMapping(); if (mapping instanceof PropertyMapping) { PropertyInfo destInfo = mapping.getLastDestinationProperty(); Class<?> elementType = TypeResolver.resolveRawArgument(destInfo.getGenericType(), destInfo.getInitialType()); return elementType == TypeResolver.Unknown.class ? Object.class : elementType; } else if (mappingContext.getGenericDestinationType() instanceof ParameterizedType) { return Types.rawTypeFor(((ParameterizedType) mappingContext.getGenericDestinationType()).getActualTypeArguments()[0]); } return Object.class; } }
Class<?> optionalType = getElementType(mappingContext); Optional<?> source = mappingContext.getSource(); if (source == null) { return null; } else if (source.isPresent()) { MappingContext<?, ?> optionalContext = mappingContext.create(source.get(), optionalType); return Optional.ofNullable(mappingContext.getMappingEngine().map(optionalContext)); } else { return Optional.empty(); }
331
118
449
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/StringConverter.java
StringConverter
convert
class StringConverter implements ConditionalConverter<Object, String> { public String convert(MappingContext<Object, String> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return destinationType == String.class ? sourceType == String.class ? MatchResult.FULL : MatchResult.PARTIAL : MatchResult.NONE; } }
Object source = context.getSource(); if (source == null) return null; Class<?> sourceType = context.getSourceType(); return sourceType.isArray() && sourceType.getComponentType() == Character.TYPE || sourceType.getComponentType() == Character.class ? String.valueOf((char[]) source) : source.toString();
114
104
218
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/ToOptionalConverter.java
ToOptionalConverter
convert
class ToOptionalConverter implements ConditionalConverter<Object, Optional<Object>> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return (!Optional.class.equals(sourceType) && Optional.class.equals(destinationType)) ? MatchResult.FULL : MatchResult.NONE; } @Override public Optional<Object> convert(MappingContext<Object, Optional<Object>> mappingContext) {<FILL_FUNCTION_BODY>} }
if (mappingContext.getSource() == null) { return Optional.empty(); } MappingContext<?, ?> propertyContext = mappingContext.create( mappingContext.getSource(), MappingContextHelper.resolveDestinationGenericType(mappingContext)); Object destination = mappingContext.getMappingEngine().map(propertyContext); return Optional.ofNullable(destination);
138
104
242
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/converter/UuidConverter.java
UuidConverter
convert
class UuidConverter implements ConditionalConverter<Object, UUID> { public UUID convert(MappingContext<Object, UUID> context) {<FILL_FUNCTION_BODY>} public MatchResult match(Class<?> sourceType, Class<?> destinationType) { boolean destMatch = destinationType == UUID.class; return destMatch ? isCharArray(sourceType) || sourceType == String.class ? MatchResult.FULL : MatchResult.PARTIAL : MatchResult.NONE; } private boolean isCharArray(Class<?> sourceType) { return sourceType.isArray() && (sourceType.getComponentType() == Character.TYPE || sourceType.getComponentType() == Character.class); } }
Object source = context.getSource(); if (source == null) { return null; } Class<?> sourceType = context.getSourceType(); if (isCharArray(sourceType)) { return UUID.fromString(new String((char[]) source)); } return UUID.fromString(source.toString());
187
89
276
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Assert.java
Assert
notNull
class Assert { private Assert() { } public static void isNull(Object object) { if (object != null) throw new IllegalArgumentException(); } public static void isNull(Object object, String message, Object... args) { if (object != null) throw new IllegalArgumentException(String.format(message, args)); } public static void isTrue(boolean expression) { if (!expression) throw new IllegalArgumentException(); } public static void isTrue(boolean expression, String errorMessage, Object... args) { if (!expression) throw new IllegalArgumentException(String.format(errorMessage, args)); } public static <T> T notNull(T reference) {<FILL_FUNCTION_BODY>} public static <T> T notNull(T reference, String parameterName) { if (reference == null) throw new IllegalArgumentException(parameterName + " cannot be null"); return reference; } public static void state(boolean expression) { if (!expression) throw new IllegalStateException(); } public static void state(boolean expression, String errorMessage, Object... args) { if (!expression) throw new IllegalStateException(String.format(errorMessage, args)); } }
if (reference == null) throw new IllegalArgumentException(); return reference;
364
27
391
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/CopyOnWriteLinkedHashMap.java
CopyOnWriteLinkedHashMap
put
class CopyOnWriteLinkedHashMap<K, V> implements Map<K, V> { private volatile Map<K, V> map; public CopyOnWriteLinkedHashMap() { map = new LinkedHashMap<K, V>(); } public CopyOnWriteLinkedHashMap(Map<K, V> data) { map = new LinkedHashMap<K, V>(data); } public synchronized void clear() { map = new LinkedHashMap<K, V>(); } public boolean containsKey(Object key) { return map.containsKey(key); } public boolean containsValue(Object value) { return map.containsValue(value); } public Set<Entry<K, V>> entrySet() { return map.entrySet(); } public V get(Object key) { return map.get(key); } public boolean isEmpty() { return map.isEmpty(); } public Set<K> keySet() { return map.keySet(); } public synchronized V put(K key, V value) {<FILL_FUNCTION_BODY>} public synchronized void putAll(Map<? extends K, ? extends V> newData) { Map<K, V> newMap = new LinkedHashMap<K, V>(map); newMap.putAll(newData); map = newMap; } public synchronized V remove(Object key) { Map<K, V> newMap = new LinkedHashMap<K, V>(map); V previous = newMap.remove(key); map = newMap; return previous; } public int size() { return map.size(); } public Collection<V> values() { return map.values(); } }
Map<K, V> newMap = new LinkedHashMap<K, V>(map); V previous = newMap.put(key, value); map = newMap; return previous;
473
52
525
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Iterables.java
Iterables
getElement
class Iterables { private Iterables() { } /** * Returns whether a given type is a iterable or not. * * @param type the type * @return {@code true} if the type is an iterable, otherwise, return {@code false} . */ public static boolean isIterable(Class<?> type) { return type.isArray() || Collection.class.isAssignableFrom(type); } /** * Gets the length of an iterable. * * @param iterable the iterable * @return the length of the iterable */ @SuppressWarnings("unchecked") public static int getLength(Object iterable) { Assert.state(isIterable(iterable.getClass())); return iterable.getClass().isArray() ? Array.getLength(iterable) : ((Collection<Object>) iterable).size(); } /** * Creates a iterator from given iterable. * * @param iterable the iterable * @return a iterator */ @SuppressWarnings("unchecked") public static Iterator<Object> iterator(Object iterable) { Assert.state(isIterable(iterable.getClass())); return iterable.getClass().isArray() ? new ArrayIterator(iterable) : ((Iterable<Object>) iterable).iterator(); } /** * Gets the element from an iterable with given index. * * @param iterable the iterable * @param index the index * @return null if the iterable doesn't have the element at index, otherwise, return the element */ @SuppressWarnings("unchecked") public static Object getElement(Object iterable, int index) {<FILL_FUNCTION_BODY>} /** * Gets the element from an array with given index. * * @param array the array * @param index the index * @return null if the array doesn't have the element at index, otherwise, return the element */ public static Object getElementFromArrary(Object array, int index) { try { return Array.get(array, index); } catch (ArrayIndexOutOfBoundsException e) { return null; } } /** * Gets the element from a collection with given index. * * @param collection the collection * @param index the index * @return null if the collection doesn't have the element at index, otherwise, return the element */ public static Object getElementFromCollection(Collection<Object> collection, int index) { if (collection.size() < index + 1) return null; if (collection instanceof List) return ((List<Object>) collection).get(index); Iterator<Object> iterator = collection.iterator(); for (int i = 0; i < index; i++) { iterator.next(); } return iterator.next(); } /** * Creates sub iterable started from {@code fromIndex}. * * @param iterable the iterable * @param fromIndex the index start from * @return a iterable */ public static Iterable<Object> subIterable(Object iterable, int fromIndex) { if (iterable == null || getLength(iterable) < fromIndex) return Collections.emptyList(); final Iterator<Object> iterator = iterator(iterable); for (int i = 0; i < fromIndex; i++) iterator.next(); return new Iterable<Object>() { @Override public Iterator<Object> iterator() { return iterator; } }; } }
if (iterable.getClass().isArray()) return getElementFromArrary(iterable, index); if (iterable instanceof Collection) return getElementFromCollection((Collection<Object>) iterable, index); return null;
1,055
70
1,125
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/JavaVersions.java
JavaVersions
getMajorVersion
class JavaVersions { private JavaVersions() { } public static int getMajorVersion() {<FILL_FUNCTION_BODY>} }
String version = System.getProperty("java.version"); if(version.startsWith("1.")) { version = version.substring(2, 3); } else { int dot = version.indexOf("."); if (dot != -1) { version = version.substring(0, dot); } } return Integer.parseInt(version);
43
100
143
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Lists.java
Lists
from
class Lists { private Lists() { } public static <T> List<T> from(Iterator<T> iterator) {<FILL_FUNCTION_BODY>} public static <T> List<T> from(Set<Map.Entry<T, ?>> entries) { List<T> list = new ArrayList<T>(); for (Map.Entry<T, ?> entry : entries) list.add(entry.getKey()); return list; } }
List<T> list = new ArrayList<T>(); while (iterator.hasNext()) list.add(iterator.next()); return list;
139
46
185
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/MappingContextHelper.java
MappingContextHelper
resolveDestinationGenericType
class MappingContextHelper { private MappingContextHelper() { } /** * Creates a collection based on the destination type. * * <ul> * <li>Creates {@code TreeSet} for {@code SortedSet}</li> * <li>Creates {@code HashSet} for {@code Set}</li> * <li>Creates {@code ArrayList} for {@code List}</li> * </ul> * * @param context the mapping context * @param <T> the element type of the collection * @return an empty collection */ public static <T> Collection<T> createCollection(MappingContext<?, Collection<T>> context) { if (context.getDestinationType().isInterface()) if (SortedSet.class.isAssignableFrom(context.getDestinationType())) return new TreeSet<T>(); else if (Set.class.isAssignableFrom(context.getDestinationType())) return new HashSet<T>(); else return new ArrayList<T>(); return context.getMappingEngine().createDestination(context); } public static Class<?> resolveDestinationGenericType(MappingContext<?, ?> context) {<FILL_FUNCTION_BODY>} }
Mapping mapping = context.getMapping(); if (mapping instanceof PropertyMapping) { PropertyInfo destInfo = mapping.getLastDestinationProperty(); Class<?> elementType = TypeResolver.resolveRawArgument(destInfo.getGenericType(), destInfo.getInitialType()); if (elementType != TypeResolver.Unknown.class) return elementType; } if (context.getGenericDestinationType() instanceof ParameterizedType) return Types.rawTypeFor(((ParameterizedType) context.getGenericDestinationType()).getActualTypeArguments()[0]); return Object.class;
357
169
526
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Maps.java
Maps
resolveRawArguments
class Maps { private Maps() { } public static Class<?>[] resolveRawArguments(Type genericType) {<FILL_FUNCTION_BODY>} }
Class<?>[] elementTypes = TypeResolver.resolveRawArguments(genericType, Map.class); if (elementTypes.length == 0) { elementTypes = TypeResolver.resolveRawArguments(TypeResolver.reify(genericType, Map.class), Map.class); } return elementTypes;
53
83
136
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Members.java
Members
methodFor
class Members { private Members() {} public static Method methodFor(Class<?> type, String methodName, Class<?>... parameterTypes) {<FILL_FUNCTION_BODY>} public static Field fieldFor(Class<?> type, String fieldName) { while (type != null) { for (Field field : type.getDeclaredFields()) if (field.getName().equals(fieldName)) return field; type = type.getSuperclass(); } return null; } }
if (type == null) return null; for (Method method : type.getDeclaredMethods()) if (!method.isBridge() && !method.isSynthetic() && method.getName().equals(methodName) && ((parameterTypes == null && method.getParameterTypes().length == 0) || Arrays.equals( method.getParameterTypes(), parameterTypes))) return method; for (Class<?> interfaze : type.getInterfaces()) { Method result = methodFor(interfaze, methodName, parameterTypes); if (result != null) return result; } return methodFor(type.getSuperclass(), methodName, parameterTypes);
135
177
312
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Objects.java
Objects
firstNonNull
class Objects { private Objects() { } public static <T> T firstNonNull(T... objects) { for (T object : objects) if (object != null) return object; return null; } public static <T> T firstNonNull(Callable<T>... callables) {<FILL_FUNCTION_BODY>} public static <T> Callable<T> callable(final T obj) { return new Callable<T>() { @Override public T call() { return obj; } }; } public static <T> T instantiate(Class<T> type) { try { Constructor<T> constructor = type.getDeclaredConstructor(); if (!constructor.isAccessible()) constructor.setAccessible(true); return constructor.newInstance(); } catch (Exception e) { return null; } } }
for (Callable<T> callable : callables) { T obj = callable.call(); if (obj != null) return obj; } return null;
277
58
335
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Primitives.java
Primitives
defaultValueForWrapper
class Primitives { private static Map<Class<?>, Class<?>> primitiveToWrapper; private static Map<Class<?>, Class<?>> wrapperToPrimitive; private static Map<Class<?>, Object> defaultValue; private static Set<String> primitiveWrapperInternalNames; static { primitiveToWrapper = new HashMap<Class<?>, Class<?>>(); primitiveToWrapper.put(Boolean.TYPE, Boolean.class); primitiveToWrapper.put(Character.TYPE, Character.class); primitiveToWrapper.put(Byte.TYPE, Byte.class); primitiveToWrapper.put(Short.TYPE, Short.class); primitiveToWrapper.put(Integer.TYPE, Integer.class); primitiveToWrapper.put(Long.TYPE, Long.class); primitiveToWrapper.put(Float.TYPE, Float.class); primitiveToWrapper.put(Double.TYPE, Double.class); wrapperToPrimitive = new HashMap<Class<?>, Class<?>>(); wrapperToPrimitive.put(Boolean.class, Boolean.TYPE); wrapperToPrimitive.put(Character.class, Character.TYPE); wrapperToPrimitive.put(Byte.class, Byte.TYPE); wrapperToPrimitive.put(Short.class, Short.TYPE); wrapperToPrimitive.put(Integer.class, Integer.TYPE); wrapperToPrimitive.put(Long.class, Long.TYPE); wrapperToPrimitive.put(Float.class, Float.TYPE); wrapperToPrimitive.put(Double.class, Double.TYPE); defaultValue = new HashMap<Class<?>, Object>(); defaultValue.put(Boolean.TYPE, Boolean.FALSE); defaultValue.put(Character.TYPE, Character.valueOf('\u0000')); defaultValue.put(Byte.TYPE, Byte.valueOf((byte) 0)); defaultValue.put(Short.TYPE, Short.valueOf((short) 0)); defaultValue.put(Integer.TYPE, Integer.valueOf(0)); defaultValue.put(Long.TYPE, Long.valueOf(0L)); defaultValue.put(Float.TYPE, Float.valueOf(0.0f)); defaultValue.put(Double.TYPE, Double.valueOf(0.0d)); primitiveWrapperInternalNames = new HashSet<String>(); for (Class<?> wrapper : wrapperToPrimitive.keySet()) primitiveWrapperInternalNames.add(wrapper.getName().replace('.', '/')); } private Primitives() { } /** * Returns the boxed default value for {@code type} if {@code type} is a primitive, else null. */ @SuppressWarnings("unchecked") public static <T> T defaultValue(Class<?> type) { return type.isPrimitive() ? (T) defaultValue.get(type) : null; } /** * Returns the boxed default value for {@code type} if {@code type} is a primitive wrapper. */ @SuppressWarnings("unchecked") public static <T> T defaultValueForWrapper(Class<?> type) {<FILL_FUNCTION_BODY>} /** * Returns true if {@code type} is a primitive or a primitive wrapper. */ public static boolean isPrimitive(Class<?> type) { return type.isPrimitive() || isPrimitiveWrapper(type); } /** * Returns true if {@code type} is a primitive wrapper. */ public static boolean isPrimitiveWrapper(Class<?> type) { return wrapperToPrimitive.containsKey(type); } /** * Returns whether the {@code name} is an internal class name of a primitive wrapper. */ public static boolean isPrimitiveWrapperInternalName(String name) { return primitiveWrapperInternalNames.contains(name); } /** * Returns the primitive type for the {@code wrapper}, else returns {@code null} if * {@code wrapper} is not a primitive wrapper. */ public static Class<?> primitiveFor(Class<?> wrapper) { return wrapperToPrimitive.get(wrapper); } /** * Returns the primitive wrapper for {@code type}, else returns {@code type} if {@code type} is * not a primitive. */ public static Class<?> wrapperFor(Class<?> type) { return type.isPrimitive() ? primitiveToWrapper.get(type) : type; } }
Class<?> primiviteType = isPrimitiveWrapper(type) ? primitiveFor(type) : type; return primiviteType == null ? null : (T) defaultValue.get(primiviteType);
1,217
58
1,275
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Strings.java
Strings
joinWithFirstType
class Strings { private Strings() { } /** * Returns the joined {@code properties} with a <code>.</code> delimiter, including a trailing * delimiter. */ public static String join(List<? extends PropertyInfo> properties) { StringBuilder sb = new StringBuilder(); for (PropertyInfo info : properties) sb.append(info.getName()).append('.'); return sb.toString(); } /** * Returns a String containing the members of the {@code properties} joined on a <code>/</code> * delimiter. */ public static String joinMembers(List<? extends PropertyInfo> properties) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < properties.size(); i++) { PropertyInfo info = properties.get(i); if (i > 0) builder.append("/"); builder.append(Types.toString(info.getMember())); } return builder.toString(); } public static String joinWithFirstType(List<? extends PropertyInfo> properties) {<FILL_FUNCTION_BODY>} /** * Utility method to take a string and convert it to normal Java variable name capitalization. * This normally means converting the first character from upper case to lower case, but in the * (unusual) special case when there is more than one character and both the first and second * characters are upper case, we leave it alone. * <p> * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL". * * @param name The string to be decapitalized. * @return The decapitalized version of the string. */ public static String decapitalize(String name) { if (name == null || name.length() == 0) return name; if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))) return name; char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return String.valueOf(chars); } }
StringBuilder sb = new StringBuilder(); String delim = ""; for (PropertyInfo info : properties) { sb.append(delim).append(delim.equals("") ? info : info.getName()); delim = "."; } return sb.toString();
632
83
715
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/ToStringBuilder.java
ToStringBuilder
add
class ToStringBuilder { private final Map<String, Object> properties = new LinkedHashMap<String, Object>(); private final String name; public ToStringBuilder(Class<?> type) { this.name = type.getSimpleName(); } public ToStringBuilder add(String name, Object value) {<FILL_FUNCTION_BODY>} @Override public String toString() { return name + properties.toString().replace('{', '[').replace('}', ']'); } static class ArrayWrapper { private final Object[] array; ArrayWrapper(Object array) { this.array = (Object[]) array; } @Override public String toString() { return Arrays.toString(array); } } }
value = value.getClass().isArray() ? new ArrayWrapper(value) : value; if (properties.put(name, value) != null) throw new RuntimeException("Duplicate property: " + name); return this;
204
62
266
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/util/Types.java
Types
isProxied
class Types { private static Class<?> JAVASSIST_PROXY_FACTORY_CLASS; private static Method JAVASSIST_IS_PROXY_CLASS_METHOD; static { try { JAVASSIST_PROXY_FACTORY_CLASS = Types.class.getClassLoader().loadClass( "javassist.util.proxy.ProxyFactory"); JAVASSIST_IS_PROXY_CLASS_METHOD = JAVASSIST_PROXY_FACTORY_CLASS.getMethod("isProxyClass", new Class<?>[] { Class.class }); } catch (Exception ignore) { } } /** * Returns the proxied type, if any, else returns the given {@code type}. */ @SuppressWarnings("unchecked") public static <T> Class<T> deProxy(Class<?> type) { // Ignore JDK proxies if (type.isInterface()) return (Class<T>) type; if (isProxied(type)) { final Class<?> superclass = type.getSuperclass(); if (!superclass.equals(Object.class) && !superclass.equals(Proxy.class)) return (Class<T>) superclass; else { Class<?>[] interfaces = type.getInterfaces(); if (interfaces.length > 0) return (Class<T>) interfaces[0]; } } return (Class<T>) type; } public static boolean isProxied(Class<?> type) {<FILL_FUNCTION_BODY>} private static boolean isProxiedByJavassist(Class<?> type) { try { return JAVASSIST_IS_PROXY_CLASS_METHOD != null && (Boolean) JAVASSIST_IS_PROXY_CLASS_METHOD.invoke(null, type); } catch (Exception ignore) { } return false; } /** * Returns whether the {@code type} is a Groovy type. */ public static boolean isGroovyType(Class<?> type) { return type.getName().startsWith("org.codehaus.groovy"); } /** * Returns true if the {@code type} is instantiable. */ public static boolean isInstantiable(Class<?> type) { return !type.isEnum() && !type.isAssignableFrom(String.class) && !Primitives.isPrimitiveWrapper(type); } /** * Returns the raw type for the {@code type}. If {@code type} is a TypeVariable or a WildcardType * then the first upper bound is returned. is returned. * * @throws IllegalArgumentException if {@code type} is not a Class, ParameterizedType, * GenericArrayType, TypeVariable or WildcardType. */ public static Class<?> rawTypeFor(Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getRawType(); } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); return Array.newInstance(rawTypeFor(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { return rawTypeFor(((TypeVariable<?>) type).getBounds()[0]); } else if (type instanceof WildcardType) { return rawTypeFor(((WildcardType) type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Could not determine raw type for " + className); } } /** * Returns a origin class for the ASM {@code type}, else {@code null}. */ public static Class<?> classFor(org.objectweb.asm.Type type, ClassLoader classLoader) throws ClassNotFoundException { switch (type.getSort()) { case org.objectweb.asm.Type.BOOLEAN: return Boolean.TYPE; case org.objectweb.asm.Type.CHAR: return Character.TYPE; case org.objectweb.asm.Type.BYTE: return Byte.TYPE; case org.objectweb.asm.Type.SHORT: return Short.TYPE; case org.objectweb.asm.Type.INT: return Integer.TYPE; case org.objectweb.asm.Type.LONG: return Long.TYPE; case org.objectweb.asm.Type.FLOAT: return Float.TYPE; case org.objectweb.asm.Type.DOUBLE: return Double.TYPE; case org.objectweb.asm.Type.ARRAY: return Array.newInstance(classFor(type.getElementType(), classLoader), new int[type.getDimensions()]) .getClass(); case org.objectweb.asm.Type.OBJECT: default: return Class.forName(type.getClassName(), true, classLoader); } } /** * Returns a simplified String representation of the {@code member}. */ public static String toString(Member member) { if (member instanceof Method) { return member.getDeclaringClass().getName() + "." + member.getName() + "()"; } else if (member instanceof Field) { return member.getDeclaringClass().getName() + "." + member.getName(); } else if (member instanceof Constructor) { return member.getDeclaringClass().getName() + ".<init>()"; } return null; } /** * Returns a simplified String representation of the {@code type}. */ public static String toString(Type type) { return type instanceof Class ? ((Class<?>) type).getName() : type.toString(); } /** * Returns whether the type might contains properties or not. */ public static boolean mightContainsProperties(Class<?> type) { return type != Object.class && type != String.class && type != Date.class && type != Calendar.class && !Primitives.isPrimitive(type) && !Iterables.isIterable(type) && !Types.isGroovyType(type); } public static boolean isInternalType(Class<?> type) { String packageName = type.getPackage().getName(); return packageName.startsWith("java."); } }
if (type.getName().contains("$ByteBuddy$")) return true; if (type.getName().contains("$$EnhancerBy")) return true; if (type.getName().contains("$HibernateProxy$")) return true; if (type.getName().contains("$MockitoMock$")) return true; if (type.getName().contains("$$Permazen")) return true; if (Proxy.isProxyClass(type)) return true; return isProxiedByJavassist(type);
1,683
141
1,824
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/internal/valueaccess/MapValueReader.java
MapValueReader
getMember
class MapValueReader implements ValueReader<Map<String, Object>> { @Override public Object get(Map<String, Object> source, String memberName) { return source.get(memberName); } @SuppressWarnings("unchecked") @Override public Member<Map<String, Object>> getMember(Map<String, Object> source, String memberName) {<FILL_FUNCTION_BODY>} @Override public Collection<String> memberNames(Map<String, Object> source) { return source.keySet(); } }
final Object value = get(source, memberName); if (value instanceof Map) return new Member<Map<String, Object>>(Map.class) { @Override public Map<String, Object> getOrigin() { return (Map<String, Object>) value; } @Override public Object get(Map<String, Object> source, String memberName) { return MapValueReader.this.get(source, memberName); } }; Class<?> memberType = value != null ? value.getClass() : Object.class; return new Member<Map<String, Object>>(memberType) { @Override public Map<String, Object> getOrigin() { return null; } @Override public Object get(Map<String, Object> source, String memberName) { return MapValueReader.this.get(source, memberName); } };
146
233
379
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/spi/ErrorMessage.java
ErrorMessage
equals
class ErrorMessage implements Serializable { private static final long serialVersionUID = 0; private final Throwable cause; private final String message; /** * Creates an ErrorMessage for the given {@code message}. */ public ErrorMessage(String message) { this(message, null); } /** * Creates an ErrorMessage for the given {@code message} and {@code cause}. */ public ErrorMessage(String message, Throwable cause) { this.message = Assert.notNull(message, "message"); this.cause = cause; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} /** * Returns the Throwable that caused the error or {@code null} if no Throwable caused the error. */ public Throwable getCause() { return cause; } /** * Returns the error message. */ public String getMessage() { return message; } @Override public int hashCode() { return message.hashCode(); } @Override public String toString() { return message; } }
if (!(o instanceof ErrorMessage)) return false; ErrorMessage e = (ErrorMessage) o; return message.equals(e.message) && cause.equals(e.cause);
305
50
355
<no_super_class>
modelmapper_modelmapper
modelmapper/core/src/main/java/org/modelmapper/spi/StrongTypeConditionalConverter.java
StrongTypeConditionalConverter
match
class StrongTypeConditionalConverter<S, D> implements ConditionalConverter<S, D> { public static <S, D> ConditionalConverter<S, D> wrap(Class<S> sourceType, Class<D> destinationType, Converter<S, D> converter) { return new StrongTypeConditionalConverter<S, D>(sourceType, destinationType, converter); } private Class<S> sourceType; private Class<D> destinationType; private Converter<S, D> converter; public StrongTypeConditionalConverter(Class<S> sourceType, Class<D> destinationType, Converter<S, D> converter) { this.sourceType = sourceType; this.destinationType = destinationType; this.converter = converter; } @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) {<FILL_FUNCTION_BODY>} @Override public D convert(MappingContext<S, D> context) { return converter.convert(context); } }
if (sourceType == this.sourceType && destinationType == this.destinationType) return MatchResult.FULL; return MatchResult.NONE;
269
42
311
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/ComplexConversion.java
PaymentInfoConverter
main
class PaymentInfoConverter implements Converter<List<PaymentInfo>, List<Object>> { private boolean billing; PaymentInfoConverter(boolean billing) { this.billing = billing; } public List<Object> convert(MappingContext<List<PaymentInfo>, List<Object>> context) { List<PaymentInfo> payments = new ArrayList<PaymentInfo>(); for (PaymentInfo p : context.getSource()) if (!billing ^ "Billing".equals(p.type)) payments.add(p); return context.getMappingEngine().map(context.create(payments, context.getDestinationType())); } } public static void main(String... args) throws Exception {<FILL_FUNCTION_BODY>
ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration() .setFieldMatchingEnabled(true) .setFieldAccessLevel(AccessLevel.PACKAGE_PRIVATE); modelMapper.addMappings(new PropertyMap<Customer, CustomerDTO>() { @Override protected void configure() { using(new PaymentInfoConverter(true)).map(source.getInfo()).setBillingInfo(null); using(new PaymentInfoConverter(false)).map(source.getInfo()).setShippingInfo(null); } }); PaymentInfo info1 = new PaymentInfo(1, "Billing"); PaymentInfo info2 = new PaymentInfo(2, "Shipping"); PaymentInfo info3 = new PaymentInfo(3, "Billing"); PaymentInfo info4 = new PaymentInfo(4, "Shipping"); Customer customer = new Customer(); customer.info = Arrays.asList(info1, info2, info3, info4); CustomerDTO dto = modelMapper.map(customer, CustomerDTO.class); assertEquals(dto.billingInfo.get(0).id, 1); assertEquals(dto.billingInfo.get(1).id, 3); assertEquals(dto.shippingInfo.get(0).id, 2); assertEquals(dto.shippingInfo.get(1).id, 4);
196
357
553
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/FieldRelocation.java
AnotherCar
main
class AnotherCar { String personName; String type; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } } public static void main(String... args) {<FILL_FUNCTION_BODY>
ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new Converter<Car, AnotherCar>() { public AnotherCar convert(MappingContext<Car, AnotherCar> context) { Person person = (Person) context.getParent().getParent().getSource(); context.getDestination().setPersonName(person.getName()); context.getDestination().setType(context.getSource().getType()); return context.getDestination(); } }); // Alternatively, using a provider // modelMapper.getConfiguration().setProvider(new Provider<AnotherCar>() { // public AnotherCar get(org.modelmapper.Provider.ProvisionRequest<AnotherCar> request) { // AnotherCar anotherCar = new AnotherCar(); // anotherCar.setPersonName(((Person) request.getSource()).getName()); // return anotherCar; // } // }); modelMapper.addMappings(new PropertyMap<Person, AnotherPerson>() { @Override protected void configure() { map(source.getCars()).setAnotherCars(null); } }); Person person = new Person(); person.name = "joe"; Car car1 = new Car(); car1.type = "Honda"; Car car2 = new Car(); car2.type = "Toyota"; person.cars = Arrays.asList(car1, car2); AnotherPerson anotherPerson = modelMapper.map(person, AnotherPerson.class); assertEquals(anotherPerson.getCars().get(0).personName, "joe"); assertEquals(anotherPerson.getCars().get(0).type, car1.type); assertEquals(anotherPerson.getCars().get(1).personName, "joe"); assertEquals(anotherPerson.getCars().get(1).type, car2.type);
129
467
596
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/PropertyExtraction.java
OrderDTO
main
class OrderDTO { String id; Integer[] deliveryAddress_addressId; } public static void main(String... args) {<FILL_FUNCTION_BODY>
ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration() .setFieldMatchingEnabled(true) .setFieldAccessLevel(AccessLevel.PACKAGE_PRIVATE); modelMapper.createTypeMap(Order.class, OrderDTO.class).setPostConverter( new Converter<Order, OrderDTO>() { public OrderDTO convert(MappingContext<Order, OrderDTO> context) { DeliveryAddress[] deliveryAddress = context.getSource().deliveryAddress; context.getDestination().deliveryAddress_addressId = new Integer[deliveryAddress.length]; for (int i = 0; i < deliveryAddress.length; i++) context.getDestination().deliveryAddress_addressId[i] = deliveryAddress[i].addressId; return context.getDestination(); } }); Order order = new Order(); order.id = UUID.randomUUID().toString(); DeliveryAddress da1 = new DeliveryAddress(); da1.addressId = 123; DeliveryAddress da2 = new DeliveryAddress(); da2.addressId = 456; order.deliveryAddress = new DeliveryAddress[] { da1, da2 }; OrderDTO dto = modelMapper.map(order, OrderDTO.class); assertEquals(dto.id, order.id); assertEquals(dto.deliveryAddress_addressId, new Integer[] { 123, 456 });
48
369
417
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/flattening/example1/FlatteningExample1.java
FlatteningExample1
main
class FlatteningExample1 { public static void main(String... args) {<FILL_FUNCTION_BODY>} }
Customer customer = new Customer("Joe Smith"); Address billingAddress = new Address("2233 Pike Street", "Seattle"); Address shippingAddress = new Address("1234 Market Street", "San Francisco"); Order order = new Order(customer, billingAddress, shippingAddress); ModelMapper modelMapper = new ModelMapper(); OrderDTO dto = modelMapper.map(order, OrderDTO.class); assertEquals(dto.getCustomerName(), order.getCustomer().getName()); assertEquals(dto.getShippingStreetAddress(), order.getShippingAddress().getStreet()); assertEquals(dto.getShippingCity(), order.getShippingAddress().getCity()); assertEquals(dto.getBillingStreetAddress(), order.getBillingAddress().getStreet()); assertEquals(dto.getBillingCity(), order.getBillingAddress().getCity());
36
238
274
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/flattening/example2/FlatteningExample2.java
FlatteningExample2
main
class FlatteningExample2 { public static void main(String... args) throws Exception {<FILL_FUNCTION_BODY>} }
Person person = new Person(); Address address = new Address(); address.setStreet("1234 Main street"); address.setCity("San Francisco"); person.setAddress(address); // Option 1 ModelMapper modelMapper = new ModelMapper(); PropertyMap<Person, PersonDTO> personMap = new PropertyMap<Person, PersonDTO>() { protected void configure() { map().setStreet(source.getAddress().getStreet()); map(source.getAddress().city, destination.city); } }; modelMapper.addMappings(personMap); PersonDTO dto = modelMapper.map(person, PersonDTO.class); assertEquals(dto.getStreet(), person.getAddress().getStreet()); assertEquals(dto.getCity(), person.getAddress().getCity()); // Option 2 modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); dto = modelMapper.map(person, PersonDTO.class); assertEquals(dto.getStreet(), person.getAddress().getStreet()); assertEquals(dto.getCity(), person.getAddress().getCity());
38
330
368
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/gettingstarted/GettingStartedExample.java
GettingStartedExample
createOrder
class GettingStartedExample { public static void main(String... args) throws Exception { mapAutomatically(); mapExplicitly(); } /** * This example demonstrates how ModelMapper automatically maps properties from Order to OrderDTO. */ static void mapAutomatically() { Order order = createOrder(); ModelMapper modelMapper = new ModelMapper(); OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class); assertOrdersEqual(order, orderDTO); } /** * This example demonstrates how ModelMapper can be used to explicitly map properties from an * Order to OrderDTO. */ static void mapExplicitly() { Order order = createOrder(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new PropertyMap<Order, OrderDTO>() { @Override protected void configure() { map().setBillingStreet(source.getBillingAddress().getStreet()); map(source.billingAddress.getCity(), destination.billingCity); } }); OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class); assertOrdersEqual(order, orderDTO); } static Order createOrder() {<FILL_FUNCTION_BODY>} static void assertOrdersEqual(Order order, OrderDTO orderDTO) { assertEquals(orderDTO.getCustomerFirstName(), order.getCustomer().getName().getFirstName()); assertEquals(orderDTO.getCustomerLastName(), order.getCustomer().getName().getLastName()); assertEquals(orderDTO.getBillingStreet(), order.getBillingAddress().getStreet()); assertEquals(orderDTO.getBillingCity(), order.getBillingAddress().getCity()); } }
Customer customer = new Customer(new Name("Joe", "Smith")); Address billingAddress = new Address("2233 Pike Street", "Seattle"); return new Order(customer, billingAddress);
454
55
509
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/inheritance/InheritanceExample1.java
InheritanceExample1
main
class InheritanceExample1 { public static void main(String... args) {<FILL_FUNCTION_BODY>} }
org.modelmapper.inheritance.C c = new org.modelmapper.inheritance.C(Arrays.asList(new BaseSrcA(), new BaseSrcB())); ModelMapper modelMapper = new ModelMapper(); TypeMap<BaseSrc, BaseDest> typeMap = modelMapper.createTypeMap(BaseSrc.class, BaseDest.class) .include(BaseSrcA.class, BaseDestA.class) .include(BaseSrcB.class, BaseDestB.class); modelMapper.typeMap(BaseSrcA.class, BaseDest.class).setProvider(new Provider<BaseDest>() { public BaseDest get(ProvisionRequest<BaseDest> request) { return new BaseDestA(); } }); modelMapper.typeMap(BaseSrcB.class, BaseDest.class).setProvider(new Provider<BaseDest>() { public BaseDest get(ProvisionRequest<BaseDest> request) { return new BaseDestB(); } }); CcDTO ccDTO = modelMapper.map(c, CcDTO.class); assertEquals(2, ccDTO.getBases().size()); assertTrue(ccDTO.getBases().get(0) instanceof BaseDestA); assertTrue(ccDTO.getBases().get(1) instanceof BaseDestB);
35
343
378
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/projection/example1/ProjectionExample1.java
ProjectionExample1
main
class ProjectionExample1 { public static void main(String... args) {<FILL_FUNCTION_BODY>} }
OrderInfo orderInfo = new OrderInfo(); orderInfo.setCustomerName("Joe Smith"); orderInfo.setStreetAddress("1234 Main Street"); ModelMapper modelMapper = new ModelMapper(); Order order = modelMapper.map(orderInfo, Order.class); assertEquals(order.getCustomer().getName(), orderInfo.getCustomerName()); assertEquals(order.getAddress().getStreet(), orderInfo.getStreetAddress());
35
123
158
<no_super_class>
modelmapper_modelmapper
modelmapper/examples/src/main/java/org/modelmapper/projection/example2/ProjectionExample2.java
ProjectionExample2
main
class ProjectionExample2 { public static void main(String... args) {<FILL_FUNCTION_BODY>} }
OrderDTO orderDTO = new OrderDTO(); orderDTO.setStreet("1234 Pike Street"); orderDTO.setCity("Seattle"); // Option 1 ModelMapper modelMapper = new ModelMapper(); PropertyMap<OrderDTO, Order> orderMap = new PropertyMap<OrderDTO, Order>() { protected void configure() { map().getAddress().setStreet(source.getStreet()); map().address.setCity(source.city); } }; modelMapper.addMappings(orderMap); Order order = modelMapper.map(orderDTO, Order.class); assertEquals(order.getAddress().getStreet(), orderDTO.getStreet()); assertEquals(order.getAddress().getCity(), orderDTO.getCity()); // Option 2 modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); order = modelMapper.map(orderDTO, Order.class); assertEquals(order.getAddress().getStreet(), orderDTO.getStreet()); assertEquals(order.getAddress().getCity(), orderDTO.getCity());
35
320
355
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/gson/src/main/java/org/modelmapper/gson/JsonElementValueReader.java
JsonElementValueReader
get
class JsonElementValueReader implements ValueReader<JsonElement> { @Override public Object get(JsonElement source, String memberName) {<FILL_FUNCTION_BODY>} @Override public Member<JsonElement> getMember(JsonElement source, String memberName) { final Object value = get(source, memberName); final Class<?> type = value != null ? value.getClass() : JsonElement.class; return new Member<JsonElement>(type) { @Override public JsonElement getOrigin() { if (value instanceof JsonElement) return (JsonElement) value; return null; } @Override public Object get(JsonElement source, String memberName) { return JsonElementValueReader.this.get(source, memberName); } }; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Collection<String> memberNames(JsonElement source) { if (source.isJsonObject()) return Lists.from((Set) ((JsonObject) source).entrySet()); return null; } @Override public String toString() { return "Gson"; } }
if (source.isJsonObject()) { JsonObject subjObj = source.getAsJsonObject(); JsonElement propertyElement = subjObj.get(memberName); if (propertyElement == null) return null; if (propertyElement.isJsonObject()) return propertyElement.getAsJsonObject(); if (propertyElement.isJsonArray()) return propertyElement.getAsJsonArray(); if (propertyElement.isJsonPrimitive()) { JsonPrimitive jsonPrim = propertyElement.getAsJsonPrimitive(); if (jsonPrim.isBoolean()) return jsonPrim.getAsBoolean(); if (jsonPrim.isNumber()) return jsonPrim.getAsNumber(); if (jsonPrim.isString()) return jsonPrim.getAsString(); } } return null;
306
206
512
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jackson/src/main/java/org/modelmapper/jackson/ArrayNodeToCollectionConverter.java
ArrayNodeToCollectionConverter
convert
class ArrayNodeToCollectionConverter implements ConditionalConverter<ArrayNode, Collection<Object>> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Collection.class.isAssignableFrom(destinationType) && sourceType.isAssignableFrom(ArrayNode.class) ? MatchResult.FULL : MatchResult.NONE; } @Override public Collection<Object> convert(MappingContext<ArrayNode, Collection<Object>> context) {<FILL_FUNCTION_BODY>} }
ArrayNode source = context.getSource(); if (source == null) return null; Collection<Object> destination = context.getDestination() == null ? MappingContextHelper.createCollection(context) : context.getDestination(); Class<?> elementType = MappingContextHelper.resolveDestinationGenericType(context); for (Object sourceElement : source) { Object element = null; if (sourceElement != null) { MappingContext<?, ?> elementContext = context.create(sourceElement, elementType); element = context.getMappingEngine().map(elementContext); } destination.add(element); } return destination;
137
175
312
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jackson/src/main/java/org/modelmapper/jackson/CollectionToArrayNodeConverter.java
CollectionToArrayNodeConverter
convert
class CollectionToArrayNodeConverter implements ConditionalConverter<Collection<Object>, ArrayNode> { private ObjectMapper objectMapper; public CollectionToArrayNodeConverter(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return Collection.class.isAssignableFrom(sourceType) && ArrayNode.class.isAssignableFrom(destinationType) ? MatchResult.FULL : MatchResult.NONE; } @Override public ArrayNode convert(MappingContext<Collection<Object>, ArrayNode> context) {<FILL_FUNCTION_BODY>} private void addPrimitiveElement(ArrayNode destination, Object element) { Class<?> elementType = element.getClass(); try { Method method = destination.getClass().getMethod("add", elementType); method.invoke(destination, element); } catch (NoSuchMethodException e) { throw new Errors().addMessage("Unsupported type: %s", elementType.getName()).toMappingException(); } catch (IllegalAccessException e) { throw new Errors().addMessage("Unable to map Array->Collection", elementType.getName()).toMappingException(); } catch (InvocationTargetException e) { throw new Errors().addMessage("Unable to map Array->Collection", elementType.getName()).toMappingException(); } } }
Collection<Object> source = context.getSource(); if (source == null) return null; ArrayNode destination = context.getDestination() == null ? objectMapper.createArrayNode() : context.getDestination(); for (Object sourceElement : source) { if (sourceElement != null) { destination.add(objectMapper.valueToTree(sourceElement)); } else { destination.add(MissingNode.getInstance()); } } return destination;
364
128
492
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jackson/src/main/java/org/modelmapper/jackson/JacksonModule.java
JacksonModule
setupModule
class JacksonModule implements Module { private ObjectMapper objectMapper; public JacksonModule() { this(new ObjectMapper()); } public JacksonModule(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public void setupModule(ModelMapper modelMapper) {<FILL_FUNCTION_BODY>} }
modelMapper.getConfiguration().addValueReader(new JsonNodeValueReader()); modelMapper.getConfiguration().getConverters().add(0, new PrimitiveJsonNodeConverter()); modelMapper.getConfiguration().getConverters().add(0, new ArrayNodeToCollectionConverter()); modelMapper.getConfiguration().getConverters().add(0, new CollectionToArrayNodeConverter(objectMapper));
92
96
188
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jackson/src/main/java/org/modelmapper/jackson/JsonNodeValueReader.java
JsonNodeValueReader
get
class JsonNodeValueReader implements ValueReader<JsonNode> { public Object get(JsonNode source, String memberName) {<FILL_FUNCTION_BODY>} public Member<JsonNode> getMember(JsonNode source, String memberName) { final Object value = get(source, memberName); final Class<?> type = value != null ? value.getClass() : JsonNode.class; return new Member<JsonNode>(type) { @Override public JsonNode getOrigin() { if (value instanceof JsonNode) return (JsonNode) value; return null; } @Override public Object get(JsonNode source, String memberName) { return JsonNodeValueReader.this.get(source, memberName); } }; } public Collection<String> memberNames(JsonNode source) { if (source.isObject()) return Lists.from(source.fieldNames()); return null; } @Override public String toString() { return "Jackson"; } }
JsonNode propertyNode = source.get(memberName); if (propertyNode == null) return null; switch (propertyNode.getNodeType()) { case BOOLEAN: return propertyNode.asBoolean(); case NUMBER: return propertyNode.numberValue(); case POJO: return ((POJONode) propertyNode).getPojo(); case STRING: return propertyNode.asText(); case BINARY: try { return propertyNode.binaryValue(); } catch (IOException ignore) { return null; } case NULL: case MISSING: return null; case ARRAY: case OBJECT: default: return propertyNode; }
269
194
463
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jackson/src/main/java/org/modelmapper/jackson/PrimitiveJsonNodeConverter.java
PrimitiveJsonNodeConverter
convert
class PrimitiveJsonNodeConverter implements ConditionalConverter<JsonNode, Object> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) { return (JsonNode.class.isAssignableFrom(sourceType) && !ContainerNode.class.isAssignableFrom(sourceType)) ? MatchResult.FULL : MatchResult.NONE; } @Override public Object convert(MappingContext<JsonNode, Object> context) {<FILL_FUNCTION_BODY>} }
JsonNode source = context.getSource(); if (source == null) return null; if (source.isNumber()) { MappingContext<?, ?> mappingContext = context.create(source.numberValue(), context.getDestinationType()); return context.getMappingEngine().map(mappingContext); } else { MappingContext<?, ?> mappingContext = context.create(source.textValue(), context.getDestinationType()); return context.getMappingEngine().map(mappingContext); }
144
142
286
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/jooq/src/main/java/org/modelmapper/jooq/RecordValueReader.java
RecordValueReader
getMember
class RecordValueReader implements ValueReader<Record> { public Object get(Record source, String memberName) { Field<?> field = matchField(source, memberName); if (field != null) { return source.getValue(field); } return null; } public Member<Record> getMember(Record source, String memberName) {<FILL_FUNCTION_BODY>} private Field<?> matchField(Record source, String memberName) { for (Field<?> field : source.fields()) if (memberName.equalsIgnoreCase(field.getName())) return field; return null; } public Collection<String> memberNames(Record source) { Field<?>[] fields = source.fields(); if (fields != null) { List<String> memberNames = new ArrayList<String>(fields.length); for (Field<?> field : fields) memberNames.add(field.getName()); return memberNames; } return null; } @Override public String toString() { return "jOOQ"; } }
Field<?> field = matchField(source, memberName); Class<?> type = field != null ? field.getType() : Record.class; return new Member<Record>(type) { @Override public Object get(Record source, String memberName) { return RecordValueReader.this.get(source, memberName); } };
288
94
382
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/protobuf/src/main/java/org/modelmapper/protobuf/MessageToBuilderConverter.java
MessageToBuilderConverter
match
class MessageToBuilderConverter implements ConditionalConverter<Message, Builder> { @Override public MatchResult match(Class<?> sourceType, Class<?> destinationType) {<FILL_FUNCTION_BODY>} @Override public Builder convert(MappingContext<Message, Builder> context) { return context.getSource().toBuilder(); } }
boolean match = Message.class.isAssignableFrom(sourceType) && Builder.class.isAssignableFrom(destinationType) && sourceType.equals(ProtobufHelper.messageOfBuilder(destinationType)); return match ? MatchResult.FULL : MatchResult.NONE;
99
80
179
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/protobuf/src/main/java/org/modelmapper/protobuf/ProtobufHelper.java
ProtobufHelper
formatSnakeCaseMethodName
class ProtobufHelper { private static final char CASE_MASK = 0x20; private ProtobufHelper() {} public static boolean hasBuilder(Class<?> builderType, String field) { return builder(builderType, field) != null; } @SuppressWarnings("unchecked") public static Class<? extends Builder> builder(Class<?> builderType, String field) { try { String methodName = "get" + formatMethodName(field) + "Builder"; return (Class<? extends Builder>) builderType.getMethod(methodName).getReturnType(); } catch (NoSuchMethodException e) { return null; } } public static List<String> fields(Class<?> type) { if (Builder.class.isAssignableFrom(type)) return fieldsOfMessage(messageOfBuilder(type)); if (Message.class.isAssignableFrom(type)) return fieldsOfMessage(type); throw new Errors().addMessage("Invalid protocol buffer type: %s", type.getName()).toConfigurationException(); } public static Class<?> fieldType(Class<?> type, String memberName) throws NoSuchFieldException, NoSuchMethodException { final Class<?> fieldType = type.getDeclaredField(formatFieldName(memberName)).getType(); if (Iterable.class.isAssignableFrom(fieldType)) return fieldType; return getter(type, memberName).getReturnType(); } public static Method getter(Class<?> type, String field) throws NoSuchMethodException { String methodName = "get" + formatMethodName(field); return type.getMethod(methodName); } public static Class<?> messageOfBuilder(Class<?> builderType) { try { Method buildMethod = builderType.getDeclaredMethod("build"); return buildMethod.getReturnType(); } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Invalid protocol buffer type").toConfigurationException(); } } public static Method setterForBuilder(Class<?> type, String field) throws NoSuchMethodException { String methodName = "set" + formatMethodName(field); for (Method method : type.getMethods()) { if (isSetterForBuilder(method, methodName)) return method; } throw new NoSuchMethodException(methodName); } public static Method setter(Class<?> type, String field) throws NoSuchMethodException { String methodName = "set" + formatMethodName(field); for (Method method : type.getMethods()) { if (isSetterForPrimitive(method, methodName)) return method; } throw new NoSuchMethodException(methodName); } public static Method adder(Class<?> type, String field) throws NoSuchMethodException { String methodName = "add" + formatMethodName(field); for (Method method : type.getMethods()) { if (isSetterForBuilder(method, methodName)) return method; } throw new NoSuchMethodException(methodName); } public static Class<?> iterableType(Class<?> type, String field) throws NoSuchMethodException { return adder(type, field).getParameterTypes()[0]; } public static Method hasMethod(Class<?> type, String field) throws NoSuchMethodException { String methodName = "has" + formatMethodName(field); return type.getMethod(methodName); } private static List<String> fieldsOfMessage(Class<?> type) { try { Method descriptorMethod = type.getDeclaredMethod("getDescriptor"); Descriptor descriptor = (Descriptor) descriptorMethod.invoke(type); List<String> fields = new ArrayList<String>(); for (FieldDescriptor field : descriptor.getFields()) { fields.add(field.getName()); } return fields; } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Invalid protocol buffer type").toConfigurationException(); } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Invalid protocol buffer type").toConfigurationException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Invalid protocol buffer type").toConfigurationException(); } } private static String formatFieldName(String str) { if (str.contains("_")) { String upperSnakeCase = formatSnakeCaseMethodName(str); return upperSnakeCase.substring(0, 1).toLowerCase() + upperSnakeCase.substring(1) + "_"; } return str + "_"; } private static String formatMethodName(String str) { if (str.contains("_")) { return formatSnakeCaseMethodName(str); } return str.substring(0, 1).toUpperCase() + str.substring(1); } private static String formatSnakeCaseMethodName(String str) {<FILL_FUNCTION_BODY>} private static boolean isSetterForPrimitive(Method method, String methodName) { if (!method.getName().equalsIgnoreCase(methodName)) return false; Class<?>[] parameterTypes = method.getParameterTypes(); return parameterTypes.length == 1 && !Message.Builder.class.isAssignableFrom(parameterTypes[0]); } private static boolean isSetterForBuilder(Method method, String methodName) { if (!method.getName().equalsIgnoreCase(methodName)) return false; Class<?>[] parameterTypes = method.getParameterTypes(); return parameterTypes.length == 1 && Message.Builder.class.isAssignableFrom(parameterTypes[0]); } }
StringBuilder methodName = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) == '_' && i + 1 < str.length()) { char c = str.charAt(++i); if ((c >= 'a') && (c <= 'z')) { methodName.append((char) (c ^ CASE_MASK)); } else { methodName.append(c); } } else { methodName.append(str.charAt(i)); } } return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
1,616
196
1,812
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/protobuf/src/main/java/org/modelmapper/protobuf/ProtobufModule.java
ProtobufModule
setupModule
class ProtobufModule implements Module { @Override public void setupModule(ModelMapper modelMapper) {<FILL_FUNCTION_BODY>} }
modelMapper.getConfiguration().addValueReader(new ProtobufValueReader()); modelMapper.getConfiguration().addValueWriter(new ProtobufValueWriter(modelMapper)); List<ConditionalConverter<?, ?>> converters = modelMapper.getConfiguration().getConverters(); converters.add(new MessageToBuilderConverter()); converters.add(wrap(Boolean.class, BoolValue.class, BoolConverters.BOOL_TO_BOOL_VALUE)); converters.add(wrap(BoolValue.class, Boolean.class, BoolConverters.BOOL_VALUE_TO_BOOL)); converters.add(wrap(Boolean.class, BoolValue.Builder.class, BoolConverters.BOOL_TO_BUILDER)); converters.add(wrap(BoolValue.Builder.class, Boolean.class, BoolConverters.BUILDER_TO_BOOL)); converters.add(wrap(Long.class, Int64Value.class, IntConverters.LONG_TO_LONG_VALUE)); converters.add(wrap(Int64Value.class, Long.class, IntConverters.LONG_VALUE_TO_LONG)); converters.add(wrap(Long.class, Int64Value.Builder.class, IntConverters.LONG_TO_BUILDER)); converters.add(wrap(Int64Value.Builder.class, Long.class, IntConverters.BUILDER_TO_LONG)); converters.add(wrap(Integer.class, Int32Value.class, IntConverters.INT_TO_INT_VALUE)); converters.add(wrap(Int32Value.class, Integer.class, IntConverters.INT_VALUE_TO_INT)); converters.add(wrap(Integer.class, Int32Value.Builder.class, IntConverters.INT_TO_BUILDER)); converters.add(wrap(Int32Value.Builder.class, Integer.class, IntConverters.BUILDER_TO_INT)); converters.add(wrap(Double.class, DoubleValue.class, DoubleConverters.DOUBLE_TO_DOUBLE_VALUE)); converters.add(wrap(DoubleValue.class, Double.class, DoubleConverters.DOUBLE_VALUE_TO_DOUBLE)); converters.add(wrap(Double.class, DoubleValue.Builder.class, DoubleConverters.DOUBLE_TO_BUILDER)); converters.add(wrap(DoubleValue.Builder.class, Double.class, DoubleConverters.BUILDER_TO_DOUBLE)); converters.add(wrap(String.class, StringValue.class, StringConverters.STRING_TO_STRING_VALUE)); converters.add(wrap(StringValue.class, String.class, StringConverters.STRING_VALUE_TO_STRING)); converters.add(wrap(String.class, StringValue.Builder.class, StringConverters.STRING_TO_BUILDER)); converters.add(wrap(StringValue.Builder.class, String.class, StringConverters.BUILDER_TO_STRING));
43
805
848
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/protobuf/src/main/java/org/modelmapper/protobuf/ProtobufValueReader.java
ProtobufValueReader
getMember
class ProtobufValueReader implements ValueReader<MessageOrBuilder> { @Override public Object get(MessageOrBuilder source, String memberName) { try { Method method = ProtobufHelper.getter(source.getClass(), memberName); return method.invoke(source); } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } } @Override public Member<MessageOrBuilder> getMember(MessageOrBuilder source, String memberName) {<FILL_FUNCTION_BODY>} @Override public Collection<String> memberNames(MessageOrBuilder source) { return ProtobufHelper.fields(source.getClass()); } }
try { final Method getter = ProtobufHelper.getter(source.getClass(), memberName); final Object value = getter.invoke(source); if (Message.class.isAssignableFrom(getter.getReturnType())) { final Method hasMethod = ProtobufHelper.hasMethod(source.getClass(), memberName); return new Member<MessageOrBuilder>(getter.getReturnType()) { @Override public MessageOrBuilder getOrigin() { return MessageOrBuilder.class.isAssignableFrom(value.getClass()) ? (MessageOrBuilder) value : null; } @Override public Object get(MessageOrBuilder source, String memberName) { try { if (Boolean.TRUE.equals(hasMethod.invoke(source))) return getter.invoke(source); return null; } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } } }; } else return new Member<MessageOrBuilder>(getter.getReturnType()) { @Override public MessageOrBuilder getOrigin() { return MessageOrBuilder.class.isAssignableFrom(value.getClass()) ? (MessageOrBuilder) value : null; } @Override public Object get(MessageOrBuilder source, String memberName) { try { return getter.invoke(source); } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } } }; } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Cannot get the member").toConfigurationException(); } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Cannot get the member").toConfigurationException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Cannot get the member").toConfigurationException(); }
280
631
911
<no_super_class>
modelmapper_modelmapper
modelmapper/extensions/protobuf/src/main/java/org/modelmapper/protobuf/ProtobufValueWriter.java
ProtobufValueWriter
setValue
class ProtobufValueWriter implements ValueWriter<Builder> { private ModelMapper modelMapper; public ProtobufValueWriter(ModelMapper modelMapper) { this.modelMapper = modelMapper; } @Override public void setValue(Builder destination, Object value, String memberName) {<FILL_FUNCTION_BODY>} @Override public Member<Builder> getMember(Class<Builder> destinationType, final String memberName) { try { final Class<?> memberType = ProtobufHelper.fieldType(destinationType, memberName); return new Member<Builder>(memberType) { @Override public void setValue(Builder destination, Object value) { ProtobufValueWriter.this.setValue(destination, value, memberName); } }; } catch (NoSuchFieldException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Cannot get the member").toMappingException(); } } @Override public Collection<String> memberNames(Class<Builder> destinationType) { return ProtobufHelper.fields(destinationType); } @Override public boolean isResolveMembersSupport() { return true; } }
if (value == null) return; try { Class<? extends Builder> destinationType = destination.getClass(); if (value instanceof Builder) { Method method = ProtobufHelper.setterForBuilder(destinationType, memberName); method.invoke(destination, value); } else if (value instanceof Iterable) { Class<?> iterableType = ProtobufHelper.iterableType(destinationType, memberName); Method method = ProtobufHelper.adder(destinationType, memberName); for (Object element : (Iterable<?>) value) { Object destElement = modelMapper.map(element, iterableType); method.invoke(destination, destElement); } } else { Method method = ProtobufHelper.setter(destination.getClass(), memberName); method.invoke(destination, value); } } catch (NoSuchMethodException e) { throw new Errors().addMessage(e, "Cannot set the member").toMappingException(); } catch (IllegalAccessException e) { throw new Errors().addMessage(e, "Cannot set the member").toMappingException(); } catch (InvocationTargetException e) { throw new Errors().addMessage(e, "Cannot set the member").toMappingException(); }
377
358
735
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/AbstractSessionMessageQueue.java
AbstractSessionMessageQueue
checkEnqueuePreconditions
class AbstractSessionMessageQueue<T> implements SessionMessageQueue<T> { protected boolean closed = false; protected void checkEnqueuePreconditions(T t) {<FILL_FUNCTION_BODY>} protected void checkDequeuePreconditions() { if (closed) { throw new IllegalStateException("Can't read data from a closed queue"); } } protected void checkIsEmptyPreconditions() { if (closed) { throw new IllegalStateException("Can't state empty status in a closed queue"); } } }
if (t == null) { throw new NullPointerException("Inserted element can't be null"); } if (closed) { throw new IllegalStateException("Can't push data in a closed queue"); }
144
60
204
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/Authorizator.java
Authorizator
getQoSCheckingAlsoPermissionsOnTopic
class Authorizator { private static final Logger LOG = LoggerFactory.getLogger(Authorizator.class); private final IAuthorizatorPolicy policy; Authorizator(IAuthorizatorPolicy policy) { this.policy = policy; } List<MqttTopicSubscription> verifyAlsoSharedTopicsReadAccess(String clientID, String username, MqttSubscribeMessage msg) { return verifyTopicsReadAccessWithTopicExtractor(clientID, username, msg, Authorizator::extractShareTopic); } private static Topic extractShareTopic(String s) { if (SharedSubscriptionUtils.isSharedSubscription(s)) { return Topic.asTopic(SharedSubscriptionUtils.extractFilterFromShared(s)); } return Topic.asTopic(s); } /** * @param clientID * the clientID * @param username * the username * @param msg * the subscribe message to verify * @return the list of verified topics for the given subscribe message. */ List<MqttTopicSubscription> verifyTopicsReadAccess(String clientID, String username, MqttSubscribeMessage msg) { return verifyTopicsReadAccessWithTopicExtractor(clientID, username, msg, Topic::asTopic); } private List<MqttTopicSubscription> verifyTopicsReadAccessWithTopicExtractor(String clientID, String username, MqttSubscribeMessage msg, Function<String, Topic> topicExtractor) { List<MqttTopicSubscription> ackTopics = new ArrayList<>(); final int messageId = messageId(msg); for (MqttTopicSubscription req : msg.payload().topicSubscriptions()) { Topic topic = topicExtractor.apply(req.topicName()); final MqttQoS qos = getQoSCheckingAlsoPermissionsOnTopic(clientID, username, messageId, topic, req.qualityOfService()); MqttSubscriptionOption option = PostOffice.optionWithQos(qos, req.option()); ackTopics.add(new MqttTopicSubscription(req.topicName(), option)); } return ackTopics; } private MqttQoS getQoSCheckingAlsoPermissionsOnTopic(String clientID, String username, int messageId, Topic topic, MqttQoS requestedQoS) {<FILL_FUNCTION_BODY>} /** * Ask the authorization policy if the topic can be used in a publish. * * @param topic * the topic to write to. * @param user * the user * @param client * the client * @return true if the user from client can publish data on topic. */ boolean canWrite(Topic topic, String user, String client) { return policy.canWrite(topic, user, client); } boolean canRead(Topic topic, String user, String client) { return policy.canRead(topic, user, client); } }
if (policy.canRead(topic, username, clientID)) { if (topic.isValid()) { LOG.debug("Client will be subscribed to the topic username: {}, messageId: {}, topic: {}", username, messageId, topic); return requestedQoS; } LOG.warn("Topic filter is not valid username: {}, messageId: {}, topic: {}", username, messageId, topic); return FAILURE; } // send SUBACK with 0x80, the user hasn't credentials to read the topic LOG.warn("Client does not have read permissions on the topic username: {}, messageId: {}, " + "topic: {}", username, messageId, topic); return FAILURE;
799
188
987
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/AutoFlushHandler.java
AutoFlushHandler
initialize
class AutoFlushHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(AutoFlushHandler.class); private static final long MIN_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(1); private final long writerIdleTimeNanos; volatile ScheduledFuture<?> writerIdleTimeout; volatile long lastWriteTime; // private boolean firstWriterIdleEvent = true; private volatile int state; // 0 - none, 1 - initialized, 2 - destroyed public AutoFlushHandler(long writerIdleTime, TimeUnit unit) { if (unit == null) { throw new NullPointerException("unit"); } writerIdleTimeNanos = Math.max(unit.toNanos(writerIdleTime), MIN_TIMEOUT_NANOS); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isActive() && ctx.channel().isRegistered()) { // channelActive() event has been fired already, which means this.channelActive() will // not be invoked. We have to initialize here instead. initialize(ctx); } else { // channelActive() event has not been fired yet. this.channelActive() will be invoked // and initialization will occur there. } } @Override public void handlerRemoved(ChannelHandlerContext ctx) { destroy(); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { // Initialize early if channel is active already. // if (ctx.channel().isActive()) { // initialize(ctx); // } super.channelRegistered(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // This method will be invoked only if this handler was added // before channelActive() event is fired. If a user adds this handler // after the channelActive() event, initialize() will be called by beforeAdd(). // initialize(ctx); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { destroy(); super.channelInactive(ctx); } private void initialize(ChannelHandlerContext ctx) {<FILL_FUNCTION_BODY>} private void destroy() { state = 2; if (writerIdleTimeout != null) { writerIdleTimeout.cancel(false); writerIdleTimeout = null; } } /** * Is called when the write timeout expire. * * @param ctx the channel context. */ private void channelIdle(ChannelHandlerContext ctx) { // ctx.fireUserEventTriggered(evt); if (LOG.isTraceEnabled()) { LOG.trace("Flushing idle Netty channel {} Cid: {}", ctx.channel(), NettyUtils.clientID(ctx.channel())); } ctx.channel().flush(); } private final class WriterIdleTimeoutTask implements Runnable { private final ChannelHandlerContext ctx; WriterIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() { if (!ctx.channel().isOpen()) { return; } // long lastWriteTime = IdleStateHandler.this.lastWriteTime; // long lastWriteTime = lastWriteTime; long nextDelay = writerIdleTimeNanos - (System.nanoTime() - lastWriteTime); if (nextDelay <= 0) { // Writer is idle - set a new timeout and notify the callback. writerIdleTimeout = ctx.executor().schedule(this, writerIdleTimeNanos, TimeUnit.NANOSECONDS); try { /* * IdleStateEvent event; if (firstWriterIdleEvent) { firstWriterIdleEvent = * false; event = IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT; } else { event = * IdleStateEvent.WRITER_IDLE_STATE_EVENT; } */ channelIdle(ctx/* , event */); } catch (Throwable t) { ctx.fireExceptionCaught(t); } } else { // Write occurred before the timeout - set a new timeout with shorter delay. writerIdleTimeout = ctx.executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS); } } } }
// Avoid the case where destroy() is called before scheduling timeouts. // See: https://github.com/netty/netty/issues/143 if (LOG.isDebugEnabled()) { LOG.debug("Initializing autoflush handler on channel {} Cid: {}", ctx.channel(), NettyUtils.clientID(ctx.channel())); } switch (state) { case 1: case 2: return; } state = 1; EventExecutor loop = ctx.executor(); lastWriteTime = System.nanoTime(); writerIdleTimeout = loop.schedule(new WriterIdleTimeoutTask(ctx), writerIdleTimeNanos, TimeUnit.NANOSECONDS);
1,156
192
1,348
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/BugSnagErrorsHandler.java
BugSnagErrorsHandler
init
class BugSnagErrorsHandler extends ChannelInboundHandlerAdapter { private Bugsnag bugsnag; public void init(IConfig props) {<FILL_FUNCTION_BODY>} @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { bugsnag.notify(cause); ctx.fireExceptionCaught(cause); } }
final String token = props.getProperty(BUGSNAG_TOKEN_PROPERTY_NAME); this.bugsnag = new Bugsnag(token);
103
45
148
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/ClientDescriptor.java
ClientDescriptor
toString
class ClientDescriptor { private final String clientID; private final String address; private final int port; ClientDescriptor(String clientID, String address, int port) { this.clientID = clientID; this.address = address; this.port = port; } public String getClientID() { return clientID; } public String getAddress() { return address; } public int getPort() { return port; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientDescriptor that = (ClientDescriptor) o; return port == that.port && Objects.equals(clientID, that.clientID) && Objects.equals(address, that.address); } @Override public int hashCode() { return Objects.hash(clientID, address, port); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ClientDescriptor{" + "clientID='" + clientID + '\'' + ", address='" + address + '\'' + ", port=" + port + '}';
285
51
336
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/DebugUtils.java
DebugUtils
payload2Str
class DebugUtils { public static String payload2Str(ByteBuf content) {<FILL_FUNCTION_BODY>} private DebugUtils() { } }
final int readerPin = content.readableBytes(); final String result = content.toString(StandardCharsets.UTF_8); content.readerIndex(readerPin); return result;
45
49
94
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/DefaultMoquetteSslContextCreator.java
DefaultMoquetteSslContextCreator
addClientAuthentication
class DefaultMoquetteSslContextCreator implements ISslContextCreator { private static final Logger LOG = LoggerFactory.getLogger(DefaultMoquetteSslContextCreator.class); private final IConfig props; DefaultMoquetteSslContextCreator(IConfig props) { this.props = Objects.requireNonNull(props); } @Override public SslContext initSSLContext() { LOG.info("Checking SSL configuration properties..."); final String keyPassword = props.getProperty(BrokerConstants.KEY_MANAGER_PASSWORD_PROPERTY_NAME); if (keyPassword == null || keyPassword.isEmpty()) { LOG.warn("The key manager password is null or empty. The SSL context won't be initialized."); return null; } try { SslProvider sslProvider = getSSLProvider(); KeyStore ks = loadKeyStore(); SslContextBuilder contextBuilder; switch (sslProvider) { case JDK: contextBuilder = builderWithJdkProvider(ks, keyPassword); break; case OPENSSL: case OPENSSL_REFCNT: contextBuilder = builderWithOpenSSLProvider(ks, keyPassword); break; default: LOG.error("unsupported SSL provider {}", sslProvider); return null; } // if client authentification is enabled a trustmanager needs to be added to the ServerContext String sNeedsClientAuth = props.getProperty(BrokerConstants.NEED_CLIENT_AUTH, "false"); if (Boolean.valueOf(sNeedsClientAuth)) { addClientAuthentication(ks, contextBuilder); } contextBuilder.sslProvider(sslProvider); SslContext sslContext = contextBuilder.build(); LOG.info("The SSL context has been initialized successfully."); return sslContext; } catch (GeneralSecurityException | IOException ex) { LOG.error("Unable to initialize SSL context.", ex); return null; } } private KeyStore loadKeyStore() throws IOException, GeneralSecurityException { final String jksPath = props.getProperty(BrokerConstants.JKS_PATH_PROPERTY_NAME); LOG.info("Initializing SSL context. KeystorePath = {}.", jksPath); if (jksPath == null || jksPath.isEmpty()) { LOG.warn("The keystore path is null or empty. The SSL context won't be initialized."); return null; } final String keyStorePassword = props.getProperty(BrokerConstants.KEY_STORE_PASSWORD_PROPERTY_NAME); if (keyStorePassword == null || keyStorePassword.isEmpty()) { LOG.warn("The keystore password is null or empty. The SSL context won't be initialized."); return null; } String ksType = props.getProperty(BrokerConstants.KEY_STORE_TYPE, "jks"); final KeyStore keyStore = KeyStore.getInstance(ksType); LOG.info("Loading keystore. KeystorePath = {}.", jksPath); try (InputStream jksInputStream = jksDatastore(jksPath)) { keyStore.load(jksInputStream, keyStorePassword.toCharArray()); } return keyStore; } private static SslContextBuilder builderWithJdkProvider(KeyStore ks, String keyPassword) throws GeneralSecurityException { LOG.info("Initializing key manager..."); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keyPassword.toCharArray()); LOG.info("Initializing SSL context..."); return SslContextBuilder.forServer(kmf); } /** * The OpenSSL provider does not support the {@link KeyManagerFactory}, so we have to lookup the integration * certificate and key in order to provide it to OpenSSL. * <p> * TODO: SNI is currently not supported, we use only the first found private key. */ private static SslContextBuilder builderWithOpenSSLProvider(KeyStore ks, String keyPassword) throws GeneralSecurityException { for (String alias : Collections.list(ks.aliases())) { if (ks.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); X509Certificate[] certChain = new X509Certificate[chain.length]; System.arraycopy(chain, 0, certChain, 0, chain.length); return SslContextBuilder.forServer(key, certChain); } } throw new KeyManagementException("the SSL key-store does not contain a private key"); } private static void addClientAuthentication(KeyStore ks, SslContextBuilder contextBuilder) throws NoSuchAlgorithmException, KeyStoreException {<FILL_FUNCTION_BODY>} private SslProvider getSSLProvider() { String providerName = props.getProperty(BrokerConstants.SSL_PROVIDER, SslProvider.JDK.name()); try { return SslProvider.valueOf(providerName); } catch (IllegalArgumentException e) { LOG.warn("unknown SSL Provider {}, falling back on JDK provider", providerName); return SslProvider.JDK; } } private InputStream jksDatastore(String jksPath) throws FileNotFoundException { URL jksUrl = getClass().getClassLoader().getResource(jksPath); if (jksUrl != null) { LOG.info("Starting with jks at {}, jks normal {}", jksUrl.toExternalForm(), jksUrl); return getClass().getClassLoader().getResourceAsStream(jksPath); } LOG.warn("No keystore has been found in the bundled resources. Scanning filesystem..."); File jksFile = new File(jksPath); if (jksFile.exists()) { LOG.info("Loading external keystore. Url = {}.", jksFile.getAbsolutePath()); return new FileInputStream(jksFile); } throw new FileNotFoundException("The keystore file does not exist. Url = " + jksFile.getAbsolutePath()); } }
LOG.warn("Client authentication is enabled. The keystore will be used as a truststore."); // use keystore as truststore, as integration needs to trust certificates signed by the integration certificates TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); contextBuilder.clientAuth(ClientAuth.REQUIRE); contextBuilder.trustManager(tmf);
1,595
109
1,704
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/InMemoryQueue.java
InMemoryQueue
closeAndPurge
class InMemoryQueue extends AbstractSessionMessageQueue<SessionRegistry.EnqueuedMessage> { private final MemoryQueueRepository queueRepository; private final String queueName; private Queue<SessionRegistry.EnqueuedMessage> queue = new ConcurrentLinkedQueue<>(); /** * Constructor to create a repository untracked queue. */ public InMemoryQueue() { this(null, null); } public InMemoryQueue(MemoryQueueRepository queueRepository, String queueName) { this.queueRepository = queueRepository; this.queueName = queueName; } @Override public void enqueue(SessionRegistry.EnqueuedMessage message) { checkEnqueuePreconditions(message); queue.add(message); } @Override public SessionRegistry.EnqueuedMessage dequeue() { checkDequeuePreconditions(); return queue.poll(); } @Override public boolean isEmpty() { checkIsEmptyPreconditions(); return queue.isEmpty(); } @Override public void closeAndPurge() {<FILL_FUNCTION_BODY>} }
for (SessionRegistry.EnqueuedMessage msg : queue) { msg.release(); } if (queueRepository != null) { // clean up the queue from the repository queueRepository.dropQueue(this.queueName); } this.closed = true;
289
73
362
<methods>public non-sealed void <init>() <variables>protected boolean closed
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/InflightResender.java
WriterIdleTimeoutTask
run
class WriterIdleTimeoutTask implements Runnable { private final ChannelHandlerContext ctx; WriterIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() {<FILL_FUNCTION_BODY>} }
if (!ctx.channel().isOpen()) { return; } long nextDelay = resenderTimeNanos - (System.nanoTime() - lastExecutionTime); if (nextDelay <= 0) { // Writer is idle - set a new timeout and notify the callback. resenderTimeout = ctx.executor().schedule(this, resenderTimeNanos, TimeUnit.NANOSECONDS); try { resendNotAcked(ctx/* , event */); } catch (Throwable t) { ctx.fireExceptionCaught(t); } } else { // Write occurred before the timeout - set a new timeout with shorter delay. resenderTimeout = ctx.executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS); }
77
203
280
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/MemoryQueueRepository.java
MemoryQueueRepository
getOrCreateQueue
class MemoryQueueRepository implements IQueueRepository { private Map<String, SessionMessageQueue<SessionRegistry.EnqueuedMessage>> queues = new HashMap<>(); @Override public Set<String> listQueueNames() { return Collections.unmodifiableSet(queues.keySet()); } @Override public boolean containsQueue(String queueName) { return queues.containsKey(queueName); } @Override public SessionMessageQueue<SessionRegistry.EnqueuedMessage> getOrCreateQueue(String clientId) {<FILL_FUNCTION_BODY>} @Override public void close() { queues.clear(); } void dropQueue(String queueName) { queues.remove(queueName); } }
if (containsQueue(clientId)) { return queues.get(clientId); } SessionMessageQueue<SessionRegistry.EnqueuedMessage> queue = new InMemoryQueue(this, clientId); queues.put(clientId, queue); return queue;
198
72
270
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/MemoryRetainedRepository.java
MemoryRetainedRepository
findMatching
class MemoryRetainedRepository implements IRetainedRepository { private final ConcurrentMap<Topic, RetainedMessage> storage = new ConcurrentHashMap<>(); private final ConcurrentMap<Topic, RetainedMessage> storageExpire = new ConcurrentHashMap<>(); @Override public void cleanRetained(Topic topic) { storage.remove(topic); storageExpire.remove(topic); } @Override public void retain(Topic topic, MqttPublishMessage msg) { byte[] rawPayload = payloadToByteArray(msg); final RetainedMessage toStore = new RetainedMessage(topic, msg.fixedHeader().qosLevel(), rawPayload, extractPropertiesArray(msg)); storage.put(topic, toStore); } @Override public void retain(Topic topic, MqttPublishMessage msg, Instant expiryTime) { byte[] rawPayload = payloadToByteArray(msg); final RetainedMessage toStore = new RetainedMessage(topic, msg.fixedHeader().qosLevel(), rawPayload, extractPropertiesArray(msg), expiryTime); storageExpire.put(topic, toStore); } private static MqttProperties.MqttProperty[] extractPropertiesArray(MqttPublishMessage msg) { MqttProperties properties = msg.variableHeader().properties(); return properties.listAll().toArray(new MqttProperties.MqttProperty[0]); } private static byte[] payloadToByteArray(MqttPublishMessage msg) { final ByteBuf payload = msg.content(); byte[] rawPayload = new byte[payload.readableBytes()]; payload.getBytes(0, rawPayload); return rawPayload; } @Override public boolean isEmpty() { return storage.isEmpty() && storageExpire.isEmpty(); } @Override public Collection<RetainedMessage> retainedOnTopic(String topic) { final Topic searchTopic = new Topic(topic); final List<RetainedMessage> matchingMessages = new ArrayList<>(); matchingMessages.addAll(findMatching(searchTopic, storage)); matchingMessages.addAll(findMatching(searchTopic, storageExpire)); return matchingMessages; } @Override public Collection<RetainedMessage> listExpirable() { return storageExpire.values(); } private List<RetainedMessage> findMatching(Topic searchTopic, ConcurrentMap<Topic, RetainedMessage> map) {<FILL_FUNCTION_BODY>} }
final List<RetainedMessage> matchingMessages = new ArrayList<>(); for (Map.Entry<Topic, RetainedMessage> entry : map.entrySet()) { final Topic scanTopic = entry.getKey(); if (scanTopic.match(searchTopic)) { matchingMessages.add(entry.getValue()); } } return matchingMessages;
644
94
738
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/MoquetteIdleTimeoutHandler.java
MoquetteIdleTimeoutHandler
userEventTriggered
class MoquetteIdleTimeoutHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(MoquetteIdleTimeoutHandler.class); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>} }
if (evt instanceof IdleStateEvent) { IdleState e = ((IdleStateEvent) evt).state(); if (e == IdleState.READER_IDLE) { LOG.warn("Close channel because it's inactive, passed keep alive. MqttClientId = {}.", NettyUtils.clientID(ctx.channel())); // fire a close that then fire channelInactive to trigger publish of Will ctx.close().addListener(CLOSE_ON_FAILURE); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Firing Netty event CId = {}, eventClass = {}", NettyUtils.clientID(ctx.channel()), evt.getClass().getName()); } super.userEventTriggered(ctx, evt); }
84
206
290
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/NettyUtils.java
NettyUtils
validateMessage
class NettyUtils { public static final String ATTR_USERNAME = "username"; private static final String ATTR_CLIENTID = "ClientID"; private static final String CLEAN_SESSION = "removeTemporaryQoS2"; private static final String KEEP_ALIVE = "keepAlive"; private static final AttributeKey<Object> ATTR_KEY_KEEPALIVE = AttributeKey.valueOf(KEEP_ALIVE); private static final AttributeKey<Object> ATTR_KEY_CLEANSESSION = AttributeKey.valueOf(CLEAN_SESSION); private static final AttributeKey<Object> ATTR_KEY_CLIENTID = AttributeKey.valueOf(ATTR_CLIENTID); private static final AttributeKey<Object> ATTR_KEY_USERNAME = AttributeKey.valueOf(ATTR_USERNAME); public static Object getAttribute(ChannelHandlerContext ctx, AttributeKey<Object> key) { Attribute<Object> attr = ctx.channel().attr(key); return attr.get(); } public static void keepAlive(Channel channel, int keepAlive) { channel.attr(NettyUtils.ATTR_KEY_KEEPALIVE).set(keepAlive); } public static void cleanSession(Channel channel, boolean cleanSession) { channel.attr(NettyUtils.ATTR_KEY_CLEANSESSION).set(cleanSession); } public static boolean cleanSession(Channel channel) { return (Boolean) channel.attr(NettyUtils.ATTR_KEY_CLEANSESSION).get(); } public static void clientID(Channel channel, String clientID) { channel.attr(NettyUtils.ATTR_KEY_CLIENTID).set(clientID); } public static String clientID(Channel channel) { return (String) channel.attr(NettyUtils.ATTR_KEY_CLIENTID).get(); } public static void userName(Channel channel, String username) { channel.attr(NettyUtils.ATTR_KEY_USERNAME).set(username); } public static String userName(Channel channel) { return (String) channel.attr(NettyUtils.ATTR_KEY_USERNAME).get(); } /** * Validate that the provided message is an MqttMessage and that it does not contain a failed result. * * @param message to be validated * @return the casted provided message * @throws IOException in case of an fail message this will wrap the root cause * @throws ClassCastException if the provided message is no MqttMessage */ public static MqttMessage validateMessage(Object message) throws IOException, ClassCastException {<FILL_FUNCTION_BODY>} private NettyUtils() { } }
MqttMessage msg = (MqttMessage) message; if (msg.decoderResult() != null && msg.decoderResult().isFailure()) { throw new IOException("Invalid message", msg.decoderResult().cause()); } if (msg.fixedHeader() == null) { throw new IOException("Unknown packet, no fixedHeader present, no cause provided"); } return msg;
694
105
799
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/NewNettyMQTTHandler.java
NewNettyMQTTHandler
channelRead
class NewNettyMQTTHandler extends ChannelInboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(NewNettyMQTTHandler.class); private static final String ATTR_CONNECTION = "connection"; private static final AttributeKey<Object> ATTR_KEY_CONNECTION = AttributeKey.valueOf(ATTR_CONNECTION); private MQTTConnectionFactory connectionFactory; NewNettyMQTTHandler(MQTTConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } private static void mqttConnection(Channel channel, MQTTConnection connection) { channel.attr(ATTR_KEY_CONNECTION).set(connection); } private static MQTTConnection mqttConnection(Channel channel) { return (MQTTConnection) channel.attr(ATTR_KEY_CONNECTION).get(); } @Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {<FILL_FUNCTION_BODY>} @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { final MQTTConnection mqttConnection = mqttConnection(ctx.channel()); mqttConnection.readCompleted(); } @Override public void channelActive(ChannelHandlerContext ctx) { MQTTConnection connection = connectionFactory.create(ctx.channel()); mqttConnection(ctx.channel(), connection); } @Override public void channelInactive(ChannelHandlerContext ctx) { final MQTTConnection mqttConnection = mqttConnection(ctx.channel()); mqttConnection.handleConnectionLost(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { LOG.error("Unexpected exception while processing MQTT message. Closing Netty channel. CId={}", NettyUtils.clientID(ctx.channel()), cause); ctx.close().addListener(CLOSE_ON_FAILURE); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) { // if (ctx.channel().isWritable()) { // m_processor.notifyChannelWritable(ctx.channel()); // } final MQTTConnection mqttConnection = mqttConnection(ctx.channel()); mqttConnection.writabilityChanged(); ctx.fireChannelWritabilityChanged(); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof InflightResender.ResendNotAckedPublishes) { final MQTTConnection mqttConnection = mqttConnection(ctx.channel()); mqttConnection.resendNotAckedPublishes(); } ctx.fireUserEventTriggered(evt); } }
MqttMessage msg = NettyUtils.validateMessage(message); final MQTTConnection mqttConnection = mqttConnection(ctx.channel()); try { mqttConnection.handleMessage(msg); } catch (Throwable ex) { //ctx.fireExceptionCaught(ex); LOG.error("Error processing protocol message: {}", msg.fixedHeader().messageType(), ex); ctx.channel().close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { LOG.info("Closed client channel due to exception in processing"); } }); } finally { ReferenceCountUtil.release(msg); }
720
175
895
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/PostOffice.java
PacketId
equals
class PacketId { private final String clientId; private final int idPacket; PacketId(String clientId, int idPacket) { this.clientId = clientId; this.idPacket = idPacket; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(clientId, idPacket); } public boolean belongToClient(String clientId) { return this.clientId.equals(clientId); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PacketId packetId = (PacketId) o; return idPacket == packetId.idPacket && Objects.equals(clientId, packetId.clientId);
156
78
234
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/RoutingResults.java
RoutingResults
preroutingError
class RoutingResults { final List<String> successedRoutings; final List<String> failedRoutings; private final CompletableFuture<Void> mergedAction; public RoutingResults(List<String> successedRoutings, List<String> failedRoutings, CompletableFuture<Void> mergedAction) { this.successedRoutings = successedRoutings; this.failedRoutings = failedRoutings; this.mergedAction = mergedAction; } public boolean isAllSuccess() { return failedRoutings.isEmpty(); } public boolean isAllFailed() { return successedRoutings.isEmpty() && !failedRoutings.isEmpty(); } public CompletableFuture<Void> completableFuture() { return mergedAction; } public static RoutingResults preroutingError() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "RoutingResults{" + "successedRoutings=" + successedRoutings + ", failedRoutings=" + failedRoutings + ", mergedAction=" + mergedAction + '}'; } }
// WARN this is a special case failed is empty, but this result is to be considered as error. return new RoutingResults(Collections.emptyList(), Collections.emptyList(), CompletableFuture.completedFuture(null));
303
56
359
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/SessionEventLoop.java
SessionEventLoop
run
class SessionEventLoop extends Thread { private static final Logger LOG = LoggerFactory.getLogger(SessionEventLoop.class); private final BlockingQueue<FutureTask<String>> sessionQueue; private final boolean flushOnExit; public SessionEventLoop(BlockingQueue<FutureTask<String>> sessionQueue) { this(sessionQueue, true); } /** * @param flushOnExit consume the commands queue before exit. * */ public SessionEventLoop(BlockingQueue<FutureTask<String>> sessionQueue, boolean flushOnExit) { this.sessionQueue = sessionQueue; this.flushOnExit = flushOnExit; } @Override public void run() {<FILL_FUNCTION_BODY>} public static void executeTask(final FutureTask<String> task) { if (!task.isCancelled()) { try { task.run(); // we ran it, but we have to grab the exception if raised task.get(); } catch (Throwable th) { LOG.warn("SessionEventLoop {} reached exception in processing command", Thread.currentThread().getName(), th); throw new RuntimeException(th); } } } }
while (!Thread.interrupted() || (Thread.interrupted() && !sessionQueue.isEmpty() && flushOnExit)) { try { // blocking call final FutureTask<String> task = this.sessionQueue.take(); executeTask(task); } catch (InterruptedException e) { LOG.info("SessionEventLoop {} interrupted", Thread.currentThread().getName()); Thread.currentThread().interrupt(); } } LOG.info("SessionEventLoop {} exit", Thread.currentThread().getName());
305
130
435
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/SessionEventLoopGroup.java
SessionEventLoopGroup
terminate
class SessionEventLoopGroup { private static final Logger LOG = LoggerFactory.getLogger(SessionEventLoopGroup.class); private final SessionEventLoop[] sessionExecutors; private final BlockingQueue<FutureTask<String>>[] sessionQueues; private final int eventLoops = Runtime.getRuntime().availableProcessors(); private final ConcurrentMap<String, Throwable> loopThrownExceptions = new ConcurrentHashMap<>(); SessionEventLoopGroup(BrokerInterceptor interceptor, int sessionQueueSize) { this.sessionQueues = new BlockingQueue[eventLoops]; for (int i = 0; i < eventLoops; i++) { this.sessionQueues[i] = new ArrayBlockingQueue<>(sessionQueueSize); } this.sessionExecutors = new SessionEventLoop[eventLoops]; for (int i = 0; i < eventLoops; i++) { SessionEventLoop newLoop = new SessionEventLoop(this.sessionQueues[i]); newLoop.setName(sessionLoopName(i)); newLoop.setUncaughtExceptionHandler((loopThread, ex) -> { // executed in session loop thread // collect the exception thrown to later re-throw loopThrownExceptions.put(loopThread.getName(), ex); // This is done in asynch from another thread in BrokerInterceptor interceptor.notifyLoopException(new InterceptExceptionMessage(ex)); }); newLoop.start(); this.sessionExecutors[i] = newLoop; } } int targetQueueOrdinal(String clientId) { return Math.abs(clientId.hashCode()) % this.eventLoops; } private String sessionLoopName(int i) { return "Session Executor " + i; } String sessionLoopThreadName(String clientId) { final int targetQueueId = targetQueueOrdinal(clientId); return sessionLoopName(targetQueueId); } /** * Route the command to the owning SessionEventLoop */ public PostOffice.RouteResult routeCommand(String clientId, String actionDescription, Callable<Void> action) { SessionCommand cmd = new SessionCommand(clientId, action); if (clientId == null) { LOG.warn("Routing collision for action [{}]", actionDescription); return PostOffice.RouteResult.failed(null, "Seems awaiting new route feature completion, skipping."); } final int targetQueueId = targetQueueOrdinal(cmd.getSessionId()); LOG.debug("Routing cmd [{}] for session [{}] to event processor {}", actionDescription, cmd.getSessionId(), targetQueueId); final FutureTask<String> task = new FutureTask<>(() -> { cmd.execute(); cmd.complete(); return cmd.getSessionId(); }); if (Thread.currentThread() == sessionExecutors[targetQueueId]) { SessionEventLoop.executeTask(task); return PostOffice.RouteResult.success(clientId, cmd.completableFuture()); } if (this.sessionQueues[targetQueueId].offer(task)) { return PostOffice.RouteResult.success(clientId, cmd.completableFuture()); } else { LOG.warn("Session command queue {} is full executing action {}", targetQueueId, actionDescription); return PostOffice.RouteResult.failed(clientId); } } public void terminate() {<FILL_FUNCTION_BODY>} public int getEventLoopCount() { return eventLoops; } }
for (SessionEventLoop processor : sessionExecutors) { processor.interrupt(); } for (SessionEventLoop processor : sessionExecutors) { try { processor.join(5_000); } catch (InterruptedException ex) { LOG.info("Interrupted while joining session event loop {}", processor.getName(), ex); } } for (Map.Entry<String, Throwable> loopThrownExceptionEntry : loopThrownExceptions.entrySet()) { String threadName = loopThrownExceptionEntry.getKey(); Throwable threadError = loopThrownExceptionEntry.getValue(); LOG.error("Session event loop {} terminated with error", threadName, threadError); }
899
181
1,080
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/SharedSubscriptionUtils.java
SharedSubscriptionUtils
extractShareName
class SharedSubscriptionUtils { /** * @return the share name in the topic filter of format $share/{shareName}/{topicFilter} * */ // VisibleForTesting protected static String extractShareName(String sharedTopicFilter) {<FILL_FUNCTION_BODY>} /** * @return the filter part from full topic filter of format $share/{shareName}/{topicFilter} * */ // VisibleForTesting protected static String extractFilterFromShared(String fullSharedTopicFilter) { int afterShare = "$share/".length(); int endOfShareName = fullSharedTopicFilter.indexOf('/', afterShare); return fullSharedTopicFilter.substring(endOfShareName + 1); } /** * @return true if topic filter is shared format * */ protected static boolean isSharedSubscription(String topicFilter) { Objects.requireNonNull(topicFilter, "topicFilter can't be null"); return topicFilter.startsWith("$share/"); } /** * @return true if shareName is well-formed, is at least one characted and doesn't contain wildcard matchers * */ protected static boolean validateShareName(String shareName) { // MQTT-4.8.2-1 MQTT-4.8.2-2, must be longer than 1 char and do not contain + or # Objects.requireNonNull(shareName); return shareName.length() > 0 && !shareName.contains("+") && !shareName.contains("#"); } }
int afterShare = "$share/".length(); int endOfShareName = sharedTopicFilter.indexOf('/', afterShare); return sharedTopicFilter.substring(afterShare, endOfShareName);
397
54
451
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/Utils.java
Couple
equals
class Couple<K, L> { public final K v1; public final L v2; public Couple(K v1, L v2) { this.v1 = v1; this.v2 = v2; } public static <K, L> Couple<K, L> of(K v1, L v2) { return new Couple<>(v1, v2); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(v1, v2); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Couple<?, ?> couple = (Couple<?, ?>) o; return Objects.equals(v1, couple.v1) && Objects.equals(v2, couple.v2);
170
86
256
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/config/ClasspathResourceLoader.java
ClasspathResourceLoader
loadResource
class ClasspathResourceLoader implements IResourceLoader { private static final Logger LOG = LoggerFactory.getLogger(ClasspathResourceLoader.class); private final String defaultResource; private final ClassLoader classLoader; public ClasspathResourceLoader() { this(IConfig.DEFAULT_CONFIG); } public ClasspathResourceLoader(String defaultResource) { this(defaultResource, Thread.currentThread().getContextClassLoader()); } public ClasspathResourceLoader(String defaultResource, ClassLoader classLoader) { this.defaultResource = defaultResource; this.classLoader = classLoader; } @Override public Reader loadDefaultResource() { return loadResource(defaultResource); } @Override public Reader loadResource(String relativePath) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "classpath resource"; } }
LOG.info("Loading resource. RelativePath = {}.", relativePath); InputStream is = this.classLoader.getResourceAsStream(relativePath); return is != null ? new InputStreamReader(is, StandardCharsets.UTF_8) : null;
235
66
301
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/config/ConfigurationParser.java
ConfigurationParser
parse
class ConfigurationParser { private static final Logger LOG = LoggerFactory.getLogger(ConfigurationParser.class); private Properties m_properties = new Properties(); /** * Parse the configuration from file. */ void parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return; } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return; } try { Reader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8); parse(reader); } catch (IOException fex) { LOG.warn("parsing not existing file {}, fallback on default configuration!", file.getAbsolutePath(), fex); } } /** * Parse the configuration * * @throws ParseException * if the format is not compliant. */ void parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>} Properties getProperties() { return m_properties; } }
if (reader == null) { // just log and return default properties LOG.warn("parsing NULL reader, so fallback on default configuration!"); return; } BufferedReader br = new BufferedReader(reader); String line; try { while ((line = br.readLine()) != null) { int commentMarker = line.indexOf('#'); if (commentMarker != -1) { if (commentMarker == 0) { // skip its a comment continue; } else { // it's a malformed comment throw new ParseException(line, commentMarker); } } else { if (line.isEmpty() || line.matches("^\\s*$")) { // skip it's a black line continue; } // split till the first space int delimiterIdx = line.indexOf(' '); String key = line.substring(0, delimiterIdx).trim(); String value = line.substring(delimiterIdx).trim(); m_properties.put(key, value); } } } catch (IOException ex) { throw new ParseException("Failed to read", 1); } finally { try { reader.close(); } catch (IOException e) { // ignore } }
322
344
666
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/config/FileResourceLoader.java
FileResourceLoader
loadResource
class FileResourceLoader implements IResourceLoader { private static final Logger LOG = LoggerFactory.getLogger(FileResourceLoader.class); private final File defaultFile; private final String parentPath; public FileResourceLoader() { this((File) null); } public FileResourceLoader(File defaultFile) { this(defaultFile, System.getProperty("moquette.path", null)); } public FileResourceLoader(String parentPath) { this(null, parentPath); } public FileResourceLoader(File defaultFile, String parentPath) { this.defaultFile = defaultFile; this.parentPath = parentPath; } @Override public Reader loadDefaultResource() { if (defaultFile != null) { return loadResource(defaultFile); } else { throw new IllegalArgumentException("Default file not set!"); } } @Override public Reader loadResource(String relativePath) { return loadResource(new File(parentPath, relativePath)); } public Reader loadResource(File f) {<FILL_FUNCTION_BODY>} @Override public String getName() { return "file"; } }
LOG.info("Loading file. Path = {}.", f.getAbsolutePath()); if (f.isDirectory()) { LOG.error("The given file is a directory. Path = {}.", f.getAbsolutePath()); throw new ResourceIsDirectoryException("File \"" + f + "\" is a directory!"); } try { return Files.newBufferedReader(f.toPath(), UTF_8); } catch (IOException e) { LOG.error("The file does not exist. Path = {}.", f.getAbsolutePath()); return null; }
313
146
459
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/config/FluentConfig.java
TLSConfig
build
class TLSConfig { private SSLProvider providerType; private KeyStoreType keyStoreType; private String keyStorePassword; private String keyManagerPassword; private String jksPath; private int sslPort; private TLSConfig() {} public void port(int port) { this.sslPort = port; validatePort(port); } public void sslProvider(SSLProvider providerType) { this.providerType = providerType; } public void jksPath(String jksPath) { this.jksPath = jksPath; } public void jksPath(Path jksPath) { jksPath(jksPath.toAbsolutePath().toString()); } public void keyStoreType(KeyStoreType keyStoreType) { this.keyStoreType = keyStoreType; } /** * @param keyStorePassword the password to access the KeyStore * */ public void keyStorePassword(String keyStorePassword) { this.keyStorePassword = keyStorePassword; } /** * @param keyManagerPassword the password to access the key manager. * */ public void keyManagerPassword(String keyManagerPassword) { this.keyManagerPassword = keyManagerPassword; } private String getSslProvider() { return providerType.name().toLowerCase(Locale.ROOT); } private String getJksPath() { return jksPath; } private String getKeyStoreType() { return keyStoreType.name().toLowerCase(Locale.ROOT); } } public FluentConfig withTLS(Consumer<TLSConfig> tlsBlock) { tlsConfig = new TLSConfig(); tlsBlock.accept(tlsConfig); configAccumulator.put(SSL_PORT_PROPERTY_NAME, Integer.toString(tlsConfig.sslPort)); configAccumulator.put(SSL_PROVIDER, tlsConfig.getSslProvider()); configAccumulator.put(JKS_PATH_PROPERTY_NAME, tlsConfig.getJksPath()); configAccumulator.put(KEY_STORE_TYPE, tlsConfig.getKeyStoreType()); configAccumulator.put(KEY_STORE_PASSWORD_PROPERTY_NAME, tlsConfig.keyStorePassword); configAccumulator.put(KEY_MANAGER_PASSWORD_PROPERTY_NAME, tlsConfig.keyManagerPassword); return this; } public IConfig build() {<FILL_FUNCTION_BODY>
if (creationKind != CreationKind.API) { throw new IllegalStateException("Can't build a configuration started directly by the server, use startServer method instead"); } return new MemoryConfig(configAccumulator);
663
60
723
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/config/IConfig.java
IConfig
durationProp
class IConfig { public static final String DEFAULT_CONFIG = "config/moquette.conf"; public static final String PORT_PROPERTY_NAME = "port"; public static final String HOST_PROPERTY_NAME = "host"; public static final String PASSWORD_FILE_PROPERTY_NAME = "password_file"; public static final String ALLOW_ANONYMOUS_PROPERTY_NAME = "allow_anonymous"; public static final String PEER_CERTIFICATE_AS_USERNAME = "peer_certificate_as_username"; public static final String AUTHENTICATOR_CLASS_NAME = "authenticator_class"; public static final String AUTHORIZATOR_CLASS_NAME = "authorizator_class"; public static final String PERSISTENT_QUEUE_TYPE_PROPERTY_NAME = "persistent_queue_type"; // h2 or segmented, default h2 public static final String DATA_PATH_PROPERTY_NAME = "data_path"; public static final String PERSISTENCE_ENABLED_PROPERTY_NAME = "persistence_enabled"; // true or false, default true /** * 0/immediate means immediate flush, like immediate_buffer_flush = true * -1/full means no explicit flush, let Netty flush when write buffers are full, like immediate_buffer_flush = false * a number of milliseconds to between flushes * */ public static final String BUFFER_FLUSH_MS_PROPERTY_NAME = "buffer_flush_millis"; public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port"; public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port"; public static final String WEB_SOCKET_PATH_PROPERTY_NAME = "websocket_path"; public static final String ACL_FILE_PROPERTY_NAME = "acl_file"; public static final String PERSISTENT_CLIENT_EXPIRATION_PROPERTY_NAME = "persistent_client_expiration"; public static final String SESSION_QUEUE_SIZE = "session_queue_size"; public static final String ENABLE_TELEMETRY_NAME = "telemetry_enabled"; /** * Defines the SSL implementation to use, default to "JDK". * @see io.netty.handler.ssl.SslProvider#name() */ public static final String SSL_PROVIDER = "ssl_provider"; public static final String SSL_PORT_PROPERTY_NAME = "ssl_port"; public static final String JKS_PATH_PROPERTY_NAME = "jks_path"; /** @see java.security.KeyStore#getInstance(String) for allowed types, default to "jks" */ public static final String KEY_STORE_TYPE = "key_store_type"; public static final String KEY_STORE_PASSWORD_PROPERTY_NAME = "key_store_password"; public static final String KEY_MANAGER_PASSWORD_PROPERTY_NAME = "key_manager_password"; public static final String NETTY_MAX_BYTES_PROPERTY_NAME = "netty.mqtt.message_size"; public static final String MAX_SERVER_GRANTED_QOS_PROPERTY_NAME = "max_server_granted_qos"; public static final int DEFAULT_NETTY_MAX_BYTES_IN_MESSAGE = 8092; public abstract void setProperty(String name, String value); /** * Same semantic of Properties * * @param name property name. * @return property value null if not found. * */ public abstract String getProperty(String name); /** * Same semantic of Properties * * @param name property name. * @param defaultValue default value to return in case the property doesn't exist. * @return property value. * */ public abstract String getProperty(String name, String defaultValue); void assignDefaults() { setProperty(PORT_PROPERTY_NAME, Integer.toString(BrokerConstants.PORT)); setProperty(HOST_PROPERTY_NAME, BrokerConstants.HOST); // setProperty(BrokerConstants.WEB_SOCKET_PORT_PROPERTY_NAME, // Integer.toString(BrokerConstants.WEBSOCKET_PORT)); setProperty(PASSWORD_FILE_PROPERTY_NAME, ""); // setProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME, // BrokerConstants.DEFAULT_PERSISTENT_PATH); setProperty(ALLOW_ANONYMOUS_PROPERTY_NAME, Boolean.TRUE.toString()); setProperty(AUTHENTICATOR_CLASS_NAME, ""); setProperty(AUTHORIZATOR_CLASS_NAME, ""); setProperty(NETTY_MAX_BYTES_PROPERTY_NAME, String.valueOf(DEFAULT_NETTY_MAX_BYTES_IN_MESSAGE)); setProperty(PERSISTENT_QUEUE_TYPE_PROPERTY_NAME, "segmented"); setProperty(DATA_PATH_PROPERTY_NAME, "data/"); setProperty(PERSISTENCE_ENABLED_PROPERTY_NAME, Boolean.TRUE.toString()); } public abstract IResourceLoader getResourceLoader(); public int intProp(String propertyName, int defaultValue) { String propertyValue = getProperty(propertyName); if (propertyValue == null) { return defaultValue; } return Integer.parseInt(propertyValue); } public boolean boolProp(String propertyName, boolean defaultValue) { String propertyValue = getProperty(propertyName); if (propertyValue == null) { return defaultValue; } return Boolean.parseBoolean(propertyValue); } public Duration durationProp(String propertyName) {<FILL_FUNCTION_BODY>} }
String propertyValue = getProperty(propertyName); final char timeSpecifier = propertyValue.charAt(propertyValue.length() - 1); final TemporalUnit periodType; switch (timeSpecifier) { case 's': periodType = ChronoUnit.SECONDS; break; case 'm': periodType = ChronoUnit.MINUTES; break; case 'h': periodType = ChronoUnit.HOURS; break; case 'd': periodType = ChronoUnit.DAYS; break; case 'w': periodType = ChronoUnit.WEEKS; break; case 'M': periodType = ChronoUnit.MONTHS; break; case 'y': periodType = ChronoUnit.YEARS; break; default: throw new IllegalStateException("Can' parse duration property " + propertyName + " with value: " + propertyValue + ", admitted only h, d, w, m, y"); } return Duration.of(Integer.parseInt(propertyValue.substring(0, propertyValue.length() - 1)), periodType);
1,503
299
1,802
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/metrics/BytesMetricsCollector.java
BytesMetricsCollector
computeMetrics
class BytesMetricsCollector { private AtomicLong readBytes = new AtomicLong(); private AtomicLong wroteBytes = new AtomicLong(); public BytesMetrics computeMetrics() {<FILL_FUNCTION_BODY>} public void sumReadBytes(long count) { readBytes.getAndAdd(count); } public void sumWroteBytes(long count) { wroteBytes.getAndAdd(count); } }
BytesMetrics allMetrics = new BytesMetrics(); allMetrics.incrementRead(readBytes.get()); allMetrics.incrementWrote(wroteBytes.get()); return allMetrics;
117
52
169
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/metrics/DropWizardMetricsHandler.java
DropWizardMetricsHandler
channelRead
class DropWizardMetricsHandler extends ChannelInboundHandlerAdapter { private MetricRegistry metrics; private Meter publishesMetrics; private Meter subscribeMetrics; private Counter connectedClientsMetrics; public void init(IConfig props) { this.metrics = new MetricRegistry(); this.publishesMetrics = metrics.meter("publish.requests"); this.subscribeMetrics = metrics.meter("subscribe.requests"); this.connectedClientsMetrics = metrics.counter("connect.num_clients"); // ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics) // .convertRatesTo(TimeUnit.SECONDS) // .convertDurationsTo(TimeUnit.MILLISECONDS) // .build(); // reporter.start(1, TimeUnit.MINUTES); final String email = props.getProperty(METRICS_LIBRATO_EMAIL_PROPERTY_NAME); final String token = props.getProperty(METRICS_LIBRATO_TOKEN_PROPERTY_NAME); final String source = props.getProperty(METRICS_LIBRATO_SOURCE_PROPERTY_NAME); Librato.reporter(this.metrics, email, token) .setSource(source) .start(10, TimeUnit.SECONDS); } @Override public void channelRead(ChannelHandlerContext ctx, Object message) {<FILL_FUNCTION_BODY>} @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { String clientID = NettyUtils.clientID(ctx.channel()); if (clientID != null && !clientID.isEmpty()) { this.connectedClientsMetrics.dec(); } ctx.fireChannelInactive(); } }
MqttMessage msg = (MqttMessage) message; MqttMessageType messageType = msg.fixedHeader().messageType(); switch (messageType) { case PUBLISH: this.publishesMetrics.mark(); break; case SUBSCRIBE: this.subscribeMetrics.mark(); break; case CONNECT: this.connectedClientsMetrics.inc(); break; case DISCONNECT: this.connectedClientsMetrics.dec(); break; default: break; } ctx.fireChannelRead(message);
461
157
618
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/metrics/MQTTMessageLogger.java
MQTTMessageLogger
logMQTTMessage
class MQTTMessageLogger extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(MQTTMessageLogger.class); @Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception { updateFishtags(ctx); logMQTTMessageRead(ctx, message); ctx.fireChannelRead(message); MDC.clear(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { updateFishtags(ctx); ctx.fireChannelReadComplete(); MDC.clear(); } private void updateFishtags(ChannelHandlerContext ctx) { MDC.put("channel", ctx.channel().toString()); final String clientId = NettyUtils.clientID(ctx.channel()); if (clientId != null && !clientId.isEmpty()) { MDC.put("client.id", "[" + clientId + "]"); } } private void logMQTTMessageRead(ChannelHandlerContext ctx, Object message) throws Exception { logMQTTMessage(ctx, message, "C->B"); } private void logMQTTMessageWrite(ChannelHandlerContext ctx, Object message) throws Exception { logMQTTMessage(ctx, message, "C<-B"); } private void logMQTTMessage(ChannelHandlerContext ctx, Object message, String direction) throws Exception {<FILL_FUNCTION_BODY>} @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { updateFishtags(ctx); LOG.info("Channel Inactive"); ctx.fireChannelInactive(); MDC.clear(); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { updateFishtags(ctx); logMQTTMessageWrite(ctx, msg); ctx.write(msg, promise).addListener(CLOSE_ON_FAILURE); MDC.clear(); } }
if (!(message instanceof MqttMessage)) { return; } MqttMessage msg = NettyUtils.validateMessage(message); String clientID = NettyUtils.clientID(ctx.channel()); MqttMessageType messageType = msg.fixedHeader().messageType(); MDC.put("msg.type", "[" + messageType.name() + "]"); switch (messageType) { case CONNACK: case PINGREQ: case PINGRESP: LOG.debug("{} {} <{}>", direction, messageType, clientID); break; case CONNECT: case DISCONNECT: LOG.info("{} {} <{}>", direction, messageType, clientID); break; case SUBSCRIBE: MqttSubscribeMessage subscribe = (MqttSubscribeMessage) msg; LOG.info("{} SUBSCRIBE <{}> to topics {}", direction, clientID, subscribe.payload().topicSubscriptions()); break; case UNSUBSCRIBE: MqttUnsubscribeMessage unsubscribe = (MqttUnsubscribeMessage) msg; LOG.info("{} UNSUBSCRIBE <{}> to topics <{}>", direction, clientID, unsubscribe.payload().topics()); break; case PUBLISH: MqttPublishMessage publish = (MqttPublishMessage) msg; LOG.debug("{} PUBLISH <{}> to topics <{}>", direction, clientID, publish.variableHeader().topicName()); break; case PUBREC: case PUBCOMP: case PUBREL: case PUBACK: case UNSUBACK: LOG.info("{} {} <{}> packetID <{}>", direction, messageType, clientID, messageId(msg)); break; case SUBACK: MqttSubAckMessage suback = (MqttSubAckMessage) msg; final List<Integer> grantedQoSLevels = suback.payload().grantedQoSLevels(); LOG.info("{} SUBACK <{}> packetID <{}>, grantedQoses {}", direction, clientID, messageId(msg), grantedQoSLevels); break; }
517
570
1,087
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/metrics/MessageMetricsCollector.java
MessageMetricsCollector
computeMetrics
class MessageMetricsCollector { private AtomicLong readMsgs = new AtomicLong(); private AtomicLong wroteMsgs = new AtomicLong(); public MessageMetrics computeMetrics() {<FILL_FUNCTION_BODY>} public void sumReadMessages(long count) { readMsgs.getAndAdd(count); } public void sumWroteMessages(long count) { wroteMsgs.getAndAdd(count); } }
MessageMetrics allMetrics = new MessageMetrics(); allMetrics.incrementRead(readMsgs.get()); allMetrics.incrementWrote(wroteMsgs.get()); return allMetrics;
119
52
171
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/scheduler/ScheduledExpirationService.java
ScheduledExpirationService
track
class ScheduledExpirationService<T extends Expirable> { private static final Logger LOG = LoggerFactory.getLogger(ScheduledExpirationService.class); static final Duration FIRER_TASK_INTERVAL = Duration.ofSeconds(1); private final DelayQueue<ExpirableTracker<T>> expiringEntities = new DelayQueue<>(); private final ScheduledFuture<?> expiredEntityTask; private final Clock clock; private final Consumer<T> action; private final Map<String, ExpirableTracker<T>> expiringEntitiesCache = new HashMap<>(); public ScheduledExpirationService(Clock clock, Consumer<T> action) { this.clock = clock; this.action = action; ScheduledExecutorService actionsExecutor = Executors.newSingleThreadScheduledExecutor(); this.expiredEntityTask = actionsExecutor.scheduleWithFixedDelay(this::checkExpiredEntities, FIRER_TASK_INTERVAL.getSeconds(), FIRER_TASK_INTERVAL.getSeconds(), TimeUnit.SECONDS); } private void checkExpiredEntities() { List<ExpirableTracker<T>> expiredEntities = new ArrayList<>(); int drainedEntities = expiringEntities.drainTo(expiredEntities); LOG.debug("Retrieved {} expired entity on {}", drainedEntities, expiringEntities.size()); expiredEntities.stream() .map(ExpirableTracker::expirable) .forEach(action); } public void track(String entityId, T entity) {<FILL_FUNCTION_BODY>} public boolean untrack(String entityId) { ExpirableTracker<T> entityTracker = expiringEntitiesCache.get(entityId); if (entityTracker == null) { return false; // not found } return expiringEntities.remove(entityTracker); } public void shutdown() { if (expiredEntityTask.cancel(false)) { LOG.info("Successfully cancelled expired entities task"); } else { LOG.warn("Can't cancel the execution of expired entities task, was already cancelled? {}, was done? {}", expiredEntityTask.isCancelled(), expiredEntityTask.isDone()); } } }
if (!entity.expireAt().isPresent()) { throw new RuntimeException("Can't track for expiration an entity without expiry instant, client_id: " + entityId); } ExpirableTracker<T> entityTracker = new ExpirableTracker<>(entity, clock); expiringEntities.add(entityTracker); expiringEntitiesCache.put(entityId, entityTracker);
597
104
701
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/ACLFileParser.java
ACLFileParser
parse
class ACLFileParser { private static final Logger LOG = LoggerFactory.getLogger(ACLFileParser.class); /** * Parse the configuration from file. * * @param file * to parse * @return the collector of authorizations form reader passed into. * @throws ParseException * if the format is not compliant. */ public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return AuthorizationsCollector.emptyImmutableCollector(); } try { Reader reader = Files.newBufferedReader(file.toPath(), UTF_8); return parse(reader); } catch (IOException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return AuthorizationsCollector.emptyImmutableCollector(); } } /** * Parse the ACL configuration file * * @param reader * to parse * @return the collector of authorizations form reader passed into. * @throws ParseException * if the format is not compliant. */ public static AuthorizationsCollector parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>} private ACLFileParser() { } }
if (reader == null) { // just log and return default properties LOG.warn("parsing NULL reader, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } BufferedReader br = new BufferedReader(reader); String line; AuthorizationsCollector collector = new AuthorizationsCollector(); Pattern emptyLine = Pattern.compile("^\\s*$"); Pattern commentLine = Pattern.compile("^#.*"); // As spec, comment lines should start with '#' Pattern invalidCommentLine = Pattern.compile("^\\s*#.*"); // This pattern has a dependency on filtering `commentLine`. Pattern endLineComment = Pattern.compile("^([\\w\\s\\/\\+]+#?)(\\s*#.*)$"); Matcher endLineCommentMatcher; try { while ((line = br.readLine()) != null) { if (line.isEmpty() || emptyLine.matcher(line).matches() || commentLine.matcher(line).matches()) { // skip it's a black line or comment continue; } else if (invalidCommentLine.matcher(line).matches()) { // it's a malformed comment int commentMarker = line.indexOf('#'); throw new ParseException(line, commentMarker); } endLineCommentMatcher = endLineComment.matcher(line); if (endLineCommentMatcher.matches()) { line = endLineCommentMatcher.group(1); } collector.parse(line); } } catch (IOException ex) { throw new ParseException("Failed to read", 1); } return collector;
447
437
884
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/Authorization.java
Authorization
equals
class Authorization { protected final Topic topic; protected final Permission permission; /** * Access rights */ enum Permission { READ, WRITE, READWRITE } Authorization(Topic topic) { this(topic, Permission.READWRITE); } Authorization(Topic topic, Permission permission) { this.topic = topic; this.permission = permission; } public boolean grant(Permission desiredPermission) { return permission == desiredPermission || permission == READWRITE; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int result = topic.hashCode(); result = 31 * result + permission.hashCode(); return result; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Authorization that = (Authorization) o; if (permission != that.permission) return false; if (!topic.equals(that.topic)) return false; return true;
217
92
309
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/AuthorizationsCollector.java
AuthorizationsCollector
canDoOperation
class AuthorizationsCollector implements IAuthorizatorPolicy { private List<Authorization> m_globalAuthorizations = new ArrayList<>(); private List<Authorization> m_patternAuthorizations = new ArrayList<>(); private Map<String, List<Authorization>> m_userAuthorizations = new HashMap<>(); private boolean m_parsingUsersSpecificSection; private boolean m_parsingPatternSpecificSection; private String m_currentUser = ""; static final AuthorizationsCollector emptyImmutableCollector() { AuthorizationsCollector coll = new AuthorizationsCollector(); coll.m_globalAuthorizations = Collections.emptyList(); coll.m_patternAuthorizations = Collections.emptyList(); coll.m_userAuthorizations = Collections.emptyMap(); return coll; } void parse(String line) throws ParseException { Authorization acl = parseAuthLine(line); if (acl == null) { // skip it's a user return; } if (m_parsingUsersSpecificSection) { // TODO in java 8 switch to m_userAuthorizations.putIfAbsent(m_currentUser, new // ArrayList()); if (!m_userAuthorizations.containsKey(m_currentUser)) { m_userAuthorizations.put(m_currentUser, new ArrayList<Authorization>()); } List<Authorization> userAuths = m_userAuthorizations.get(m_currentUser); userAuths.add(acl); } else if (m_parsingPatternSpecificSection) { m_patternAuthorizations.add(acl); } else { m_globalAuthorizations.add(acl); } } protected Authorization parseAuthLine(String line) throws ParseException { String[] tokens = line.split("\\s+"); String keyword = tokens[0].toLowerCase(); switch (keyword) { case "topic": return createAuthorization(line, tokens); case "user": m_parsingUsersSpecificSection = true; m_currentUser = tokens[1]; m_parsingPatternSpecificSection = false; return null; case "pattern": m_parsingUsersSpecificSection = false; m_currentUser = ""; m_parsingPatternSpecificSection = true; return createAuthorization(line, tokens); default: throw new ParseException(String.format("invalid line definition found %s", line), 1); } } private Authorization createAuthorization(String line, String[] tokens) throws ParseException { if (tokens.length > 2) { // if the tokenized lines has 3 token the second must be the permission try { Authorization.Permission permission = Authorization.Permission.valueOf(tokens[1].toUpperCase()); // bring topic with all original spacing Topic topic = new Topic(line.substring(line.indexOf(tokens[2]))); return new Authorization(topic, permission); } catch (IllegalArgumentException iaex) { throw new ParseException("invalid permission token", 1); } } Topic topic = new Topic(tokens[1]); return new Authorization(topic); } @Override public boolean canWrite(Topic topic, String user, String client) { return canDoOperation(topic, Authorization.Permission.WRITE, user, client); } @Override public boolean canRead(Topic topic, String user, String client) { return canDoOperation(topic, Authorization.Permission.READ, user, client); } private boolean canDoOperation(Topic topic, Authorization.Permission permission, String username, String client) {<FILL_FUNCTION_BODY>} private boolean matchACL(List<Authorization> auths, Topic topic, Authorization.Permission permission) { for (Authorization auth : auths) { if (auth.grant(permission)) { if (topic.match(auth.topic)) { return true; } } } return false; } private boolean isNotEmpty(String client) { return client != null && !client.isEmpty(); } public boolean isEmpty() { return m_globalAuthorizations.isEmpty(); } }
if (matchACL(m_globalAuthorizations, topic, permission)) { return true; } if (isNotEmpty(client) || isNotEmpty(username)) { for (Authorization auth : m_patternAuthorizations) { Topic substitutedTopic = new Topic(auth.topic.toString().replace("%c", client).replace("%u", username)); if (auth.grant(permission)) { if (topic.match(substitutedTopic)) { return true; } } } } if (isNotEmpty(username)) { if (m_userAuthorizations.containsKey(username)) { List<Authorization> auths = m_userAuthorizations.get(username); if (matchACL(auths, topic, permission)) { return true; } } } return false;
1,090
221
1,311
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/DBAuthenticator.java
DBAuthenticator
checkValid
class DBAuthenticator implements IAuthenticator { private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticator.class); private final MessageDigest messageDigest; private HikariDataSource dataSource; private String sqlQuery; public DBAuthenticator(IConfig conf) { this(conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DRIVER, ""), conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_URL, ""), conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_QUERY, ""), conf.getProperty(BrokerConstants.DB_AUTHENTICATOR_DIGEST, "")); } /** * provide authenticator from SQL database * * @param driver * : jdbc driver class like : "org.postgresql.Driver" * @param jdbcUrl * : jdbc url like : "jdbc:postgresql://host:port/dbname" * @param sqlQuery * : sql query like : "SELECT PASSWORD FROM USER WHERE LOGIN=?" * @param digestMethod * : password encoding algorithm : "MD5", "SHA-1", "SHA-256" */ public DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod) { this.sqlQuery = sqlQuery; this.dataSource = new HikariDataSource(); this.dataSource.setJdbcUrl(jdbcUrl); try { this.messageDigest = MessageDigest.getInstance(digestMethod); } catch (NoSuchAlgorithmException nsaex) { LOG.error(String.format("Can't find %s for password encoding", digestMethod), nsaex); throw new RuntimeException(nsaex); } } @Override public synchronized boolean checkValid(String clientId, String username, byte[] password) {<FILL_FUNCTION_BODY>} }
// Check Username / Password in DB using sqlQuery if (username == null || password == null) { LOG.info("username or password was null"); return false; } ResultSet resultSet = null; PreparedStatement preparedStatement = null; Connection conn = null; try { conn = this.dataSource.getConnection(); preparedStatement = conn.prepareStatement(this.sqlQuery); preparedStatement.setString(1, username); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { final String foundPwq = resultSet.getString(1); messageDigest.update(password); byte[] digest = messageDigest.digest(); String encodedPasswd = new String(Hex.encodeHex(digest)); return foundPwq.equals(encodedPasswd); } } catch (SQLException sqlex) { LOG.error("Error quering DB for username: {}", username, sqlex); } finally { try { if (resultSet != null) { resultSet.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { LOG.error("Error releasing connection to the datasource", username, e); } } return false;
510
361
871
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/DeclarativeAuthorizatorPolicy.java
Builder
writeTo
class Builder { private DeclarativeAuthorizatorPolicy instance; public Builder readFrom(Topic topic, String user, String client) { final DeclarativeAuthorizatorPolicy policy = createOrGet(); policy.addReadFrom(topic, user, client); return this; } public Builder writeTo(Topic topic, String user, String client) {<FILL_FUNCTION_BODY>} private DeclarativeAuthorizatorPolicy createOrGet() { if (instance == null) { instance = new DeclarativeAuthorizatorPolicy(); } return instance; } public IAuthorizatorPolicy build() { return createOrGet(); } }
final DeclarativeAuthorizatorPolicy policy = createOrGet(); policy.addWriteTo(topic, user, client); return this;
178
38
216
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/PemUtils.java
PemUtils
certificatesToPem
class PemUtils { private static final String certificateBoundaryType = "CERTIFICATE"; public static String certificatesToPem(Certificate... certificates) throws CertificateEncodingException, IOException {<FILL_FUNCTION_BODY>} /** * Copyright (c) 2000 - 2021 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org) * SPDX-License-Identifier: MIT * * <p>A generic PEM writer, based on RFC 1421 * From: https://javadoc.io/static/org.bouncycastle/bcprov-jdk15on/1.62/org/bouncycastle/util/io/pem/PemWriter.html</p> */ public static class PemWriter extends BufferedWriter { private static final int LINE_LENGTH = 64; private final char[] buf = new char[LINE_LENGTH]; /** * Base constructor. * * @param out output stream to use. */ public PemWriter(Writer out) { super(out); } /** * Writes a pem encoded string. * * @param type key type. * @param bytes encoded string * @throws IOException IO Exception */ public void writeObject(String type, byte[] bytes) throws IOException { writePreEncapsulationBoundary(type); writeEncoded(bytes); writePostEncapsulationBoundary(type); } private void writeEncoded(byte[] bytes) throws IOException { bytes = Base64.getEncoder().encode(bytes); for (int i = 0; i < bytes.length; i += buf.length) { int index = 0; while (index != buf.length) { if ((i + index) >= bytes.length) { break; } buf[index] = (char) bytes[i + index]; index++; } this.write(buf, 0, index); this.newLine(); } } private void writePreEncapsulationBoundary(String type) throws IOException { this.write("-----BEGIN " + type + "-----"); this.newLine(); } private void writePostEncapsulationBoundary(String type) throws IOException { this.write("-----END " + type + "-----"); this.newLine(); } } }
try (StringWriter str = new StringWriter(); PemWriter pemWriter = new PemWriter(str)) { for (Certificate certificate : certificates) { pemWriter.writeObject(certificateBoundaryType, certificate.getEncoded()); } pemWriter.close(); return str.toString(); }
629
85
714
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/security/ResourceAuthenticator.java
ResourceAuthenticator
parse
class ResourceAuthenticator implements IAuthenticator { protected static final Logger LOG = LoggerFactory.getLogger(ResourceAuthenticator.class); private Map<String, String> m_identities = new HashMap<>(); public ResourceAuthenticator(IResourceLoader resourceLoader, String resourceName) { try { MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsaex) { LOG.error("Can't find SHA-256 for password encoding", nsaex); throw new RuntimeException(nsaex); } LOG.info(String.format("Loading password %s %s", resourceLoader.getName(), resourceName)); Reader reader = null; try { reader = resourceLoader.loadResource(resourceName); if (reader == null) { LOG.warn(String.format("Parsing not existing %s %s", resourceLoader.getName(), resourceName)); } else { parse(reader); } } catch (IResourceLoader.ResourceIsDirectoryException e) { LOG.warn(String.format("Trying to parse directory %s", resourceName)); } catch (ParseException pex) { LOG.warn( String.format("Format error in parsing password %s %s", resourceLoader.getName(), resourceName), pex); } } private void parse(Reader reader) throws ParseException {<FILL_FUNCTION_BODY>} @Override public boolean checkValid(String clientId, String username, byte[] password) { if (username == null || password == null) { LOG.info("username or password was null"); return false; } String foundPwq = m_identities.get(username); if (foundPwq == null) { return false; } String encodedPasswd = DigestUtils.sha256Hex(password); return foundPwq.equals(encodedPasswd); } }
if (reader == null) { return; } BufferedReader br = new BufferedReader(reader); String line; try { while ((line = br.readLine()) != null) { int commentMarker = line.indexOf('#'); if (commentMarker != -1) { if (commentMarker == 0) { // skip its a comment continue; } else { // it's a malformed comment throw new ParseException(line, commentMarker); } } else { if (line.isEmpty() || line.matches("^\\s*$")) { // skip it's a black line continue; } // split till the first space int delimiterIdx = line.indexOf(':'); String username = line.substring(0, delimiterIdx).trim(); String password = line.substring(delimiterIdx + 1).trim(); m_identities.put(username, password); } } } catch (IOException ex) { throw new ParseException("Failed to read", 1); }
501
288
789
<no_super_class>
moquette-io_moquette
moquette/broker/src/main/java/io/moquette/broker/subscriptions/CTrie.java
UnsubscribeRequest
insert
class UnsubscribeRequest { private final Topic topicFilter; private final String clientId; private boolean shared = false; private ShareName shareName; private UnsubscribeRequest(String clientId, Topic topicFilter) { this.topicFilter = topicFilter; this.clientId = clientId; } public static UnsubscribeRequest buildNonShared(String clientId, Topic topicFilter) { return new UnsubscribeRequest(clientId, topicFilter); } public static UnsubscribeRequest buildShared(ShareName shareName, Topic topicFilter, String clientId) { if (topicFilter.headToken().name().startsWith("$share")) { throw new IllegalArgumentException("Topic filter of a shared subscription can't contains $share and share name"); } UnsubscribeRequest request = new UnsubscribeRequest(clientId, topicFilter); request.shared = true; request.shareName = shareName; return request; } public Topic getTopicFilter() { return topicFilter; } public boolean isShared() { return shared; } public ShareName getSharedName() { return shareName; } public String getClientId() { return clientId; } } interface IVisitor<T> { void visit(CNode node, int deep); T getResult(); } private static final Token ROOT = new Token("root"); private static final INode NO_PARENT = null; private enum Action { OK, REPEAT, OK_NEW // used to indicate that the action was successful and the subscription created a new branch } INode root; CTrie() { final CNode mainNode = new CNode(ROOT); this.root = new INode(mainNode); } Optional<CNode> lookup(Topic topic) { INode inode = this.root; Token token = topic.headToken(); while (!topic.isEmpty()) { Optional<INode> child = inode.mainNode().childOf(token); if (!child.isPresent()) { break; } topic = topic.exceptHeadToken(); inode = child.get(); token = topic.headToken(); } if (inode == null || !topic.isEmpty()) { return Optional.empty(); } return Optional.of(inode.mainNode()); } enum NavigationAction { MATCH, GODEEP, STOP } private NavigationAction evaluate(Topic topicName, CNode cnode, int depth) { // depth 0 is the root node of all the topics, so for topic filter // monitor/sensor we have <root> -> monitor -> sensor final boolean isFirstLevel = depth == 1; if (Token.MULTI.equals(cnode.getToken())) { Token token = topicName.headToken(); if (token != null && token.isReserved() && isFirstLevel) { // [MQTT-4.7.2-1] single wildcard can't match reserved topics // if reserved token is the first of the topicName return NavigationAction.STOP; } return NavigationAction.MATCH; } if (topicName.isEmpty()) { return NavigationAction.STOP; } final Token token = topicName.headToken(); if (Token.SINGLE.equals(cnode.getToken()) || cnode.getToken().equals(token) || ROOT.equals(cnode.getToken())) { if (Token.SINGLE.equals(cnode.getToken()) && token.isReserved() && isFirstLevel) { // [MQTT-4.7.2-1] single wildcard can't match reserved topics return NavigationAction.STOP; } return NavigationAction.GODEEP; } return NavigationAction.STOP; } public List<Subscription> recursiveMatch(Topic topicName) { return recursiveMatch(topicName, this.root, 0); } private List<Subscription> recursiveMatch(Topic topicName, INode inode, int depth) { CNode cnode = inode.mainNode(); if (cnode instanceof TNode) { return Collections.emptyList(); } NavigationAction action = evaluate(topicName, cnode, depth); if (action == NavigationAction.MATCH) { return cnode.sharedAndNonSharedSubscriptions(); } if (action == NavigationAction.STOP) { return Collections.emptyList(); } Topic remainingTopic = (ROOT.equals(cnode.getToken())) ? topicName : topicName.exceptHeadToken(); List<Subscription> subscriptions = new ArrayList<>(); // We should only consider the maximum three children children of // type #, + or exact match Optional<INode> subInode = cnode.childOf(Token.MULTI); if (subInode.isPresent()) { subscriptions.addAll(recursiveMatch(remainingTopic, subInode.get(), depth + 1)); } subInode = cnode.childOf(Token.SINGLE); if (subInode.isPresent()) { subscriptions.addAll(recursiveMatch(remainingTopic, subInode.get(), depth + 1)); } if (remainingTopic.isEmpty()) { subscriptions.addAll(cnode.sharedAndNonSharedSubscriptions()); } else { subInode = cnode.childOf(remainingTopic.headToken()); if (subInode.isPresent()) { subscriptions.addAll(recursiveMatch(remainingTopic, subInode.get(), depth + 1)); } } return subscriptions; } /** * @return true if the subscription didn't exist. * */ public boolean addToTree(SubscriptionRequest request) { Action res; do { res = insert(request.getTopicFilter(), this.root, request); } while (res == Action.REPEAT); return res == Action.OK_NEW; } private Action insert(Topic topic, final INode inode, SubscriptionRequest request) {<FILL_FUNCTION_BODY>
final Token token = topic.headToken(); final CNode cnode = inode.mainNode(); if (!topic.isEmpty()) { Optional<INode> nextInode = cnode.childOf(token); if (nextInode.isPresent()) { Topic remainingTopic = topic.exceptHeadToken(); return insert(remainingTopic, nextInode.get(), request); } } if (topic.isEmpty()) { return insertSubscription(inode, cnode, request); } else { return createNodeAndInsertSubscription(topic, inode, cnode, request); }
1,611
159
1,770
<no_super_class>