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<... |
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 == so... | 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("h... |
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);
... | 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, ... |
notNull(destinationSetter, "destinationSetter");
try {
destinationSetter.accept(destination, destinationValue(destinationSetter));
} catch (NullPointerException e) {
if (collector.getProxyErrors().hasErrors())
throw collector.getProxyErrors().toException();
throw e;
} catch (E... | 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);
... |
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 getLastDes... |
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> mutator... |
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)
... |
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 TypeInfoI... | 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 = destinat... |
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;
... | 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;
}
... |
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.... |
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 ... |
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<?... | 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 :... |
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_F... |
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))
retur... | 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 (DatatypeConfi... |
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(sourc... | 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 || destin... |
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(),
... |
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
... | 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.isAssign... |
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(((Calen... | 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(destination... |
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 (Il... | 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;... |
if (mappingContext.getSource() == null || !mappingContext.getSource().isPresent()) {
return null;
}
MappingContext<Object, Object> propertyContext = mappingContext.create(
mappingContext.getSource().get(), mappingContext.getDestinationType());
return mappingContext.getMappingEngine().map... | 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(... |
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;
... | 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
: MatchR... |
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<?> eleme... | 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
: MatchRe... |
Object source = context.getSource();
if (source == null)
return null;
Collection<Object> originalDestination = context.getDestination();
Collection<Object> destination = MappingContextHelper.createCollection(context);
Class<?> elementType = MappingContextHelper.resolveDestinationGenericType(... | 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 (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 < B... | 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;
}
... |
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.ofNull... | 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 ? MatchR... |
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)... | 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.NO... |
if (mappingContext.getSource() == null) {
return Optional.empty();
}
MappingContext<?, ?> propertyContext = mappingContext.create(
mappingContext.getSource(), MappingContextHelper.resolveDestinationGenericType(mappingContext));
Object destination = mappingContext.getMappingEngine(... | 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(s... |
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.f... |
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 = ... |
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... |
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 lis... |
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 {@co... |
Mapping mapping = context.getMapping();
if (mapping instanceof PropertyMapping) {
PropertyInfo destInfo = mapping.getLastDestinationProperty();
Class<?> elementType = TypeResolver.resolveRawArgument(destInfo.getGenericType(),
destInfo.getInitialType());
if (elementType != Ty... | 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... |
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(
... | 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... |
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<?> 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 ... |
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
p... |
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 = 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... | 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 membe... |
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, O... | 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);
}
/**
* Create... |
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);
}
... |
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 = ... |
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(AccessLevel.PACKAGE_PRIVATE);
modelMapper.addMappings(new PropertyMap<Customer, CustomerDTO>() {
@Override
protected void configure() {
using(... | 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.pers... |
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(perso... | 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... | 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 ... | 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 PropertyM... | 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()... |
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.cl... | 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.getC... | 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... | 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<... |
if (source.isJsonObject()) {
JsonObject subjObj = source.getAsJsonObject();
JsonElement propertyElement = subjObj.get(memberName);
if (propertyElement == null)
return null;
if (propertyElement.isJsonObject())
return propertyElement.getAsJsonObject();
if (propertyEleme... | 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)
? MatchResul... |
ArrayNode source = context.getSource();
if (source == null)
return null;
Collection<Object> destination = context.getDestination() == null
? MappingContextHelper.createCollection(context)
: context.getDestination();
Class<?> elementType = MappingContextHelper.resolveDestinationGe... | 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<?>... |
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) {
destin... | 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().... | 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.getClas... |
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) property... | 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.FU... |
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 {
Ma... | 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 memberNa... |
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().toBuilde... |
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(C... |
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 {
... | 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... | 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) {
... |
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);
retur... | 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>}
@O... |
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... | 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 f... |
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, ... |
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.war... | 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... |
// 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.channe... | 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.fireExcepti... |
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 "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);
... |
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.getDefaultAlgo... | 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 repos... |
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 = c... | 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... |
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) {
... |
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());
}
... | 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 clos... | 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_... |
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");
}
... | 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_CONNE... |
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 pr... | 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) ... |
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 ... |
// 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) {
... |
while (!Thread.interrupted() || (Thread.interrupted() && !sessionQueue.isEmpty() && flushOnExit)) {
try {
// blocking call
final FutureTask<String> task = this.sessionQueue.take();
executeTask(task);
} catch (InterruptedException e) {
... | 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.... |
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().availableProcesso... |
for (SessionEventLoop processor : sessionExecutors) {
processor.interrupt();
}
for (SessionEventLoop processor : sessionExecutors) {
try {
processor.join(5_000);
} catch (InterruptedException ex) {
LOG.info("Interrupted while j... | 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 f... |
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 b... |
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);
... |
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) {
... |
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... | 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(Fil... |
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... | 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) {
... |
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 AL... |
String propertyValue = getProperty(propertyName);
final char timeSpecifier = propertyValue.charAt(propertyValue.length() - 1);
final TemporalUnit periodType;
switch (timeSpecifier) {
case 's':
periodType = ChronoUnit.SECONDS;
break;
... | 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(... |
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.... |
MqttMessage msg = (MqttMessage) message;
MqttMessageType messageType = msg.fixedHeader().messageType();
switch (messageType) {
case PUBLISH:
this.publishesMetrics.mark();
break;
case SUBSCRIBE:
this.subscribeMetrics.mark();... | 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);
... |
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", "[" + messageTyp... | 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 sumWroteMe... |
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<>();
p... |
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);
... | 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 (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... | 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, Permissio... |
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;
... | 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 boolea... |
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... | 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.get... |
// 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 = nul... | 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;
}
pub... |
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... |
try (StringWriter str = new StringWriter();
PemWriter pemWriter = new PemWriter(str)) {
for (Certificate certificate : certificates) {
pemWriter.writeObject(certificateBoundaryType, certificate.getEncoded());
}
pemWriter.close();
re... | 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 {
... |
if (reader == null) {
return;
}
BufferedReader br = new BufferedReader(reader);
String line;
try {
while ((line = br.readLine()) != null) {
int commentMarker = line.indexOf('#');
if (commentMarker != -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.c... |
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 inse... | 1,611 | 159 | 1,770 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.