language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/NonNullLiteralTest.java
{ "start": 2171, "end": 2516 }
class ____ { public void testClassLiteral() { Type klass = String.class; } } """); assertCompiles(nonNullLiteralMatches(/* shouldMatch= */ true, Matchers.nonNullLiteral())); } @Test public void shouldNotMatchClassDeclaration() { writeFile( "A.java", """ public
A
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/chain/Chain.java
{ "start": 24932, "end": 26859 }
class ____" + " not match the previous Mapper's output key class."); } if (!inputValueClass.isAssignableFrom(previousMapperConf.getClass( MAPPER_OUTPUT_VALUE_CLASS, null))) { throw new IllegalArgumentException("The specified Mapper input value class" + " does not match the previous Mapper's output value class."); } } } protected static void setMapperConf(boolean isMap, Configuration jobConf, Class<?> inputKeyClass, Class<?> inputValueClass, Class<?> outputKeyClass, Class<?> outputValueClass, Configuration mapperConf, int index, String prefix) { // if the Mapper does not have a configuration, create an empty one if (mapperConf == null) { // using a Configuration without defaults to make it lightweight. // still the chain's conf may have all defaults and this conf is // overlapped to the chain configuration one. mapperConf = new Configuration(true); } // store the input/output classes of the mapper in the mapper conf mapperConf.setClass(MAPPER_INPUT_KEY_CLASS, inputKeyClass, Object.class); mapperConf .setClass(MAPPER_INPUT_VALUE_CLASS, inputValueClass, Object.class); mapperConf.setClass(MAPPER_OUTPUT_KEY_CLASS, outputKeyClass, Object.class); mapperConf.setClass(MAPPER_OUTPUT_VALUE_CLASS, outputValueClass, Object.class); // serialize the mapper configuration in the chain configuration. Stringifier<Configuration> stringifier = new DefaultStringifier<Configuration>(jobConf, Configuration.class); try { jobConf.set(prefix + CHAIN_MAPPER_CONFIG + index, stringifier .toString(new Configuration(mapperConf))); } catch (IOException ioEx) { throw new RuntimeException(ioEx); } // increment the chain counter jobConf.setInt(prefix + CHAIN_MAPPER_SIZE, index + 1); } /** * Sets the Reducer
does
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/deployment/items/InjectedEmitterBuildItem.java
{ "start": 540, "end": 3392 }
class ____ extends MultiBuildItem { /** * Creates a new instance of {@link InjectedEmitterBuildItem} setting the overflow strategy. * * @param name the name of the stream * @param emitterType emitterType * @param overflow the overflow strategy * @param bufferSize the buffer size, if overflow is set to {@code BUFFER} * @return the new {@link InjectedEmitterBuildItem} */ public static InjectedEmitterBuildItem of(String name, String emitterType, String overflow, int bufferSize, boolean hasBroadcast, int awaitSubscribers) { return new InjectedEmitterBuildItem(name, emitterType, overflow, bufferSize, hasBroadcast, awaitSubscribers); } /** * The name of the stream the emitter is connected to. */ private final String name; /** * The name of the overflow strategy. Valid values are {@code BUFFER, DROP, FAIL, LATEST, NONE}. * If not set, it uses {@code BUFFER} with a default buffer size. */ private final String overflow; /** * The buffer size, used when {@code overflow} is set to {@code BUFFER}. Not that if {@code overflow} is set to * {@code BUFFER} and {@code bufferSize} is not set, an unbounded buffer is used. */ private final int bufferSize; /** * Whether the emitter uses the {@link io.smallrye.reactive.messaging.annotations.Broadcast} annotation. */ private final boolean hasBroadcast; /** * The emitter type */ private final String emitterType; /** * If the emitter uses the {@link io.smallrye.reactive.messaging.annotations.Broadcast} annotation, indicates the * number of subscribers to be expected before subscribing upstream. */ private final int awaitSubscribers; public InjectedEmitterBuildItem(String name, String emitterType, String overflow, int bufferSize, boolean hasBroadcast, int awaitSubscribers) { this.name = name; this.overflow = overflow; this.emitterType = emitterType; this.bufferSize = bufferSize; this.hasBroadcast = hasBroadcast; this.awaitSubscribers = hasBroadcast ? awaitSubscribers : -1; } public EmitterConfiguration getEmitterConfig() { return new QuarkusEmitterConfiguration(name, EmitterFactoryForLiteral.of(loadEmitterClass()), OnOverflowLiteral.create(overflow, bufferSize), hasBroadcast ? new BroadcastLiteral(awaitSubscribers) : null); } private Class<?> loadEmitterClass() { try { return Class.forName(emitterType, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { // should not happen throw new RuntimeException(e); } } }
InjectedEmitterBuildItem
java
micronaut-projects__micronaut-core
http-server/src/main/java/io/micronaut/http/server/exceptions/URISyntaxHandler.java
{ "start": 1103, "end": 1777 }
class ____ extends ErrorExceptionHandler<URISyntaxException> { /** * Constructor. * @param responseProcessor Error Response Processor */ public URISyntaxHandler(ErrorResponseProcessor<?> responseProcessor) { super(responseProcessor); } @Override @NonNull protected Error error(URISyntaxException exception) { return new Error() { @Override public String getMessage() { return "Malformed URI"; } @Override public Optional<String> getTitle() { return Optional.of("Malformed URI"); } }; } }
URISyntaxHandler
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ApplicationClientProtocol.java
{ "start": 26883, "end": 27466 }
interface ____ get the details for a specific resource profile. * </p> * @param request request to get the details of a resource profile * @return Response containing the details for a particular resource profile * @throws YARNFeatureNotEnabledException if resource-profile is disabled * @throws YarnException if any error happens inside YARN * @throws IOException in case of other errors */ @Public @Unstable GetResourceProfileResponse getResourceProfile( GetResourceProfileRequest request) throws YarnException, IOException; /** * <p> * The
to
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/support/IndexComponentSelectorTests.java
{ "start": 707, "end": 1988 }
class ____ extends ESTestCase { public void testIndexComponentSelectorFromKey() { assertThat(IndexComponentSelector.getByKey("data"), equalTo(IndexComponentSelector.DATA)); assertThat(IndexComponentSelector.getByKey("failures"), equalTo(IndexComponentSelector.FAILURES)); assertThat(IndexComponentSelector.getByKey("*"), nullValue()); assertThat(IndexComponentSelector.getByKey("d*ta"), nullValue()); assertThat(IndexComponentSelector.getByKey("_all"), nullValue()); assertThat(IndexComponentSelector.getByKey("**"), nullValue()); assertThat(IndexComponentSelector.getByKey("failure"), nullValue()); } public void testIndexComponentSelectorFromId() { assertThat(IndexComponentSelector.getById((byte) 0), equalTo(IndexComponentSelector.DATA)); assertThat(IndexComponentSelector.getById((byte) 1), equalTo(IndexComponentSelector.FAILURES)); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> IndexComponentSelector.getById((byte) 2)); assertThat( exception.getMessage(), containsString("Unknown id of index component selector [2], available options are: {0=DATA, 1=FAILURES}") ); } }
IndexComponentSelectorTests
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/HasIdentifierTest.java
{ "start": 1593, "end": 2200 }
class ____ { A() { this(0); } A(int foo) {} } """); assertCompiles( methodHasIdentifierMatching( /* shouldMatch= */ true, hasIdentifier( new Matcher<IdentifierTree>() { @Override public boolean matches(IdentifierTree tree, VisitorState state) { return tree.getName().contentEquals("this"); } }))); } @Test public void shouldMatchLocalVar() { writeFile( "A.java", """ public
A
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/SubQueryInFromOneToManyTests.java
{ "start": 8603, "end": 9566 }
class ____ { private Integer id; private Name name; private Set<Contact> alternativeContacts; private Contact primaryContact; public Contact() { } public Contact(Integer id, Name name) { this.id = id; this.name = name; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } @OneToMany(mappedBy = "primaryContact") public Set<Contact> getAlternativeContacts() { return alternativeContacts; } public void setAlternativeContacts(Set<Contact> alternativeContacts) { this.alternativeContacts = alternativeContacts; } @ManyToOne(fetch = FetchType.LAZY) public Contact getPrimaryContact() { return primaryContact; } public void setPrimaryContact(Contact primaryContact) { this.primaryContact = primaryContact; } @Embeddable public static
Contact
java
elastic__elasticsearch
benchmarks/src/main/java/org/elasticsearch/benchmark/bytes/BytesArrayReadLongBenchmark.java
{ "start": 1561, "end": 2576 }
class ____ { @Param(value = { "1" }) private int dataMb; private BytesReference bytesArray; private StreamInput streamInput; @Setup public void initResults() throws IOException { final BytesStreamOutput tmp = new BytesStreamOutput(); final long bytes = ByteSizeValue.of(dataMb, ByteSizeUnit.MB).getBytes(); for (int i = 0; i < bytes / 8; i++) { tmp.writeLong(i); } bytesArray = tmp.copyBytes(); if (bytesArray instanceof BytesArray == false) { throw new AssertionError("expected BytesArray but saw [" + bytesArray.getClass() + "]"); } streamInput = bytesArray.streamInput(); } @Benchmark public long readLong() throws IOException { long res = 0L; streamInput.reset(); final int reads = bytesArray.length() / 8; for (int i = 0; i < reads; i++) { res = res ^ streamInput.readLong(); } return res; } }
BytesArrayReadLongBenchmark
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/test/replaces/InterfaceBImpl.java
{ "start": 691, "end": 811 }
class ____ implements InterfaceB { @Override public String doStuff() { return "real"; } }
InterfaceBImpl
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/ChannelsTests.java
{ "start": 1230, "end": 6987 }
class ____ extends ESTestCase { byte[] randomBytes; FileChannel fileChannel; @Override @Before public void setUp() throws Exception { super.setUp(); Path tmpFile = createTempFile(); FileChannel randomAccessFile = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE); fileChannel = new MockFileChannel(randomAccessFile); randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes(StandardCharsets.UTF_8); } @Override @After public void tearDown() throws Exception { fileChannel.close(); super.tearDown(); } public void testReadWriteThoughArrays() throws Exception { writeToChannel(randomBytes, fileChannel); byte[] readBytes = Channels.readFromFileChannel(fileChannel, 0, randomBytes.length); assertThat("read bytes didn't match written bytes", randomBytes, Matchers.equalTo(readBytes)); } public void testPartialReadWriteThroughArrays() throws Exception { int length = randomIntBetween(1, randomBytes.length / 2); int offset = randomIntBetween(0, randomBytes.length - length); writeToChannel(randomBytes, offset, length, fileChannel); int lengthToRead = randomIntBetween(1, length); int offsetToRead = randomIntBetween(0, length - lengthToRead); byte[] readBytes = new byte[randomBytes.length]; Channels.readFromFileChannel(fileChannel, offsetToRead, readBytes, offset + offsetToRead, lengthToRead); BytesReference source = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead); BytesReference read = new BytesArray(readBytes, offset + offsetToRead, lengthToRead); assertThat("read bytes didn't match written bytes", BytesReference.toBytes(source), Matchers.equalTo(BytesReference.toBytes(read))); } public void testBufferReadPastEOFWithException() throws Exception { int bytesToWrite = randomIntBetween(0, randomBytes.length - 1); writeToChannel(randomBytes, 0, bytesToWrite, fileChannel); try { Channels.readFromFileChannel(fileChannel, 0, bytesToWrite + 1 + randomInt(1000)); fail("Expected an EOFException"); } catch (EOFException e) { assertThat(e.getMessage(), containsString("read past EOF")); } } public void testBufferReadPastEOFWithoutException() throws Exception { int bytesToWrite = randomIntBetween(0, randomBytes.length - 1); writeToChannel(randomBytes, 0, bytesToWrite, fileChannel); byte[] bytes = new byte[bytesToWrite + 1 + randomInt(1000)]; int read = Channels.readFromFileChannel(fileChannel, 0, bytes, 0, bytes.length); assertThat(read, Matchers.lessThan(0)); } public void testReadWriteThroughBuffers() throws IOException { ByteBuffer source; if (randomBoolean()) { source = ByteBuffer.wrap(randomBytes); } else { source = ByteBuffer.allocateDirect(randomBytes.length); source.put(randomBytes); source.flip(); } Channels.writeToChannel(source, fileChannel); ByteBuffer copy; if (randomBoolean()) { copy = ByteBuffer.allocate(randomBytes.length); } else { copy = ByteBuffer.allocateDirect(randomBytes.length); } int read = Channels.readFromFileChannel(fileChannel, 0, copy); assertThat(read, Matchers.equalTo(randomBytes.length)); byte[] copyBytes = new byte[read]; copy.flip(); copy.get(copyBytes); assertThat("read bytes didn't match written bytes", randomBytes, Matchers.equalTo(copyBytes)); } public void testPartialReadWriteThroughBuffers() throws IOException { int length = randomIntBetween(1, randomBytes.length / 2); int offset = randomIntBetween(0, randomBytes.length - length); ByteBuffer source; if (randomBoolean()) { source = ByteBuffer.wrap(randomBytes, offset, length); } else { source = ByteBuffer.allocateDirect(length); source.put(randomBytes, offset, length); source.flip(); } Channels.writeToChannel(source, fileChannel); int lengthToRead = randomIntBetween(1, length); int offsetToRead = randomIntBetween(0, length - lengthToRead); ByteBuffer copy; if (randomBoolean()) { copy = ByteBuffer.allocate(lengthToRead); } else { copy = ByteBuffer.allocateDirect(lengthToRead); } int read = Channels.readFromFileChannel(fileChannel, offsetToRead, copy); assertThat(read, Matchers.equalTo(lengthToRead)); copy.flip(); BytesReference sourceRef = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead); byte[] tmp = new byte[copy.remaining()]; copy.duplicate().get(tmp); BytesReference copyRef = new BytesArray(tmp); assertTrue("read bytes didn't match written bytes", sourceRef.equals(copyRef)); } private static void writeToChannel(byte[] source, int offset, int length, FileChannel channel) throws IOException { if (randomBoolean()) { Channels.writeToChannel(source, offset, length, channel, channel.position()); } else { Channels.writeToChannel(source, offset, length, channel); } } private static void writeToChannel(byte[] source, FileChannel channel) throws IOException { if (randomBoolean()) { Channels.writeToChannel(source, channel, channel.position()); } else { Channels.writeToChannel(source, channel); } }
ChannelsTests
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/support/NotificationListenerHolder.java
{ "start": 1539, "end": 6149 }
class ____ { private @Nullable NotificationListener notificationListener; private @Nullable NotificationFilter notificationFilter; private @Nullable Object handback; protected @Nullable Set<Object> mappedObjectNames; /** * Set the {@link javax.management.NotificationListener}. */ public void setNotificationListener(@Nullable NotificationListener notificationListener) { this.notificationListener = notificationListener; } /** * Get the {@link javax.management.NotificationListener}. */ public @Nullable NotificationListener getNotificationListener() { return this.notificationListener; } /** * Set the {@link javax.management.NotificationFilter} associated * with the encapsulated {@link #getNotificationFilter() NotificationFilter}. * <p>May be {@code null}. */ public void setNotificationFilter(@Nullable NotificationFilter notificationFilter) { this.notificationFilter = notificationFilter; } /** * Return the {@link javax.management.NotificationFilter} associated * with the encapsulated {@link #getNotificationListener() NotificationListener}. * <p>May be {@code null}. */ public @Nullable NotificationFilter getNotificationFilter() { return this.notificationFilter; } /** * Set the (arbitrary) object that will be 'handed back' as-is by an * {@link javax.management.NotificationBroadcaster} when notifying * any {@link javax.management.NotificationListener}. * @param handback the handback object (can be {@code null}) * @see javax.management.NotificationListener#handleNotification(javax.management.Notification, Object) */ public void setHandback(@Nullable Object handback) { this.handback = handback; } /** * Return the (arbitrary) object that will be 'handed back' as-is by an * {@link javax.management.NotificationBroadcaster} when notifying * any {@link javax.management.NotificationListener}. * @return the handback object (may be {@code null}) * @see javax.management.NotificationListener#handleNotification(javax.management.Notification, Object) */ public @Nullable Object getHandback() { return this.handback; } /** * Set the {@link javax.management.ObjectName}-style name of the single MBean * that the encapsulated {@link #getNotificationFilter() NotificationFilter} * will be registered with to listen for {@link javax.management.Notification Notifications}. * Can be specified as {@code ObjectName} instance or as {@code String}. * @see #setMappedObjectNames */ public void setMappedObjectName(@Nullable Object mappedObjectName) { this.mappedObjectNames = (mappedObjectName != null ? new LinkedHashSet<>(Collections.singleton(mappedObjectName)) : null); } /** * Set an array of {@link javax.management.ObjectName}-style names of the MBeans * that the encapsulated {@link #getNotificationFilter() NotificationFilter} * will be registered with to listen for {@link javax.management.Notification Notifications}. * Can be specified as {@code ObjectName} instances or as {@code String}s. * @see #setMappedObjectName */ public void setMappedObjectNames(Object... mappedObjectNames) { this.mappedObjectNames = new LinkedHashSet<>(Arrays.asList(mappedObjectNames)); } /** * Return the list of {@link javax.management.ObjectName} String representations for * which the encapsulated {@link #getNotificationFilter() NotificationFilter} will * be registered as a listener for {@link javax.management.Notification Notifications}. * @throws MalformedObjectNameException if an {@code ObjectName} is malformed */ public ObjectName @Nullable [] getResolvedObjectNames() throws MalformedObjectNameException { if (this.mappedObjectNames == null) { return null; } ObjectName[] resolved = new ObjectName[this.mappedObjectNames.size()]; int i = 0; for (Object objectName : this.mappedObjectNames) { resolved[i] = ObjectNameManager.getInstance(objectName); i++; } return resolved; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof NotificationListenerHolder that && ObjectUtils.nullSafeEquals(this.notificationListener, that.notificationListener) && ObjectUtils.nullSafeEquals(this.notificationFilter, that.notificationFilter) && ObjectUtils.nullSafeEquals(this.handback, that.handback) && ObjectUtils.nullSafeEquals(this.mappedObjectNames, that.mappedObjectNames))); } @Override public int hashCode() { return ObjectUtils.nullSafeHash(this.notificationListener, this.notificationFilter, this.handback, this.mappedObjectNames); } }
NotificationListenerHolder
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/convert/value/ConvertibleValues.java
{ "start": 1594, "end": 9884 }
interface ____<V> extends ValueResolver<CharSequence>, Iterable<Map.Entry<String, V>>, ConversionServiceProvider { ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap()); /** * @return The names of the values */ Set<String> names(); /** * @return The values */ Collection<V> values(); /** * @return Whether these values are empty */ default boolean isEmpty() { return this == ConvertibleValues.EMPTY || names().isEmpty(); } /** * @return The concrete type of the value */ @SuppressWarnings("unchecked") default Class<V> getValueType() { Optional<Class<?>> type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class); return (Class<V>) type.orElse(Object.class); } /** * Whether the given key is contained within these values. * * @param name The key name * @return True if it is */ default boolean contains(String name) { return get(name, Argument.OBJECT_ARGUMENT).isPresent(); } /** * Get a raw value without any conversion. * * @param name The key name * @return True if it is * @since 2.0.0 */ default @Nullable V getValue(CharSequence name) { return (V) get(name, Argument.OBJECT_ARGUMENT).orElse(null); } /** * Performs the given action for each value. Note that in the case * where multiple values exist for the same header then the consumer will be invoked * multiple times for the same key. * * @param action The action to be performed for each entry * @throws NullPointerException if the specified action is null * @since 1.0 */ default void forEach(BiConsumer<String, V> action) { Objects.requireNonNull(action, "Consumer cannot be null"); Collection<String> headerNames = names(); for (String headerName : headerNames) { Optional<V> vOptional = this.get(headerName, getValueType()); vOptional.ifPresent(v -> action.accept(headerName, v)); } } /** * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance. * * @return The values */ default Map<String, V> asMap() { Map<String, V> newMap = new LinkedHashMap<>(); for (Map.Entry<String, V> entry : this) { String key = entry.getKey(); newMap.put(key, entry.getValue()); } return newMap; } /** * Return this {@link ConvertibleValues} as a map for the given key type and value type. If any entry cannot be * converted to the target key/value type then the entry is simply excluded, hence the size of the map returned * may not match the size of this {@link ConvertibleValues}. * * @param keyType The key type * @param valueType The value type * @param <KT> The key type * @param <VT> The value type * @return The values with the key converted to the given key type and the value to the given value type. */ default <KT, VT> Map<KT, VT> asMap(Class<KT> keyType, Class<VT> valueType) { Map<KT, VT> newMap = new LinkedHashMap<>(); for (Map.Entry<String, V> entry : this) { String key = entry.getKey(); Optional<KT> convertedKey = getConversionService().convert(key, keyType); if (convertedKey.isPresent()) { Optional<VT> convertedValue = getConversionService().convert(entry.getValue(), valueType); convertedValue.ifPresent(vt -> newMap.put(convertedKey.get(), vt)); } } return newMap; } /** * Return this {@link ConvertibleValues} as a {@link Properties} object returning only keys and values that * can be represented as a string. * * @return The values with the key converted to the given key type and the value to the given value type. * @since 1.0.3 */ default Properties asProperties() { Properties props = new Properties(); for (Map.Entry<String, V> entry : this) { String key = entry.getKey(); V value = entry.getValue(); if (value instanceof CharSequence || value instanceof Number) { props.setProperty(key, value.toString()); } } return props; } /** * Returns a submap for all the keys with the given prefix. * * @param prefix The prefix * @param valueType The value type * @return The submap */ @SuppressWarnings("unchecked") default Map<String, V> subMap(String prefix, Class<V> valueType) { return subMap(prefix, Argument.of(valueType)); } /** * Returns a submap for all the keys with the given prefix. * * @param prefix The prefix * @param valueType The value type * @return The submap */ @SuppressWarnings("unchecked") default Map<String, V> subMap(String prefix, Argument<V> valueType) { return subMap(prefix, ConversionContext.of(valueType)); } /** * Returns a submap for all the keys with the given prefix. * * @param prefix The prefix * @param valueType The value type * @return The submap */ @SuppressWarnings("unchecked") default Map<String, V> subMap(String prefix, ArgumentConversionContext<V> valueType) { // special handling for maps for resolving sub keys String finalPrefix = prefix + '.'; return names().stream() .filter(name -> name.startsWith(finalPrefix)) .collect(Collectors.toMap(name -> name.substring(finalPrefix.length()), name -> get(name, valueType).orElse(null))); } @SuppressWarnings("NullableProblems") @Override default Iterator<Map.Entry<String, V>> iterator() { Iterator<String> names = names().iterator(); return new Iterator<>() { @Override public boolean hasNext() { return names.hasNext(); } @Override public Map.Entry<String, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } String name = names.next(); return new Map.Entry<>() { @Override public String getKey() { return name; } @Override public V getValue() { return get(name, getValueType()).orElse(null); } @Override public V setValue(V value) { throw new UnsupportedOperationException("Not mutable"); } }; } }; } /** * Creates a new {@link ConvertibleValues} for the values. * * @param values A map of values * @param <T> The target generic type * @return The values */ static <T> ConvertibleValues<T> of(Map<? extends CharSequence, T> values) { return of(values, ConversionService.SHARED); } /** * Creates a new {@link ConvertibleValues} for the values. * * @param values A map of values * @param conversionService The conversion service * @param <T> The target generic type * @return The values * @since 4.0.0 */ static <T> ConvertibleValues<T> of(Map<? extends CharSequence, T> values, ConversionService conversionService) { if (values == null) { return ConvertibleValuesMap.empty(); } else { return new ConvertibleValuesMap<>(values, conversionService); } } /** * An empty {@link ConvertibleValues}. * * @param <V> The generic type * @return The empty {@link ConvertibleValues} */ @SuppressWarnings("unchecked") static <V> ConvertibleValues<V> empty() { return ConvertibleValues.EMPTY; } @Override default ConversionService getConversionService() { return ConversionService.SHARED; } }
ConvertibleValues
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/steps/ClassTransformingBuildStep.java
{ "start": 17065, "end": 20797 }
class ____ it from the original archive Map<ArtifactKey, Set<String>> removed = new HashMap<>(); for (Map.Entry<String, Set<String>> entry : classLoadingConfig.removedResources().entrySet()) { removed.put(new GACT(entry.getKey().split(":")), entry.getValue()); } for (RemovedResourceBuildItem i : removedResourceBuildItems) { removed.computeIfAbsent(i.getArtifact(), k -> new HashSet<>()).addAll(i.getResources()); } if (!removed.isEmpty()) { ApplicationModel applicationModel = curateOutcomeBuildItem.getApplicationModel(); Collection<ResolvedDependency> runtimeDependencies = applicationModel.getRuntimeDependencies(); List<ResolvedDependency> allArtifacts = new ArrayList<>(runtimeDependencies.size() + 1); allArtifacts.addAll(runtimeDependencies); allArtifacts.add(applicationModel.getAppArtifact()); for (ResolvedDependency i : allArtifacts) { Set<String> filtered = removed.remove(i.getKey()); if (filtered != null) { for (Path path : i.getResolvedPaths()) { transformedClassesByJar.computeIfAbsent(path, s -> new HashSet<>()) .addAll(filtered.stream() .map(file -> new TransformedClassesBuildItem.TransformedClass(null, null, file, false)) .collect(Collectors.toSet())); } } } } if (!removed.isEmpty()) { log.warn("Could not remove configured resources from the following artifacts as they were not found in the model: " + removed); } } private byte[] transformClass(String className, List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors, byte[] classData, List<BiFunction<String, byte[], byte[]>> preVisitFunctions, int classReaderOptions) { for (BiFunction<String, byte[], byte[]> i : preVisitFunctions) { classData = i.apply(className, classData); if (classData == null) { return null; } } byte[] data; if (!visitors.isEmpty()) { ClassReader cr = new ClassReader(classData); ClassWriter writer = new QuarkusClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); ClassVisitor visitor = writer; for (BiFunction<String, ClassVisitor, ClassVisitor> i : visitors) { visitor = i.apply(className, visitor); if (visitor instanceof QuarkusClassVisitor) { ((QuarkusClassVisitor) visitor).setOriginalClassReaderOptions(classReaderOptions); } } cr.accept(visitor, classReaderOptions); data = writer.toByteArray(); } else { data = classData; } var debugTransformedClassesDir = BootstrapDebug.transformedClassesDir(); if (debugTransformedClassesDir != null) { File debugPath = new File(debugTransformedClassesDir); if (!debugPath.exists()) { debugPath.mkdir(); } File classFile = new File(debugPath, fromClassNameToResourceName(className)); classFile.getParentFile().mkdirs(); try (FileOutputStream classWriter = new FileOutputStream(classFile)) { classWriter.write(data); } catch (Exception e) { log.errorf(e, "Failed to write transformed class %s", className); } log.infof("Wrote transformed
removes
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java
{ "start": 10692, "end": 10918 }
class ____ extends InheritedDefaultListenersTestCase { } @TestExecutionListeners( {FooTestExecutionListener.class, BarTestExecutionListener.class, BazTestExecutionListener.class}) static
NonInheritedDefaultListenersTestCase
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/reflect/ReflectNestedObjectArrayTest.java
{ "start": 2476, "end": 3563 }
class ____ extends BasicArrayState { private final Schema schema; private ObjectArrayWrapper[] testData; private Encoder encoder; private ReflectDatumWriter<ObjectArrayWrapper> datumWriter; public TestStateEncode() { super(ARRAY_SIZE); final String jsonText = ReflectData.get().getSchema(ObjectArrayWrapper.class).toString(); this.schema = new Schema.Parser().parse(jsonText); } /** * Setup the trial data. * * @throws IOException Could not setup test data */ @Setup(Level.Trial) public void doSetupTrial() throws Exception { this.encoder = super.newEncoder(false, getNullOutputStream()); this.datumWriter = new ReflectDatumWriter<>(schema); this.testData = new ObjectArrayWrapper[getBatchSize()]; for (int i = 0; i < testData.length; i++) { ObjectArrayWrapper wrapper = new ObjectArrayWrapper(); wrapper.value = populateRecordArray(getRandom(), getArraySize()); this.testData[i] = wrapper; } } } @State(Scope.Thread) public static
TestStateEncode
java
apache__camel
components/camel-openapi-java/src/test/java/org/apache/camel/openapi/RestOpenApiReaderModelTest.java
{ "start": 6224, "end": 6343 }
enum ____ no allowable values are set assertFalse(json.contains("\"enum\"")); context.stop(); } }
when
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/math/AbstractTrigonometricFunction.java
{ "start": 1045, "end": 2104 }
class ____ extends UnaryScalarFunction { AbstractTrigonometricFunction(Source source, Expression field) { super(source, field); } protected AbstractTrigonometricFunction(StreamInput in) throws IOException { super(in); } /** * Build an evaluator for this function given the evaluator for it’s input. */ protected abstract EvalOperator.ExpressionEvaluator.Factory doubleEvaluator(EvalOperator.ExpressionEvaluator.Factory field); @Override public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { return doubleEvaluator(Cast.cast(source(), field().dataType(), DataType.DOUBLE, toEvaluator.apply(field()))); } @Override protected final TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } return isNumeric(field, sourceText(), DEFAULT); } @Override public final DataType dataType() { return DataType.DOUBLE; } }
AbstractTrigonometricFunction
java
google__error-prone
check_api/src/main/java/com/google/errorprone/fixes/BranchedSuggestedFixes.java
{ "start": 772, "end": 1310 }
class ____ accumulating a branching tree of alternative fixes designed to help build as set * of potential fixes with different options in them. * * <p>Consider building a list of fixes from a set of operations A followed by B or C then D or E. * The resulting list should be ABD, ACD, ABE, ACE. * * <pre>{@code * BranchedSuggestedFixes a = BranchedSuggestedFixes.builder() * .startWith(A) * .then() * .addOption(B) * .addOption(C) * .then() * .addOption(D) * .addOption(E) * .build(); * }</pre> * * This
for
java
alibaba__druid
core/src/test/java/com/alibaba/druid/benckmark/pool/Case1.java
{ "start": 1412, "end": 1947 }
class ____ extends TestCase { private String jdbcUrl; private String user; private String password; private String driverClass; private int initialSize = 10; private int minPoolSize = 10; private int maxPoolSize = 50; private int maxActive = 50; private String validationQuery = "SELECT 1"; private int threadCount = 5; private int loopCount = 10; final int LOOP_COUNT = 1000 * 1 * 1 / threadCount; private static AtomicLong physicalConnStat = new AtomicLong(); public static
Case1
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 18271, "end": 18626 }
class ____ { @SomeAnnotation Void foo() { return null; } } """) .doTest(); } @Test public void qualifyType_someOtherNullable() { AddAnnotation.testHelper(getClass()) .addInputLines( "in/SomeAnnotation.java", // "@
AddAnnotation
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowVerifyInjectedAccessTokenDisabledTest.java
{ "start": 601, "end": 1925 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(ProtectedResourceWithJwtAccessToken.class) .addAsResource("application-verify-injected-access-token-disabled.properties", "application.properties")); @Test public void testVerifyAccessTokenDisabled() throws IOException, InterruptedException { try (final WebClient webClient = createWebClient()) { HtmlPage page = webClient.getPage("http://localhost:8081/protected"); assertEquals("Sign in to quarkus", page.getTitleText()); HtmlForm loginForm = page.getForms().get(0); loginForm.getInputByName("username").setValueAttribute("alice"); loginForm.getInputByName("password").setValueAttribute("alice"); page = loginForm.getButtonByName("login").click(); assertEquals("alice:false", page.getBody().asNormalizedText()); webClient.getCookieManager().clearCookies(); } } private WebClient createWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); return webClient; } }
CodeFlowVerifyInjectedAccessTokenDisabledTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/property/access/internal/PropertyAccessStrategyBackRefImpl.java
{ "start": 2199, "end": 3156 }
class ____ implements Getter { private final String entityName; private final String propertyName; public GetterImpl(String entityName, String propertyName) { this.entityName = entityName; this.propertyName = propertyName; } @Override public Object get(Object owner) { return UNKNOWN; } @Override public Object getForInsert(Object owner, Map<Object, Object> mergeMap, SharedSessionContractImplementor session) { return session.getPersistenceContextInternal().getOwnerId( entityName, propertyName, owner, mergeMap ); } @Override public Class<?> getReturnTypeClass() { return Object.class; } @Override public Type getReturnType() { return Object.class; } @Override public @Nullable Member getMember() { return null; } @Override public @Nullable String getMethodName() { return null; } @Override public @Nullable Method getMethod() { return null; } } private static
GetterImpl
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/nfa/NFAStatusChangeITCase.java
{ "start": 1854, "end": 12503 }
class ____ { private SharedBuffer<Event> sharedBuffer; private SharedBufferAccessor<Event> sharedBufferAccessor; private AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.noSkip(); private TimerService timerService = new TestTimerService(); @Before public void init() { this.sharedBuffer = TestSharedBuffer.createTestBuffer(Event.createTypeSerializer()); sharedBufferAccessor = sharedBuffer.getAccessor(); } @After public void clear() throws Exception { sharedBufferAccessor.close(); } @Test public void testNFAChange() throws Exception { Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .followedByAny("middle") .where( new IterativeCondition<Event>() { private static final long serialVersionUID = 8061969839441121955L; @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("b"); } }) .oneOrMore() .optional() .allowCombinations() .followedBy("middle2") .where( new IterativeCondition<Event>() { private static final long serialVersionUID = 8061969839441121955L; @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("d"); } }) .followedBy("end") .where( new IterativeCondition<Event>() { private static final long serialVersionUID = 8061969839441121955L; @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("e"); } }) .within(Duration.ofMillis(10)); NFA<Event> nfa = compile(pattern, true); NFAState nfaState = nfa.createInitialNFAState(); nfa.process( sharedBufferAccessor, nfaState, new Event(1, "b", 1.0), 1L, skipStrategy, timerService); assertFalse( "NFA status should not change as the event does not match the take condition of the 'start' state", nfaState.isStateChanged()); nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(2, "a", 1.0), 2L, skipStrategy, timerService); assertTrue( "NFA status should change as the event matches the take condition of the 'start' state", nfaState.isStateChanged()); // the status of the queue of ComputationStatus changed, // more than one ComputationStatus is generated by the event from some ComputationStatus nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(3, "f", 1.0), 3L, skipStrategy, timerService); assertTrue( "NFA status should change as the event matches the ignore condition and proceed condition of the 'middle:1' state", nfaState.isStateChanged()); // both the queue of ComputationStatus and eventSharedBuffer have not changed nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(4, "f", 1.0), 4L, skipStrategy, timerService); assertFalse( "NFA status should not change as the event only matches the ignore condition of the 'middle:2' state and the target state is still 'middle:2'", nfaState.isStateChanged()); // both the queue of ComputationStatus and eventSharedBuffer have changed nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(5, "b", 1.0), 5L, skipStrategy, timerService); assertTrue( "NFA status should change as the event matches the take condition of 'middle:2' state", nfaState.isStateChanged()); // both the queue of ComputationStatus and eventSharedBuffer have changed nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(6, "d", 1.0), 6L, skipStrategy, timerService); assertTrue( "NFA status should change as the event matches the take condition of 'middle2' state", nfaState.isStateChanged()); // both the queue of ComputationStatus and eventSharedBuffer have not changed // as the timestamp is within the window nfaState.resetStateChanged(); nfa.advanceTime(sharedBufferAccessor, nfaState, 8L, skipStrategy); assertFalse( "NFA status should not change as the timestamp is within the window", nfaState.isStateChanged()); // timeout ComputationStatus will be removed from the queue of ComputationStatus and timeout // event will // be removed from eventSharedBuffer as the timeout happens nfaState.resetStateChanged(); Collection<Tuple2<Map<String, List<Event>>, Long>> timeoutResults = nfa.advanceTime(sharedBufferAccessor, nfaState, 12L, skipStrategy).f1; assertTrue( "NFA status should change as timeout happens", nfaState.isStateChanged() && !timeoutResults.isEmpty()); } @Test public void testNFAChangedOnOneNewComputationState() throws Exception { Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("start"))) .followedBy("a*") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .oneOrMore() .optional() .next("end") .where( new IterativeCondition<Event>() { private static final long serialVersionUID = 8061969839441121955L; @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("b"); } }) .within(Duration.ofMillis(10)); NFA<Event> nfa = compile(pattern, true); NFAState nfaState = nfa.createInitialNFAState(); nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(6, "start", 1.0), 6L, skipStrategy, timerService); nfaState.resetStateChanged(); nfa.process( sharedBufferAccessor, nfaState, new Event(6, "a", 1.0), 7L, skipStrategy, timerService); assertTrue(nfaState.isStateChanged()); } @Test public void testNFAChangedOnTimeoutWithoutPrune() throws Exception { Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where( new IterativeCondition<Event>() { @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("start"); } }) .followedBy("end") .where( new IterativeCondition<Event>() { private static final long serialVersionUID = 8061969839441121955L; @Override public boolean filter(Event value, Context<Event> ctx) throws Exception { return value.getName().equals("end"); } }) .within(Duration.ofMillis(10)); NFA<Event> nfa = compile(pattern, true); NFAState nfaState = nfa.createInitialNFAState(); nfaState.resetStateChanged(); nfa.advanceTime(sharedBufferAccessor, nfaState, 6L, skipStrategy); nfa.process( sharedBufferAccessor, nfaState, new Event(6, "start", 1.0), 6L, skipStrategy, timerService); nfaState.resetStateChanged(); nfa.advanceTime(sharedBufferAccessor, nfaState, 17L, skipStrategy); assertTrue(nfaState.isStateChanged()); } }
NFAStatusChangeITCase
java
qos-ch__slf4j
slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java
{ "start": 1404, "end": 1455 }
enum ____ { STARTED, STOPPED; }
TimeInstrumentStatus
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/mapcompelem/Product.java
{ "start": 244, "end": 585 }
class ____ { private String name; private Map parts = new HashMap(); Product() {} public Product(String n) { name = n; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getParts() { return parts; } public void setParts(Map users) { this.parts = users; } }
Product
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/crypto/key/KeyProviderCryptoExtension.java
{ "start": 1442, "end": 1983 }
class ____ extends KeyProviderExtension<KeyProviderCryptoExtension.CryptoExtension> { /** * Designates an encrypted encryption key, or EEK. */ public static final String EEK = "EEK"; /** * Designates a decrypted encrypted encryption key, that is, an encryption key * (EK). */ public static final String EK = "EK"; /** * An encrypted encryption key (EEK) and related information. An EEK must be * decrypted using the key's encryption key before it can be used. */ public static
KeyProviderCryptoExtension
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/QueryableBuiltInRoles.java
{ "start": 1075, "end": 1414 }
interface ____ { /** * @return the built-in roles. */ QueryableBuiltInRoles getRoles(); /** * Adds a listener to be notified when the built-in roles change. * * @param listener the listener to add. */ void addListener(Listener listener); } }
Provider
java
apache__camel
components/camel-jdbc/src/main/java/org/apache/camel/component/jdbc/ConnectionStrategy.java
{ "start": 1008, "end": 1199 }
interface ____ { Connection getConnection(DataSource dataSource) throws Exception; boolean isConnectionTransactional(Connection connection, DataSource dataSource); }
ConnectionStrategy
java
netty__netty
common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java
{ "start": 8205, "end": 9836 }
class ____ { static final FallbackThreadSet EMPTY = new FallbackThreadSet(); private static final long EMPTY_VALUE = 0L; private final LongLongHashMap map; private FallbackThreadSet() { this.map = new LongLongHashMap(EMPTY_VALUE); } private FallbackThreadSet(LongLongHashMap map) { this.map = map; } public boolean contains(long threadId) { long key = threadId >>> 6; long bit = 1L << (threadId & 63); long bitmap = map.get(key); return (bitmap & bit) != 0; } public FallbackThreadSet add(long threadId) { long key = threadId >>> 6; long bit = 1L << (threadId & 63); LongLongHashMap newMap = new LongLongHashMap(map); long oldBitmap = newMap.get(key); long newBitmap = oldBitmap | bit; newMap.put(key, newBitmap); return new FallbackThreadSet(newMap); } public FallbackThreadSet remove(long threadId) { long key = threadId >>> 6; long bit = 1L << (threadId & 63); long oldBitmap = map.get(key); if ((oldBitmap & bit) == 0) { return this; } LongLongHashMap newMap = new LongLongHashMap(map); long newBitmap = oldBitmap & ~bit; if (newBitmap != EMPTY_VALUE) { newMap.put(key, newBitmap); } else { newMap.remove(key); } return new FallbackThreadSet(newMap); } } }
FallbackThreadSet
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BidirectionalOneToOneCascadeRemoveTest.java
{ "start": 828, "end": 1797 }
class ____ { @Test public void testWithFlush(SessionFactoryScope scope) { scope.inTransaction( session -> { final A a1 = new A( "1", "a1", 1 ); session.persist( a1 ); final B bRef = new B( "2", "b2", 2, a1 ); session.persist( bRef ); session.flush(); session.remove( bRef ); } ); scope.inTransaction( session -> { assertThat( session.find( A.class, "1" ) ).isNull(); assertThat( session.find( B.class, "2" ) ).isNull(); } ); } @Test public void testWithoutFlush(SessionFactoryScope scope) { scope.inTransaction( session -> { final A a1 = new A( "1", "a1", 1 ); session.persist( a1 ); final B bRef = new B( "2", "b2", 2, a1 ); session.persist( bRef ); session.remove( bRef ); } ); scope.inTransaction( session -> { assertThat( session.find( A.class, "1" ) ).isNull(); assertThat( session.find( B.class, "2" ) ).isNull(); } ); } @Entity( name = "EntityA" ) static
BidirectionalOneToOneCascadeRemoveTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/filter/JsonIncludeArrayTest.java
{ "start": 999, "end": 1180 }
class ____ { @JsonInclude(JsonInclude.Include.NON_EMPTY) public int[] value; public NonEmptyIntArray(int... v) { value = v; } } static
NonEmptyIntArray
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/ipc/TestRPCUtil.java
{ "start": 1705, "end": 5123 }
class ____<? extends Throwable> exception = FileNotFoundException.class; verifyRemoteExceptionUnwrapping(exception, exception.getName()); } @Test void testRemoteYarnExceptionUnwrapping() { Class<? extends Throwable> exception = YarnException.class; verifyRemoteExceptionUnwrapping(exception, exception.getName()); } @Test void testRemoteYarnExceptionDerivativeUnwrapping() { Class<? extends Throwable> exception = YarnTestException.class; verifyRemoteExceptionUnwrapping(exception, exception.getName()); } @Test void testRemoteRuntimeExceptionUnwrapping() { Class<? extends Throwable> exception = NullPointerException.class; verifyRemoteExceptionUnwrapping(exception, exception.getName()); } @Test void testUnexpectedRemoteExceptionUnwrapping() { // Non IOException, YarnException thrown by the remote side. Class<? extends Throwable> exception = Exception.class; verifyRemoteExceptionUnwrapping(RemoteException.class, exception.getName()); } @Test void testRemoteYarnExceptionWithoutStringConstructor() { // Derivatives of YarnException should always define a string constructor. Class<? extends Throwable> exception = YarnTestExceptionNoConstructor.class; verifyRemoteExceptionUnwrapping(RemoteException.class, exception.getName()); } @Test void testRPCServiceExceptionUnwrapping() { String message = "ServiceExceptionMessage"; ServiceException se = new ServiceException(message); Throwable t = null; try { RPCUtil.unwrapAndThrowException(se); } catch (Throwable thrown) { t = thrown; } assertTrue(IOException.class.isInstance(t)); assertTrue(t.getMessage().contains(message)); } @Test void testRPCIOExceptionUnwrapping() { String message = "DirectIOExceptionMessage"; IOException ioException = new FileNotFoundException(message); ServiceException se = new ServiceException(ioException); Throwable t = null; try { RPCUtil.unwrapAndThrowException(se); } catch (Throwable thrown) { t = thrown; } assertTrue(FileNotFoundException.class.isInstance(t)); assertTrue(t.getMessage().contains(message)); } @Test void testRPCRuntimeExceptionUnwrapping() { String message = "RPCRuntimeExceptionUnwrapping"; RuntimeException re = new NullPointerException(message); ServiceException se = new ServiceException(re); Throwable t = null; try { RPCUtil.unwrapAndThrowException(se); } catch (Throwable thrown) { t = thrown; } assertTrue(NullPointerException.class.isInstance(t)); assertTrue(t.getMessage().contains(message)); } private void verifyRemoteExceptionUnwrapping( Class<? extends Throwable> expectedLocalException, String realExceptionClassName) { String message = realExceptionClassName + "Message"; RemoteException re = new RemoteException(realExceptionClassName, message); ServiceException se = new ServiceException(re); Throwable t = null; try { RPCUtil.unwrapAndThrowException(se); } catch (Throwable thrown) { t = thrown; } assertTrue(expectedLocalException.isInstance(t), "Expected exception [" + expectedLocalException + "] but found " + t); assertTrue(t.getMessage().contains(message), "Expected message [" + message + "] but found " + t.getMessage()); } private static
Class
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/net/ssl/EnvironmentPasswordProvider.java
{ "start": 1051, "end": 1987 }
interface ____ obtain system environment variable values * requires us to use String objects. String objects are immutable and Java does not provide a way to erase this * sensitive data from the application memory. The password data will stay resident in memory until the String object * and its associated char[] array object are garbage collected and the memory is overwritten by another object. * </p><p> * This is slightly more secure than {@link MemoryPasswordProvider} because the actual password string does not * need to be passed to the application. * The actual password string is not pulled into memory until it is needed * (so the password string does not need to be passed in from the command line or in a configuration file). * This gives an attacker a smaller window of opportunity to obtain the password from a memory dump. * </p><p> * A more secure implementation is {@link FilePasswordProvider}. * </p> */
to
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/ServiceContext.java
{ "start": 1328, "end": 2190 }
class ____ { public Service service = null; public SliderFileSystem fs; public String serviceHdfsDir = ""; public ApplicationAttemptId attemptId; public LoadingCache<ConfigFile, Object> configCache; public ServiceScheduler scheduler; public ClientToAMTokenSecretManager secretManager; public ClientAMService clientAMService; // tokens used for container launch public ByteBuffer tokens; // AM keytab principal public String principal; // AM keytab location public String keytab; private ServiceManager serviceManager; public ServiceContext() { } public ServiceManager getServiceManager() { return serviceManager; } void setServiceManager(ServiceManager serviceManager) { this.serviceManager = Preconditions.checkNotNull(serviceManager); } public Service getService() { return service; } }
ServiceContext
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/AdviceWithWeaveByToUriEnrichTest.java
{ "start": 1117, "end": 3095 }
class ____ extends ContextTestSupport { @Test public void testAdviceEnrichToString() throws Exception { RouteDefinition route = context.getRouteDefinitions().get(0); AdviceWith.adviceWith(route, context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveByToString("enrich*").replace().to("mock:foo"); mockEndpointsAndSkip("direct:foo*"); } }); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:bar").expectedMessageCount(0); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testAdviceEnrichToUri() throws Exception { RouteDefinition route = context.getRouteDefinitions().get(0); AdviceWith.adviceWith(route, context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveByToUri("direct:bar").replace().to("mock:foo"); mockEndpointsAndSkip("direct:foo*"); } }); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:bar").expectedMessageCount(0); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .enrich("direct:bar").to("mock:result"); from("direct:bar").to("mock:bar").setBody().constant("Hello Bar"); } }; } }
AdviceWithWeaveByToUriEnrichTest
java
apache__camel
test-infra/camel-test-infra-hashicorp-vault/src/test/java/org/apache/camel/test/infra/hashicorp/vault/services/HashicorpServiceFactory.java
{ "start": 957, "end": 1397 }
class ____ { private HashicorpServiceFactory() { } public static SimpleTestServiceBuilder<HashicorpVaultService> builder() { return new SimpleTestServiceBuilder<>("hashicorp-vault"); } public static HashicorpVaultService createService() { return builder() .addLocalMapping(HashicorpVaultLocalContainerService::new) .build(); } public static
HashicorpServiceFactory
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/counters/AbstractCounters.java
{ "start": 2291, "end": 2559 }
class ____<C extends Counter, G extends CounterGroupBase<C>> implements Writable, Iterable<G> { protected static final Logger LOG = LoggerFactory.getLogger("mapreduce.Counters"); /** * A cache from
AbstractCounters
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/MapKeyJavaTypeAnnotation.java
{ "start": 472, "end": 1627 }
class ____ implements MapKeyJavaType { private java.lang.Class<? extends org.hibernate.type.descriptor.java.BasicJavaType<?>> value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public MapKeyJavaTypeAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public MapKeyJavaTypeAnnotation(MapKeyJavaType annotation, ModelsContext modelContext) { this.value = annotation.value(); } /** * Used in creating annotation instances from Jandex variant */ public MapKeyJavaTypeAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (Class<? extends org.hibernate.type.descriptor.java.BasicJavaType<?>>) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return MapKeyJavaType.class; } @Override public java.lang.Class<? extends org.hibernate.type.descriptor.java.BasicJavaType<?>> value() { return value; } public void value(java.lang.Class<? extends org.hibernate.type.descriptor.java.BasicJavaType<?>> value) { this.value = value; } }
MapKeyJavaTypeAnnotation
java
qos-ch__slf4j
slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java
{ "start": 1343, "end": 1846 }
class ____ essentially a wrapper around an {@link LoggerFactory} producing * {@link LocLogger} instances. * * <p> * Contrary to {@link LoggerFactory#getLogger(String)} method of * {@link LoggerFactory}, each call to {@link #getLocLogger(String)} produces a new * instance of {@link LocLogger}. This should not matter because a LocLogger * instance does have any state beyond that of the {@link Logger} instance it * wraps and its message conveyor. * * @author Ceki G&uuml;lc&uuml; * */ public
is
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/FileTokensTool.java
{ "start": 1481, "end": 2174 }
class ____ extends MultiCommand { FileTokensTool() { super("Manages elasticsearch service account file-tokens"); subcommands.put("create", newCreateFileTokenCommand()); subcommands.put("delete", newDeleteFileTokenCommand()); subcommands.put("list", newListFileTokenCommand()); } protected CreateFileTokenCommand newCreateFileTokenCommand() { return new CreateFileTokenCommand(); } protected DeleteFileTokenCommand newDeleteFileTokenCommand() { return new DeleteFileTokenCommand(); } protected ListFileTokenCommand newListFileTokenCommand() { return new ListFileTokenCommand(); } static
FileTokensTool
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/blockhash/BytesRef2BlockHash.java
{ "start": 3486, "end": 7293 }
class ____ extends AddPage { final IntBlock b1; final IntBlock b2; AddWork(IntBlock b1, IntBlock b2, GroupingAggregatorFunction.AddInput addInput) { super(blockFactory, emitBatchSize, addInput); this.b1 = b1; this.b2 = b2; } void add() { int positionCount = b1.getPositionCount(); for (int i = 0; i < positionCount; i++) { int v1 = b1.getValueCount(i); int v2 = b2.getValueCount(i); int first1 = b1.getFirstValueIndex(i); int first2 = b2.getFirstValueIndex(i); if (v1 == 1 && v2 == 1) { long ord = ord(b1.getInt(first1), b2.getInt(first2)); appendOrdSv(i, Math.toIntExact(ord)); continue; } for (int i1 = 0; i1 < v1; i1++) { int k1 = b1.getInt(first1 + i1); for (int i2 = 0; i2 < v2; i2++) { int k2 = b2.getInt(first2 + i2); long ord = ord(k1, k2); appendOrdInMv(i, Math.toIntExact(ord)); } } finishMv(); } flushRemaining(); } } private long ord(int k1, int k2) { return hashOrdToGroup(finalHash.add((long) k2 << 32 | k1)); } @Override public ReleasableIterator<IntBlock> lookup(Page page, ByteSizeValue targetBlockSize) { throw new UnsupportedOperationException("TODO"); } @Override public Block[] getKeys() { // TODO Build Ordinals blocks #114010 final int positions = (int) finalHash.size(); final BytesRef scratch = new BytesRef(); final BytesRefBlock[] outputBlocks = new BytesRefBlock[2]; try { try (BytesRefBlock.Builder b1 = blockFactory.newBytesRefBlockBuilder(positions)) { for (int i = 0; i < positions; i++) { int k1 = (int) (finalHash.get(i) & 0xffffffffL); // k1 is always positive, it's how hash values are generated, see BytesRefBlockHash. // For now, we only manage at most 2^31 hash entries if (k1 == 0) { b1.appendNull(); } else { b1.appendBytesRef(hash1.hash.get(k1 - 1, scratch)); } } outputBlocks[0] = b1.build(); } try (BytesRefBlock.Builder b2 = blockFactory.newBytesRefBlockBuilder(positions)) { for (int i = 0; i < positions; i++) { int k2 = (int) (finalHash.get(i) >>> 32); if (k2 == 0) { b2.appendNull(); } else { b2.appendBytesRef(hash2.hash.get(k2 - 1, scratch)); } } outputBlocks[1] = b2.build(); } return outputBlocks; } finally { if (outputBlocks[outputBlocks.length - 1] == null) { Releasables.close(outputBlocks); } } } @Override public BitArray seenGroupIds(BigArrays bigArrays) { return new Range(0, Math.toIntExact(finalHash.size())).seenGroupIds(bigArrays); } @Override public IntVector nonEmpty() { return IntVector.range(0, Math.toIntExact(finalHash.size()), blockFactory); } @Override public String toString() { return String.format( Locale.ROOT, "BytesRef2BlockHash{keys=[channel1=%d, channel2=%d], entries=%d}", channel1, channel2, finalHash.size() ); } }
AddWork
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuildpackReference.java
{ "start": 1086, "end": 2517 }
class ____ { private final String value; private BuildpackReference(String value) { this.value = value; } boolean hasPrefix(String prefix) { return this.value.startsWith(prefix); } @Nullable String getSubReference(String prefix) { return this.value.startsWith(prefix) ? this.value.substring(prefix.length()) : null; } @Nullable Path asPath() { try { URL url = new URL(this.value); if (url.getProtocol().equals("file")) { return Paths.get(url.toURI()); } return null; } catch (MalformedURLException | URISyntaxException ex) { // not a URL, fall through to attempting to find a plain file path } try { return Paths.get(this.value); } catch (Exception ex) { return null; } } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.value.equals(((BuildpackReference) obj).value); } @Override public int hashCode() { return this.value.hashCode(); } @Override public String toString() { return this.value; } /** * Create a new {@link BuildpackReference} from the given value. * @param value the value to use * @return a new {@link BuildpackReference} */ public static BuildpackReference of(String value) { Assert.hasText(value, "'value' must not be empty"); return new BuildpackReference(value); } }
BuildpackReference
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest.java
{ "start": 1076, "end": 6106 }
class ____ extends TestCase { public void test_alter_0() throws Exception { String sql = "ALTER TABLE `test`.`tb1` CHANGE COLUMN `fname` `fname1` VARCHAR(45) NULL DEFAULT NULL ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`\n\tCHANGE COLUMN `fname` `fname1` VARCHAR(45) NULL DEFAULT NULL;", output); } public void test_alter_1() throws Exception { String sql = "ALTER TABLE `test`.`tb1` CHARACTER SET = utf8 , COLLATE = utf8_general_ci ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); assertEquals("ALTER TABLE `test`.`tb1`\n\tCHARACTER SET = utf8 COLLATE = utf8_general_ci;", SQLUtils.toMySqlString(stmt)); assertEquals("alter table `test`.`tb1`\n\tcharacter set = utf8 collate = utf8_general_ci;", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } public void test_alter_2() throws Exception { String sql = "ALTER TABLE `test`.`tb1` ADD INDEX `f` (`fname` ASC) ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`\n\tADD INDEX `f` (`fname` ASC);", output); } public void test_alter_3() throws Exception { String sql = "ALTER TABLE `test`.`tb1` ENGINE = InnoDB ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`\n\tENGINE = InnoDB;", output); } public void test_alter_4() throws Exception { String sql = "ALTER TABLE `test`.`tb1` COLLATE = utf8_general_ci , PACK_KEYS = Pack All , ENGINE = InnoDB ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`\n\tCOLLATE = utf8_general_ci PACK_KEYS = PACK ALL ENGINE = InnoDB;", output); } public void test_alter_5() throws Exception { String sql = "ALTER TABLE t1 COMMENT '表的注释';"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE t1\n\tCOMMENT = '表的注释';", output); } public void test_alter_6() throws Exception { String sql = "ALTER TABLE `test`.`tb1` DEFAULT CHARACTER SET utf8 COLLATE = utf8_general_ci ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); System.out.println(stmt.toString()); //System.out.println(SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); assertEquals("ALTER TABLE `test`.`tb1`\n\tCHARACTER SET = utf8 COLLATE = utf8_general_ci;", SQLUtils.toMySqlString(stmt)); assertEquals("alter table `test`.`tb1`\n\tcharacter set = utf8 collate = utf8_general_ci;", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); } public void test_alter_7() throws Exception { for (String sql : new String[]{ "ALTER TABLE \n" + " `test` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;", "ALTER TABLE \n" + " `test` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_bin';", "ALTER TABLE \n" + " `test` CHARACTER SET \"utf8mb4\" COLLATE \"utf8mb4_bin\";", "ALTER TABLE \n" + " `test` default CHARACTER SET utf8mb4 COLLATE =utf8mb4_bin", }) { System.out.println("原始的sql===" + sql); SQLStatementParser parser1 = SQLParserUtils.createSQLStatementParser(sql, DbType.mysql); List<SQLStatement> statementList1 = parser1.parseStatementList(); String sqleNew = statementList1.get(0).toString(); System.out.println("生成的sql===" + sqleNew); SQLStatementParser parser2 = SQLParserUtils.createSQLStatementParser(sqleNew, DbType.mariadb); List<SQLStatement> statementList2 = parser2.parseStatementList(); String sqleNew2 = statementList2.get(0).toString(); System.out.println("再次解析生成的sql===" + sqleNew2); assertEquals(sqleNew, sqleNew2); } } }
MySqlAlterTableTest
java
spring-projects__spring-boot
module/spring-boot-webclient-test/src/test/java/org/springframework/boot/webclient/test/autoconfigure/WebClientTestIntegrationTests.java
{ "start": 1210, "end": 2022 }
class ____ { @Autowired private MockWebServer server; @Autowired private ExampleWebClientService client; @Test void mockServerCall1() throws InterruptedException { this.server.enqueue(new MockResponse().setBody("1")); assertThat(this.client.test()).isEqualTo("1"); this.server.takeRequest(); } @Test void mockServerCall2() throws InterruptedException { this.server.enqueue(new MockResponse().setBody("2")); assertThat(this.client.test()).isEqualTo("2"); this.server.takeRequest(); } @Test void mockServerCallWithContent() throws InterruptedException { this.server.enqueue(new MockResponse().setBody("1")); this.client.testPostWithBody("test"); assertThat(this.server.takeRequest().getBody().readString(StandardCharsets.UTF_8)).isEqualTo("test"); } }
WebClientTestIntegrationTests
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IbmCosComponentBuilderFactory.java
{ "start": 14716, "end": 19027 }
class ____ use when storing objects (e.g., STANDARD, VAULT, * COLD, FLEX). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param storageClass the value to set * @return the dsl builder */ default IbmCosComponentBuilder storageClass(java.lang.String storageClass) { doSetProperty("storageClass", storageClass); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default IbmCosComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Reference to an IBM COS Client instance in the registry. * * The option is a: * &lt;code&gt;com.ibm.cloud.objectstorage.services.s3.AmazonS3&lt;/code&gt; type. * * Group: advanced * * @param cosClient the value to set * @return the dsl builder */ default IbmCosComponentBuilder cosClient(com.ibm.cloud.objectstorage.services.s3.AmazonS3 cosClient) { doSetProperty("cosClient", cosClient); return this; } /** * Used for enabling or disabling all consumer based health checks from * this component. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckConsumerEnabled the value to set * @return the dsl builder */ default IbmCosComponentBuilder healthCheckConsumerEnabled(boolean healthCheckConsumerEnabled) { doSetProperty("healthCheckConsumerEnabled", healthCheckConsumerEnabled); return this; } /** * Used for enabling or disabling all producer based health checks from * this component. Notice: Camel has by default disabled all producer * based health-checks. You can turn on producer checks globally by * setting camel.health.producersEnabled=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckProducerEnabled the value to set * @return the dsl builder */ default IbmCosComponentBuilder healthCheckProducerEnabled(boolean healthCheckProducerEnabled) { doSetProperty("healthCheckProducerEnabled", healthCheckProducerEnabled); return this; } /** * IBM Cloud API Key for authentication. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param apiKey the value to set * @return the dsl builder */ default IbmCosComponentBuilder apiKey(java.lang.String apiKey) { doSetProperty("apiKey", apiKey); return this; } /** * IBM COS Service Instance ID (CRN). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param serviceInstanceId the value to set * @return the dsl builder */ default IbmCosComponentBuilder serviceInstanceId(java.lang.String serviceInstanceId) { doSetProperty("serviceInstanceId", serviceInstanceId); return this; } }
to
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/MutationCoordinator.java
{ "start": 405, "end": 616 }
interface ____ { /** * The operation group used to perform the mutation unless some form * of dynamic mutation is necessary. */ MutationOperationGroup getStaticMutationOperationGroup(); }
MutationCoordinator
java
processing__processing4
app/src/processing/app/ui/MarkerColumn.java
{ "start": 5887, "end": 6114 }
class ____ { /** y co-ordinate of the marker */ int y; /** Problem that the error marker represents */ final Problem problem; LineMarker(Problem problem) { this.problem = problem; } } }
LineMarker
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/spr10546/Spr10546Tests.java
{ "start": 4076, "end": 4645 }
class ____ extends ParentWithImportConfig {} } @Test void childConfigFirst() { assertLoadsMyBean(AEnclosingConfig.ChildConfig.class, AEnclosingConfig.class); } @Test void enclosingConfigOnly() { assertLoadsMyBean(AEnclosingConfig.class); } @Test void childConfigOnly() { assertLoadsMyBean(AEnclosingConfig.ChildConfig.class); } private void assertLoadsMyBean(Class<?>... annotatedClasses) { context = new AnnotationConfigApplicationContext(annotatedClasses); assertThat(context.getBean("myBean",String.class)).isEqualTo("myBean"); } }
ChildConfig
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/InternalGeoHexGridBucket.java
{ "start": 687, "end": 1322 }
class ____ extends InternalGeoGridBucket { InternalGeoHexGridBucket(long hashAsLong, long docCount, InternalAggregations aggregations) { super(hashAsLong, docCount, aggregations); } /** * Read from a stream. */ public InternalGeoHexGridBucket(StreamInput in) throws IOException { super(in); } @Override public String getKeyAsString() { return H3.h3ToString(hashAsLong); } @Override public GeoPoint getKey() { LatLng latLng = H3.h3ToLatLng(hashAsLong); return new GeoPoint(latLng.getLatDeg(), latLng.getLonDeg()); } }
InternalGeoHexGridBucket
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/utils/YamlParserUtil.java
{ "start": 3388, "end": 5760 }
class ____ extends AbstractConstruct { @Override public Object construct(Node node) { if (!YamlParserConstructor.configMetadataTag.getValue().equals(node.getTag().getValue())) { throw new NacosRuntimeException(NacosException.INVALID_PARAM, "could not determine a constructor for the tag " + node.getTag() + node.getStartMark()); } MappingNode mNode = (MappingNode) node; List<NodeTuple> value = mNode.getValue(); if (CollectionUtils.isEmpty(value)) { return null; } NodeTuple nodeTuple = value.get(0); ConfigMetadata configMetadata = new ConfigMetadata(); SequenceNode sequenceNode = (SequenceNode) nodeTuple.getValueNode(); if (CollectionUtils.isEmpty(sequenceNode.getValue())) { return configMetadata; } List<ConfigMetadata.ConfigExportItem> exportItems = sequenceNode.getValue().stream().map(itemValue -> { ConfigMetadata.ConfigExportItem configExportItem = new ConfigMetadata.ConfigExportItem(); MappingNode itemMap = (MappingNode) itemValue; List<NodeTuple> propertyValues = itemMap.getValue(); Map<String, String> metadataMap = new HashMap<>(propertyValues.size()); propertyValues.forEach(metadata -> { ScalarNode keyNode = (ScalarNode) metadata.getKeyNode(); ScalarNode valueNode = (ScalarNode) metadata.getValueNode(); metadataMap.put(keyNode.getValue(), valueNode.getValue()); }); configExportItem.setDataId(metadataMap.get("dataId")); configExportItem.setGroup(metadataMap.get("group")); configExportItem.setType(metadataMap.get("type")); configExportItem.setDesc(metadataMap.get("desc")); configExportItem.setAppName(metadataMap.get("appName")); configExportItem.setConfigTags(metadataMap.get("configTags")); return configExportItem; }).collect(Collectors.toList()); configMetadata.setMetadata(exportItems); return configMetadata; } } }
ConstructYamlConfigMetadata
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessarilyVisibleTest.java
{ "start": 940, "end": 1435 }
class ____ { private final BugCheckerRefactoringTestHelper helper = BugCheckerRefactoringTestHelper.newInstance(UnnecessarilyVisible.class, getClass()); private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(UnnecessarilyVisible.class, getClass()); @Test public void publicConstructor() { helper .addInputLines( "Test.java", """ import javax.inject.Inject;
UnnecessarilyVisibleTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es816/BinaryQuantizer.java
{ "start": 1650, "end": 15933 }
class ____ { public static final byte B_QUERY = 4; private final int discretizedDimensions; private final VectorSimilarityFunction similarityFunction; private final float sqrtDimensions; public BinaryQuantizer(int dimensions, int discretizedDimensions, VectorSimilarityFunction similarityFunction) { if (dimensions <= 0) { throw new IllegalArgumentException("dimensions must be > 0 but was: " + dimensions); } assert discretizedDimensions % 64 == 0 : "discretizedDimensions must be a multiple of 64 but was: " + discretizedDimensions; this.discretizedDimensions = discretizedDimensions; this.similarityFunction = similarityFunction; this.sqrtDimensions = (float) Math.sqrt(dimensions); } BinaryQuantizer(int dimensions, VectorSimilarityFunction similarityFunction) { this(dimensions, dimensions, similarityFunction); } private static void removeSignAndDivide(float[] a, float divisor) { for (int i = 0; i < a.length; i++) { a[i] = Math.abs(a[i]) / divisor; } } private static float sumAndNormalize(float[] a, float norm) { float aDivided = 0f; for (int i = 0; i < a.length; i++) { aDivided += a[i]; } aDivided = aDivided / norm; if (Float.isFinite(aDivided) == false) { aDivided = 0.8f; // can be anything } return aDivided; } private static void packAsBinary(float[] vector, byte[] packedVector) { for (int h = 0; h < vector.length; h += 8) { byte result = 0; int q = 0; for (int i = 7; i >= 0; i--) { if (vector[h + i] > 0) { result |= (byte) (1 << q); } q++; } packedVector[h / 8] = result; } } public VectorSimilarityFunction getSimilarity() { return this.similarityFunction; } private record SubspaceOutput(float projection) {} private SubspaceOutput generateSubSpace(float[] vector, float[] centroid, byte[] quantizedVector) { // typically no-op if dimensions/64 float[] paddedCentroid = BQVectorUtils.pad(centroid, discretizedDimensions); float[] paddedVector = BQVectorUtils.pad(vector, discretizedDimensions); BQVectorUtils.subtractInPlace(paddedVector, paddedCentroid); // The inner product between the data vector and the quantized data vector float norm = BQVectorUtils.norm(paddedVector); packAsBinary(paddedVector, quantizedVector); removeSignAndDivide(paddedVector, sqrtDimensions); float projection = sumAndNormalize(paddedVector, norm); return new SubspaceOutput(projection); } record SubspaceOutputMIP(float OOQ, float normOC, float oDotC) {} private SubspaceOutputMIP generateSubSpaceMIP(float[] vector, float[] centroid, byte[] quantizedVector) { // typically no-op if dimensions/64 float[] paddedCentroid = BQVectorUtils.pad(centroid, discretizedDimensions); float[] paddedVector = BQVectorUtils.pad(vector, discretizedDimensions); float oDotC = VectorUtil.dotProduct(paddedVector, paddedCentroid); BQVectorUtils.subtractInPlace(paddedVector, paddedCentroid); float normOC = BQVectorUtils.norm(paddedVector); packAsBinary(paddedVector, quantizedVector); BQVectorUtils.divideInPlace(paddedVector, normOC); // OmC / norm(OmC) float OOQ = computerOOQ(vector.length, paddedVector, quantizedVector); return new SubspaceOutputMIP(OOQ, normOC, oDotC); } private float computerOOQ(int originalLength, float[] normOMinusC, byte[] packedBinaryVector) { float OOQ = 0f; for (int j = 0; j < originalLength / 8; j++) { for (int r = 0; r < 8; r++) { int sign = ((packedBinaryVector[j] >> (7 - r)) & 0b00000001); OOQ += (normOMinusC[j * 8 + r] * (2 * sign - 1)); } } OOQ = OOQ / sqrtDimensions; return OOQ; } private static float[] range(float[] q) { float vl = 1e20f; float vr = -1e20f; for (int i = 0; i < q.length; i++) { if (q[i] < vl) { vl = q[i]; } if (q[i] > vr) { vr = q[i]; } } return new float[] { vl, vr }; } /** Results of quantizing a vector for both querying and indexing */ public record QueryAndIndexResults(float[] indexFeatures, QueryFactors queryFeatures) {} public QueryAndIndexResults quantizeQueryAndIndex(float[] vector, byte[] indexDestination, byte[] queryDestination, float[] centroid) { assert similarityFunction != COSINE || isUnitVector(vector); assert similarityFunction != COSINE || isUnitVector(centroid); assert this.discretizedDimensions == BQVectorUtils.discretize(vector.length, 64); if (this.discretizedDimensions != indexDestination.length * 8) { throw new IllegalArgumentException( "vector and quantized vector destination must be compatible dimensions: " + BQVectorUtils.discretize(vector.length, 64) + " [ " + this.discretizedDimensions + " ]" + "!= " + indexDestination.length + " * 8" ); } if (this.discretizedDimensions != (queryDestination.length * 8) / B_QUERY) { throw new IllegalArgumentException( "vector and quantized vector destination must be compatible dimensions: " + vector.length + " [ " + this.discretizedDimensions + " ]" + "!= (" + queryDestination.length + " * 8) / " + B_QUERY ); } if (vector.length != centroid.length) { throw new IllegalArgumentException( "vector and centroid dimensions must be the same: " + vector.length + "!= " + centroid.length ); } vector = ArrayUtil.copyArray(vector); float distToC = VectorUtil.squareDistance(vector, centroid); // only need vdotc for dot-products similarity, but not for euclidean float vDotC = similarityFunction != EUCLIDEAN ? VectorUtil.dotProduct(vector, centroid) : 0f; BQVectorUtils.subtractInPlace(vector, centroid); // both euclidean and dot-product need the norm of the vector, just at different times float normVmC = BQVectorUtils.norm(vector); // quantize for index packAsBinary(BQVectorUtils.pad(vector, discretizedDimensions), indexDestination); if (similarityFunction != EUCLIDEAN) { BQVectorUtils.divideInPlace(vector, normVmC); } // Quantize for query float[] range = range(vector); float lower = range[0]; float upper = range[1]; // Δ := (𝑣𝑟 − 𝑣𝑙)/(2𝐵𝑞 − 1) float width = (upper - lower) / ((1 << B_QUERY) - 1); QuantResult quantResult = quantize(vector, lower, width); int[] byteQuery = quantResult.result(); // q¯ = Δ · q¯𝑢 + 𝑣𝑙 · 1𝐷 // q¯ is an approximation of q′ (scalar quantized approximation) ESVectorUtil.transposeHalfByte(byteQuery, queryDestination); QueryFactors factors = new QueryFactors(quantResult.quantizedSum, distToC, lower, width, normVmC, vDotC); final float[] indexCorrections; if (similarityFunction == EUCLIDEAN) { indexCorrections = new float[2]; indexCorrections[0] = (float) Math.sqrt(distToC); removeSignAndDivide(vector, sqrtDimensions); indexCorrections[1] = sumAndNormalize(vector, normVmC); } else { indexCorrections = new float[3]; indexCorrections[0] = computerOOQ(vector.length, vector, indexDestination); indexCorrections[1] = normVmC; indexCorrections[2] = vDotC; } return new QueryAndIndexResults(indexCorrections, factors); } public float[] quantizeForIndex(float[] vector, byte[] destination, float[] centroid) { assert similarityFunction != COSINE || isUnitVector(vector); assert similarityFunction != COSINE || isUnitVector(centroid); assert this.discretizedDimensions == BQVectorUtils.discretize(vector.length, 64); if (this.discretizedDimensions != destination.length * 8) { throw new IllegalArgumentException( "vector and quantized vector destination must be compatible dimensions: " + BQVectorUtils.discretize(vector.length, 64) + " [ " + this.discretizedDimensions + " ]" + "!= " + destination.length + " * 8" ); } if (vector.length != centroid.length) { throw new IllegalArgumentException( "vector and centroid dimensions must be the same: " + vector.length + "!= " + centroid.length ); } float[] corrections; // FIXME: make a copy of vector so we don't overwrite it here? // ... (could trade subtractInPlace w subtract in genSubSpace) vector = ArrayUtil.copyArray(vector); switch (similarityFunction) { case EUCLIDEAN: float distToCentroid = (float) Math.sqrt(VectorUtil.squareDistance(vector, centroid)); SubspaceOutput subspaceOutput = generateSubSpace(vector, centroid, destination); corrections = new float[2]; // FIXME: quantize these values so we are passing back 1 byte values for all three of these corrections[0] = distToCentroid; corrections[1] = subspaceOutput.projection(); break; case MAXIMUM_INNER_PRODUCT: case COSINE: case DOT_PRODUCT: SubspaceOutputMIP subspaceOutputMIP = generateSubSpaceMIP(vector, centroid, destination); corrections = new float[3]; // FIXME: quantize these values so we are passing back 1 byte values for all three of these corrections[0] = subspaceOutputMIP.OOQ(); corrections[1] = subspaceOutputMIP.normOC(); corrections[2] = subspaceOutputMIP.oDotC(); break; default: throw new UnsupportedOperationException("Unsupported similarity function: " + similarityFunction); } return corrections; } private record QuantResult(int[] result, int quantizedSum) {} private static QuantResult quantize(float[] vector, float lower, float width) { // FIXME: speed up with panama? and/or use existing scalar quantization utils in Lucene? int[] result = new int[vector.length]; float oneOverWidth = 1.0f / width; int sumQ = 0; for (int i = 0; i < vector.length; i++) { byte res = (byte) ((vector[i] - lower) * oneOverWidth); result[i] = res; sumQ += res; } return new QuantResult(result, sumQ); } /** Factors for quantizing query */ public record QueryFactors(int quantizedSum, float distToC, float lower, float width, float normVmC, float vDotC) {} public QueryFactors quantizeForQuery(float[] vector, byte[] destination, float[] centroid) { assert similarityFunction != COSINE || isUnitVector(vector); assert similarityFunction != COSINE || isUnitVector(centroid); assert this.discretizedDimensions == BQVectorUtils.discretize(vector.length, 64); if (this.discretizedDimensions != (destination.length * 8) / B_QUERY) { throw new IllegalArgumentException( "vector and quantized vector destination must be compatible dimensions: " + vector.length + " [ " + this.discretizedDimensions + " ]" + "!= (" + destination.length + " * 8) / " + B_QUERY ); } if (vector.length != centroid.length) { throw new IllegalArgumentException( "vector and centroid dimensions must be the same: " + vector.length + "!= " + centroid.length ); } float distToC = VectorUtil.squareDistance(vector, centroid); // FIXME: make a copy of vector so we don't overwrite it here? // ... (could subtractInPlace but the passed vector is modified) <<--- float[] vmC = BQVectorUtils.subtract(vector, centroid); // FIXME: should other similarity functions behave like MIP on query like COSINE float normVmC = 0f; if (similarityFunction != EUCLIDEAN) { normVmC = BQVectorUtils.norm(vmC); BQVectorUtils.divideInPlace(vmC, normVmC); } float[] range = range(vmC); float lower = range[0]; float upper = range[1]; // Δ := (𝑣𝑟 − 𝑣𝑙)/(2𝐵𝑞 − 1) float width = (upper - lower) / ((1 << B_QUERY) - 1); QuantResult quantResult = quantize(vmC, lower, width); int[] byteQuery = quantResult.result(); // q¯ = Δ · q¯𝑢 + 𝑣𝑙 · 1𝐷 // q¯ is an approximation of q′ (scalar quantized approximation) ESVectorUtil.transposeHalfByte(byteQuery, destination); QueryFactors factors; if (similarityFunction != EUCLIDEAN) { float vDotC = VectorUtil.dotProduct(vector, centroid); // FIXME: quantize the corrections as well so we store less factors = new QueryFactors(quantResult.quantizedSum, distToC, lower, width, normVmC, vDotC); } else { // FIXME: quantize the corrections as well so we store less factors = new QueryFactors(quantResult.quantizedSum, distToC, lower, width, 0f, 0f); } return factors; } }
BinaryQuantizer
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/HANAUnnestFunction.java
{ "start": 15265, "end": 18928 }
class ____ implements SelfRenderingExpression { private final List<ColumnInfo> idColumns; private final String tableQualifier; private final Expression argument; public XmlWrapperExpression(List<ColumnInfo> idColumns, String tableQualifier, Expression argument) { this.idColumns = idColumns; this.tableQualifier = tableQualifier; this.argument = argument; } @Override public void renderToSql( SqlAppender sqlAppender, SqlAstTranslator<?> walker, SessionFactoryImplementor sessionFactory) { final BasicPluralType<?, ?> pluralType = (BasicPluralType<?, ?>) argument.getExpressionType().getSingleJdbcMapping(); final XmlHelper.CollectionTags collectionTags = XmlHelper.determineCollectionTags( (BasicPluralJavaType<?>) pluralType.getJavaTypeDescriptor(), sessionFactory ); // Produce an XML string e.g. <root id="1">...</root> // which will contain the original XML as well as id column information for correlation sqlAppender.appendSql( "trim('/>' from (select" ); char separator = ' '; for ( ColumnInfo columnInfo : idColumns ) { sqlAppender.appendSql( separator ); sqlAppender.appendSql( tableQualifier ); sqlAppender.appendSql( '.' ); sqlAppender.appendSql( columnInfo.name() ); sqlAppender.appendSql( ' ' ); sqlAppender.appendDoubleQuoteEscapedString( columnInfo.name() ); separator = ','; } sqlAppender.appendSql( " from sys.dummy for xml('root'='no','columnstyle'='attribute','rowname'='" ); sqlAppender.appendSql( collectionTags.rootName() ); sqlAppender.appendSql( "','format'='no')))||substring(" ); argument.accept( walker ); sqlAppender.appendSql( ",locate('<" ); sqlAppender.appendSql( collectionTags.rootName() ); sqlAppender.appendSql( ">'," ); argument.accept( walker ); sqlAppender.appendSql( ")+" ); sqlAppender.appendSql( collectionTags.rootName().length() + 2 ); sqlAppender.appendSql( ",length(" ); argument.accept( walker ); sqlAppender.appendSql( "))" ); } @Override public JdbcMappingContainer getExpressionType() { return argument.getExpressionType(); } } @Override protected String getDdlType(SqlTypedMapping sqlTypedMapping, int containerSqlTypeCode, SqlAstTranslator<?> translator) { final String ddlType = super.getDdlType( sqlTypedMapping, containerSqlTypeCode, translator ); if ( containerSqlTypeCode == SqlTypes.JSON_ARRAY ) { return HANAJsonValueFunction.jsonValueReturningType( ddlType ); } return ddlType; } @Override protected void renderJsonTable( SqlAppender sqlAppender, Expression array, BasicPluralType<?, ?> pluralType, @Nullable SqlTypedMapping sqlTypedMapping, AnonymousTupleTableGroupProducer tupleType, String tableIdentifierVariable, SqlAstTranslator<?> walker) { sqlAppender.appendSql( "json_table(" ); array.accept( walker ); if ( array instanceof TableColumnReferenceExpression expression ) { sqlAppender.appendSql( ",'$' columns(" ); for ( ColumnInfo columnInfo : expression.getIdColumns() ) { sqlAppender.appendSql( columnInfo.name() ); sqlAppender.appendSql( ' ' ); sqlAppender.appendSql( columnInfo.ddlType() ); sqlAppender.appendSql( " path '$." ); sqlAppender.appendSql( columnInfo.name() ); sqlAppender.appendSql( "'," ); } sqlAppender.appendSql( "nested path '$.v' columns" ); renderJsonTableColumns( sqlAppender, tupleType, walker, true ); sqlAppender.appendSql( "))" ); } else { sqlAppender.appendSql( ",'$[*]' columns" ); renderJsonTableColumns( sqlAppender, tupleType, walker, true ); sqlAppender.appendSql( ")" ); } } static
XmlWrapperExpression
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
{ "start": 109491, "end": 110921 }
class ____ extends MyAdaptedControllerBase<String> { @RequestMapping public void myHandle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().write("test"); } @Override public void myHandle(@RequestParam("param1") String p1, int param2, @RequestHeader Integer header1, @CookieValue int cookie1, HttpServletResponse response) throws IOException { response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1); } @RequestMapping("/myPath3") public void myHandle(TestBean tb, HttpServletResponse response) throws IOException { response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); } @RequestMapping("/myPath4.*") public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) throws IOException { response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); } @Override @InitBinder public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { assertThat(px).isNull(); } @Override @ModelAttribute public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { assertThat(px).isNull(); } } @Controller @RequestMapping(method = RequestMethod.GET) static
MyAdaptedController3
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/singlepersistenceunit/entityassignment/packageincludedthroughannotation/EntityIncludedThroughPackageAnnotation.java
{ "start": 275, "end": 621 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "includedSeq") public long id; public String name; public EntityIncludedThroughPackageAnnotation() { } public EntityIncludedThroughPackageAnnotation(String name) { this.name = name; } }
EntityIncludedThroughPackageAnnotation
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/lucene/LuceneMaxDoubleOperatorTests.java
{ "start": 1116, "end": 3381 }
class ____ extends LuceneMaxOperatorTestCase { @Override public LuceneMaxFactory.NumberType getNumberType() { return LuceneMaxFactory.NumberType.DOUBLE; } @Override protected NumberTypeTest getNumberTypeTest() { return new NumberTypeTest() { double max = -Double.MAX_VALUE; @Override public IndexableField newPointField() { return new DoubleField(FIELD_NAME, newValue(), randomFrom(Field.Store.values())); } @Override public IndexableField newDocValuesField() { return new SortedNumericDocValuesField(FIELD_NAME, NumericUtils.doubleToSortableLong(newValue())); } private double newValue() { final double value = randomDoubleBetween(-Double.MAX_VALUE, Double.MAX_VALUE, true); max = Math.max(max, value); return value; } @Override public void assertPage(Page page) { assertThat(page.getBlock(0), instanceOf(DoubleBlock.class)); final DoubleBlock db = page.getBlock(0); assertThat(page.getBlock(1), instanceOf(BooleanBlock.class)); final BooleanBlock bb = page.getBlock(1); if (bb.getBoolean(0) == false) { assertThat(db.getDouble(0), equalTo(-Double.MAX_VALUE)); } else { assertThat(db.getDouble(0), lessThanOrEqualTo(max)); } } @Override public AggregatorFunction newAggregatorFunction(DriverContext context) { return new MaxDoubleAggregatorFunctionSupplier().aggregator(context, List.of(0, 1)); } @Override public void assertMaxValue(Block block, boolean exactResult) { assertThat(block, instanceOf(DoubleBlock.class)); final DoubleBlock db = (DoubleBlock) block; if (exactResult) { assertThat(db.getDouble(0), equalTo(max)); } else { assertThat(db.getDouble(0), lessThanOrEqualTo(max)); } } }; } }
LuceneMaxDoubleOperatorTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/MergeNotNullCollectionUsingIdentityTest.java
{ "start": 3123, "end": 3481 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne private Parent parent; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } } }
Child
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/util/TestUtil.java
{ "start": 10359, "end": 10559 }
class ____ the specified entity. */ public static Class<?> getMetamodelClassFor(Class<?> entityClass) { return getMetamodelClassFor( entityClass, false ); } /** * Returns the static metamodel
for
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ImmutableSetForContains.java
{ "start": 11057, "end": 11642 }
enum ____ { /** No usage detected. */ NEVER_USED, /** At least one allowed usage detected. No disallowed usage detected. */ ONLY_ALLOWED_USAGE, /** Disallowed usage detected. Allowed usage is ignored. */ DISALLOWED_USAGE; UsageState markAllowedUsageDetected() { if (this == DISALLOWED_USAGE) { return DISALLOWED_USAGE; } return ONLY_ALLOWED_USAGE; } UsageState markDisallowedUsageDetected() { return DISALLOWED_USAGE; } boolean shouldReport() { return this == ONLY_ALLOWED_USAGE; } } }
UsageState
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/update/UpdateIT.java
{ "start": 3299, "end": 31075 }
class ____ extends MockScriptPlugin { @Override public String pluginScriptLang() { return UPDATE_SCRIPTS; } @Override protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() { Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>(); scripts.put(PUT_VALUES_SCRIPT, vars -> { Map<String, Object> ctx = get(vars, "ctx"); assertNotNull(ctx); Map<String, Object> params = new HashMap<>(get(vars, "params")); @SuppressWarnings("unchecked") Map<String, Object> newCtx = (Map<String, Object>) params.remove("_ctx"); if (newCtx != null) { assertFalse(newCtx.containsKey("_source")); ctx.putAll(newCtx); } Map<String, Object> source = get(ctx, "_source"); params.remove("ctx"); source.putAll(params); return ctx; }); scripts.put(FIELD_INC_SCRIPT, vars -> { Map<String, Object> params = get(vars, "params"); String fieldname = (String) vars.get("field"); Map<String, Object> ctx = get(vars, "ctx"); assertNotNull(ctx); Map<String, Object> source = get(ctx, "_source"); Number currentValue = (Number) source.get(fieldname); Number inc = (Number) params.getOrDefault("inc", 1); source.put(fieldname, currentValue.longValue() + inc.longValue()); return ctx; }); scripts.put(UPSERT_SCRIPT, vars -> { Map<String, Object> ctx = get(vars, "ctx"); assertNotNull(ctx); Map<String, Object> source = get(ctx, "_source"); Number payment = (Number) vars.get("payment"); Number oldBalance = (Number) source.get("balance"); int deduction = "create".equals(ctx.get("op")) ? payment.intValue() / 2 : payment.intValue(); source.put("balance", oldBalance.intValue() - deduction); return ctx; }); scripts.put(EXTRACT_CTX_SCRIPT, vars -> { Map<String, Object> ctx = get(vars, "ctx"); assertNotNull(ctx); Map<String, Object> source = get(ctx, "_source"); Map<String, Object> ctxWithoutSource = new HashMap<>(ctx); ctxWithoutSource.remove("_source"); source.put("update_context", ctxWithoutSource); return ctx; }); return scripts; } } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(UpdateScriptsPlugin.class, InternalSettingsPlugin.class); } private void createTestIndex() throws Exception { logger.info("--> creating index test"); assertAcked(prepareCreate("test").addAlias(new Alias("alias").writeIndex(randomFrom(true, null)))); } public void testUpsert() throws Exception { createTestIndex(); ensureGreen(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject()) .setScript(fieldIncScript) .get(); assertEquals(DocWriteResponse.Result.CREATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("1")); } updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject()) .setScript(fieldIncScript) .get(); assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("2")); } } public void testScriptedUpsert() throws Exception { createTestIndex(); ensureGreen(); // Script logic is // 1) New accounts take balance from "balance" in upsert doc and first payment is charged at 50% // 2) Existing accounts subtract full payment from balance stored in elasticsearch int openingBalance = 10; Map<String, Object> params = new HashMap<>(); params.put("payment", 2); // Pay money from what will be a new account and opening balance comes from upsert doc // provided by client UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("balance", openingBalance).endObject()) .setScriptedUpsert(true) .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, UPSERT_SCRIPT, params)) .get(); assertEquals(DocWriteResponse.Result.CREATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("balance").toString(), equalTo("9")); } // Now pay money for an existing account where balance is stored in es updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("balance", openingBalance).endObject()) .setScriptedUpsert(true) .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, UPSERT_SCRIPT, params)) .get(); assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("balance").toString(), equalTo("7")); } } public void testUpsertDoc() throws Exception { createTestIndex(); ensureGreen(); UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()) .setDocAsUpsert(true) .setFetchSource(true) .get(); assertThat(updateResponse.getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult(), notNullValue()); assertThat(updateResponse.getGetResult().getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult().sourceAsMap().get("bar").toString(), equalTo("baz")); } // Issue #3265 public void testNotUpsertDoc() throws Exception { createTestIndex(); ensureGreen(); assertFutureThrows( client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()) .setDocAsUpsert(false) .setFetchSource(true) .execute(), DocumentMissingException.class ); } public void testUpsertFields() throws Exception { createTestIndex(); ensureGreen(); UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()) .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, PUT_VALUES_SCRIPT, Collections.singletonMap("extra", "foo"))) .setFetchSource(true) .get(); assertThat(updateResponse.getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult(), notNullValue()); assertThat(updateResponse.getGetResult().getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult().sourceAsMap().get("bar").toString(), equalTo("baz")); assertThat(updateResponse.getGetResult().sourceAsMap().get("extra"), nullValue()); updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()) .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, PUT_VALUES_SCRIPT, Collections.singletonMap("extra", "foo"))) .setFetchSource(true) .get(); assertThat(updateResponse.getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult(), notNullValue()); assertThat(updateResponse.getGetResult().getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult().sourceAsMap().get("bar").toString(), equalTo("baz")); assertThat(updateResponse.getGetResult().sourceAsMap().get("extra").toString(), equalTo("foo")); } public void testIndexAutoCreation() throws Exception { UpdateResponse updateResponse = client().prepareUpdate("test", "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject()) .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, PUT_VALUES_SCRIPT, Collections.singletonMap("extra", "foo"))) .setFetchSource(true) .get(); assertThat(updateResponse.getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult(), notNullValue()); assertThat(updateResponse.getGetResult().getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult().sourceAsMap().get("bar").toString(), equalTo("baz")); assertThat(updateResponse.getGetResult().sourceAsMap().get("extra"), nullValue()); } public void testUpdate() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias").writeIndex(true))); assertAcked(prepareCreate("test2").addAlias(new Alias("alias"))); ensureGreen(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); DocumentMissingException ex = expectThrows( DocumentMissingException.class, client().prepareUpdate(indexOrAlias(), "1").setScript(fieldIncScript) ); assertEquals("[1]: document missing", ex.getMessage()); prepareIndex("test").setId("1").setSource("field", 1).get(); UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1").setScript(fieldIncScript).get(); assertThat(updateResponse.getVersion(), equalTo(2L)); assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("2")); } Map<String, Object> params = new HashMap<>(); params.put("inc", 3); params.put("field", "field"); updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, params)) .get(); assertThat(updateResponse.getVersion(), equalTo(3L)); assertEquals(DocWriteResponse.Result.UPDATED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("5")); } // check noop updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setScript( new Script( ScriptType.INLINE, UPDATE_SCRIPTS, PUT_VALUES_SCRIPT, Collections.singletonMap("_ctx", Collections.singletonMap("op", "none")) ) ) .get(); assertThat(updateResponse.getVersion(), equalTo(3L)); assertEquals(DocWriteResponse.Result.NOOP, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("5")); } // check delete updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setScript( new Script( ScriptType.INLINE, UPDATE_SCRIPTS, PUT_VALUES_SCRIPT, Collections.singletonMap("_ctx", Collections.singletonMap("op", "delete")) ) ) .get(); assertThat(updateResponse.getVersion(), equalTo(4L)); assertEquals(DocWriteResponse.Result.DELETED, updateResponse.getResult()); assertThat(updateResponse.getIndex(), equalTo("test")); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.isExists(), equalTo(false)); } // check _source parameter prepareIndex("test").setId("1").setSource("field1", 1, "field2", 2).get(); updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field1"))) .setFetchSource("field1", "field2") .get(); assertThat(updateResponse.getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult(), notNullValue()); assertThat(updateResponse.getGetResult().getIndex(), equalTo("test")); assertThat(updateResponse.getGetResult().sourceRef(), notNullValue()); assertThat(updateResponse.getGetResult().field("field1"), nullValue()); assertThat(updateResponse.getGetResult().sourceAsMap().size(), equalTo(1)); assertThat(updateResponse.getGetResult().sourceAsMap().get("field1"), equalTo(2)); // check updates without script // add new field prepareIndex("test").setId("1").setSource("field", 1).get(); client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field2", 2).endObject()) .get(); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("1")); assertThat(getResponse.getSourceAsMap().get("field2").toString(), equalTo("2")); } // change existing field client().prepareUpdate(indexOrAlias(), "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field", 3).endObject()).get(); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); assertThat(getResponse.getSourceAsMap().get("field").toString(), equalTo("3")); assertThat(getResponse.getSourceAsMap().get("field2").toString(), equalTo("2")); } // recursive map Map<String, Object> testMap = new HashMap<>(); Map<String, Object> testMap2 = new HashMap<>(); Map<String, Object> testMap3 = new HashMap<>(); testMap3.put("commonkey", testMap); testMap3.put("map3", 5); testMap2.put("map2", 6); testMap.put("commonkey", testMap2); testMap.put("map1", 8); prepareIndex("test").setId("1").setSource("map", testMap).get(); client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("map", testMap3).endObject()) .get(); for (int i = 0; i < 5; i++) { GetResponse getResponse = client().prepareGet("test", "1").get(); Map<String, Object> map1 = get(getResponse.getSourceAsMap(), "map"); assertThat(map1.size(), equalTo(3)); assertThat(map1.containsKey("map1"), equalTo(true)); assertThat(map1.containsKey("map3"), equalTo(true)); assertThat(map1.containsKey("commonkey"), equalTo(true)); Map<String, Object> map2 = get(map1, "commonkey"); assertThat(map2.size(), equalTo(3)); assertThat(map2.containsKey("map1"), equalTo(true)); assertThat(map2.containsKey("map2"), equalTo(true)); assertThat(map2.containsKey("commonkey"), equalTo(true)); } } public void testUpdateWithIfSeqNo() throws Exception { createTestIndex(); ensureGreen(); DocWriteResponse result = prepareIndex("test").setId("1").setSource("field", 1).get(); expectThrows( VersionConflictEngineException.class, client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field", 2).endObject()) .setIfSeqNo(result.getSeqNo() + 1) .setIfPrimaryTerm(result.getPrimaryTerm()) ); expectThrows( VersionConflictEngineException.class, client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field", 2).endObject()) .setIfSeqNo(result.getSeqNo()) .setIfPrimaryTerm(result.getPrimaryTerm() + 1) ); expectThrows( VersionConflictEngineException.class, client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field", 2).endObject()) .setIfSeqNo(result.getSeqNo() + 1) .setIfPrimaryTerm(result.getPrimaryTerm() + 1) ); UpdateResponse updateResponse = client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field", 2).endObject()) .setIfSeqNo(result.getSeqNo()) .setIfPrimaryTerm(result.getPrimaryTerm()) .get(); assertThat(updateResponse.status(), equalTo(RestStatus.OK)); assertThat(updateResponse.getSeqNo(), equalTo(result.getSeqNo() + 1)); } public void testUpdateRequestWithBothScriptAndDoc() throws Exception { createTestIndex(); ensureGreen(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); try { client().prepareUpdate(indexOrAlias(), "1") .setDoc(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject()) .setScript(fieldIncScript) .get(); fail("Should have thrown ActionRequestValidationException"); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors().size(), equalTo(1)); assertThat(e.validationErrors().get(0), containsString("can't provide both script and doc")); assertThat(e.getMessage(), containsString("can't provide both script and doc")); } } public void testUpdateRequestWithScriptAndShouldUpsertDoc() throws Exception { createTestIndex(); ensureGreen(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); try { client().prepareUpdate(indexOrAlias(), "1").setScript(fieldIncScript).setDocAsUpsert(true).get(); fail("Should have thrown ActionRequestValidationException"); } catch (ActionRequestValidationException e) { assertThat(e.validationErrors().size(), equalTo(1)); assertThat(e.validationErrors().get(0), containsString("doc must be specified if doc_as_upsert is enabled")); assertThat(e.getMessage(), containsString("doc must be specified if doc_as_upsert is enabled")); } } public void testContextVariables() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias"))); ensureGreen(); // Index some documents prepareIndex("test").setId("id1").setRouting("routing1").setSource("field1", 1, "content", "foo").get(); prepareIndex("test").setId("id2").setSource("field1", 0, "content", "bar").get(); // Update the first object and note context variables values UpdateResponse updateResponse = client().prepareUpdate("test", "id1") .setRouting("routing1") .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, EXTRACT_CTX_SCRIPT, Collections.emptyMap())) .get(); assertEquals(2, updateResponse.getVersion()); GetResponse getResponse = client().prepareGet("test", "id1").setRouting("routing1").get(); Map<String, Object> updateContext = get(getResponse.getSourceAsMap(), "update_context"); assertEquals("test", updateContext.get("_index")); assertEquals("id1", updateContext.get("_id")); assertEquals(1, updateContext.get("_version")); assertEquals("routing1", updateContext.get("_routing")); // Idem with the second object updateResponse = client().prepareUpdate("test", "id2") .setScript(new Script(ScriptType.INLINE, UPDATE_SCRIPTS, EXTRACT_CTX_SCRIPT, Collections.emptyMap())) .get(); assertEquals(2, updateResponse.getVersion()); getResponse = client().prepareGet("test", "id2").get(); updateContext = get(getResponse.getSourceAsMap(), "update_context"); assertEquals("test", updateContext.get("_index")); assertEquals("id2", updateContext.get("_id")); assertEquals(1, updateContext.get("_version")); assertNull(updateContext.get("_routing")); assertNull(updateContext.get("_ttl")); } public void testConcurrentUpdateWithRetryOnConflict() throws Exception { final boolean useBulkApi = randomBoolean(); createTestIndex(); ensureGreen(); int numberOfThreads = scaledRandomIntBetween(2, 5); final CountDownLatch latch = new CountDownLatch(numberOfThreads); final CountDownLatch startLatch = new CountDownLatch(1); final int numberOfUpdatesPerThread = scaledRandomIntBetween(100, 500); final List<Exception> failures = new CopyOnWriteArrayList<>(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); for (int i = 0; i < numberOfThreads; i++) { Runnable r = new Runnable() { @Override public void run() { try { startLatch.await(); for (int i = 0; i < numberOfUpdatesPerThread; i++) { if (i % 100 == 0) { logger.debug( "Client [{}] issued [{}] of [{}] requests", Thread.currentThread().getName(), i, numberOfUpdatesPerThread ); } if (useBulkApi) { UpdateRequestBuilder updateRequestBuilder = client().prepareUpdate(indexOrAlias(), Integer.toString(i)) .setScript(fieldIncScript) .setRetryOnConflict(Integer.MAX_VALUE) .setUpsert(jsonBuilder().startObject().field("field", 1).endObject()); client().prepareBulk().add(updateRequestBuilder).get(); } else { client().prepareUpdate(indexOrAlias(), Integer.toString(i)) .setScript(fieldIncScript) .setRetryOnConflict(Integer.MAX_VALUE) .setUpsert(jsonBuilder().startObject().field("field", 1).endObject()) .get(); } } logger.info("Client [{}] issued all [{}] requests.", Thread.currentThread().getName(), numberOfUpdatesPerThread); } catch (InterruptedException e) { // test infrastructure kills long-running tests by interrupting them, thus we handle this case separately logger.warn( "Test was forcefully stopped. Client [{}] may still have outstanding requests.", Thread.currentThread().getName() ); failures.add(e); Thread.currentThread().interrupt(); } catch (Exception e) { failures.add(e); } finally { latch.countDown(); } } }; Thread updater = new Thread(r); updater.setName("UpdateIT-Client-" + i); updater.start(); } startLatch.countDown(); latch.await(); for (Throwable throwable : failures) { logger.info("Captured failure on concurrent update:", throwable); } assertThat(failures.size(), equalTo(0)); for (int i = 0; i < numberOfUpdatesPerThread; i++) { GetResponse response = client().prepareGet("test", Integer.toString(i)).get(); assertThat(response.getId(), equalTo(Integer.toString(i))); assertThat(response.isExists(), equalTo(true)); assertThat(response.getVersion(), equalTo((long) numberOfThreads)); assertThat(response.getSource().get("field"), equalTo(numberOfThreads)); } } public void testStressUpdateDeleteConcurrency() throws Exception { // We create an index with merging disabled so that deletes don't get merged away assertAcked(prepareCreate("test").setSettings(Settings.builder().put(MergePolicyConfig.INDEX_MERGE_ENABLED, false))); ensureGreen(); Script fieldIncScript = new Script(ScriptType.INLINE, UPDATE_SCRIPTS, FIELD_INC_SCRIPT, Collections.singletonMap("field", "field")); final int numberOfThreads = scaledRandomIntBetween(3, 5); final int numberOfIdsPerThread = scaledRandomIntBetween(3, 10); final int numberOfUpdatesPerId = scaledRandomIntBetween(10, 100); final int retryOnConflict = randomIntBetween(0, 1); final CountDownLatch latch = new CountDownLatch(numberOfThreads); final CountDownLatch startLatch = new CountDownLatch(1); final List<Throwable> failures = new CopyOnWriteArrayList<>(); final
UpdateScriptsPlugin
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/main/java/io/quarkus/resteasy/reactive/jackson/deployment/processor/JacksonDeserializerFactory.java
{ "start": 5445, "end": 5498 }
class ____ the following * * <pre>{@code * public
like
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/typeRef/TypeReferenceTest13.java
{ "start": 1357, "end": 2030 }
class ____<I, F> extends BaseResult { /** * 大的结果对象,包含结果数据、耗时、数量统计等信息 */ @JSONField(name = "result") private ResultDO<I, F> result; /** * 目前没有用到 */ @JSONField(name = "tracer") private String tracer; public String getTracer() { return tracer; } public void setTracer(String tracer) { this.tracer = tracer; } public ResultDO<I, F> getResult() { return result; } public void setResult(ResultDO<I, F> result) { this.result = result; } } public static
SearchResult
java
apache__camel
components/camel-cxf/camel-cxf-spring-soap/src/main/java/org/apache/camel/component/cxf/spring/jaxws/CxfEndpointBeanDefinitionParser.java
{ "start": 1273, "end": 3887 }
class ____ extends AbstractCxfBeanDefinitionParser { @Override protected Class<?> getBeanClass(Element arg0) { return CxfSpringEndpoint.class; } private boolean isSpringPlaceHolder(String value) { if (value != null && (value.startsWith("${") && value.endsWith("}") || value.startsWith("{{") && value.endsWith("}}"))) { return true; } return false; } @Override protected boolean parseAttributes(Element element, ParserContext ctx, BeanDefinitionBuilder bean) { boolean addedBus = super.parseAttributes(element, ctx, bean); final String bus = element.getAttribute("bus"); if (!addedBus && !StringUtils.isEmpty(bus)) { bean.addPropertyReference("bus", bus.startsWith("#") ? bus.substring(1) : bus); addedBus = true; } return addedBus; } @Override protected void mapAttribute(BeanDefinitionBuilder bean, Element e, String name, String val) { if ("endpointName".equals(name) || "serviceName".equals(name)) { if (isSpringPlaceHolder(val)) { // set the property with the String value directly mapToProperty(bean, name, val); } else { QName q = parseQName(e, val); bean.addPropertyValue(name + "AsQName", q); } } else { mapToProperty(bean, name, val); } } @Override protected void mapElement(ParserContext ctx, BeanDefinitionBuilder bean, Element el, String name) { if ("properties".equals(name)) { Map<String, Object> map = CastUtils.cast(ctx.getDelegate().parseMapElement(el, bean.getBeanDefinition())); Map<String, Object> props = getPropertyMap(bean, false); if (props != null) { map.putAll(props); } bean.addPropertyValue("properties", map); } else if ("binding".equals(name)) { setFirstChildAsProperty(el, ctx, bean, "bindingConfig"); } else if ("inInterceptors".equals(name) || "inFaultInterceptors".equals(name) || "outInterceptors".equals(name) || "outFaultInterceptors".equals(name) || "features".equals(name) || "schemaLocations".equals(name) || "handlers".equals(name)) { List<?> list = ctx.getDelegate().parseListElement(el, bean.getBeanDefinition()); bean.addPropertyValue(name, list); } else { setFirstChildAsProperty(el, ctx, bean, name); } } }
CxfEndpointBeanDefinitionParser
java
spring-projects__spring-boot
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
{ "start": 1289, "end": 2583 }
class ____ coerce values to another type when requested. * <ul> * <li>When the requested type is a boolean, strings will be coerced using a * case-insensitive comparison to "true" and "false". * <li>When the requested type is a double, other {@link Number} types will be coerced * using {@link Number#doubleValue() doubleValue}. Strings that can be coerced using * {@link Double#valueOf(String)} will be. * <li>When the requested type is an int, other {@link Number} types will be coerced using * {@link Number#intValue() intValue}. Strings that can be coerced using * {@link Double#valueOf(String)} will be, and then cast to int. * <li><a id="lossy">When the requested type is a long, other {@link Number} types will be * coerced using {@link Number#longValue() longValue}. Strings that can be coerced using * {@link Double#valueOf(String)} will be, and then cast to long. This two-step conversion * is lossy for very large values. For example, the string "9223372036854775806" yields * the long 9223372036854775807.</a> * <li>When the requested type is a String, other non-null values will be coerced using * {@link String#valueOf(Object)}. Although null cannot be coerced, the sentinel value * {@link JSONObject#NULL} is coerced to the string "null". * </ul> * <p> * This
can
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/util/PropertyFilePropertySource.java
{ "start": 1263, "end": 2340 }
class ____ extends PropertiesPropertySource { private static final Logger LOGGER = StatusLogger.getLogger(); public PropertyFilePropertySource(final String fileName) { this(fileName, true); } /** * @since 2.18.0 */ public PropertyFilePropertySource(final String fileName, final boolean useTccl) { super(loadPropertiesFile(fileName, useTccl)); } @SuppressFBWarnings( value = "URLCONNECTION_SSRF_FD", justification = "This property source should only be used with hardcoded file names.") private static Properties loadPropertiesFile(final String fileName, final boolean useTccl) { final Properties props = new Properties(); for (final URL url : LoaderUtil.findResources(fileName, useTccl)) { try (final InputStream in = url.openStream()) { props.load(in); } catch (final IOException error) { LOGGER.error("Unable to read URL `{}`", url, error); } } return props; } }
PropertyFilePropertySource
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MinioEndpointBuilderFactory.java
{ "start": 72732, "end": 76632 }
class ____ set in the request. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param storageClass the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder storageClass(String storageClass) { doSetProperty("storageClass", storageClass); return this; } /** * Amazon AWS Secret Access Key or Minio Access Key. If not set camel * will connect to service for anonymous access. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param accessKey the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder accessKey(String accessKey) { doSetProperty("accessKey", accessKey); return this; } /** * Amazon AWS Access Key Id or Minio Secret Key. If not set camel will * connect to service for anonymous access. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param secretKey the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder secretKey(String secretKey) { doSetProperty("secretKey", secretKey); return this; } /** * Server-side encryption. * * The option is a: <code>io.minio.ServerSideEncryption</code> type. * * Group: security * * @param serverSideEncryption the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder serverSideEncryption(io.minio.ServerSideEncryption serverSideEncryption) { doSetProperty("serverSideEncryption", serverSideEncryption); return this; } /** * Server-side encryption. * * The option will be converted to a * <code>io.minio.ServerSideEncryption</code> type. * * Group: security * * @param serverSideEncryption the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder serverSideEncryption(String serverSideEncryption) { doSetProperty("serverSideEncryption", serverSideEncryption); return this; } /** * Server-side encryption for source object while copy/move objects. * * The option is a: * <code>io.minio.ServerSideEncryptionCustomerKey</code> type. * * Group: security * * @param serverSideEncryptionCustomerKey the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder serverSideEncryptionCustomerKey(io.minio.ServerSideEncryptionCustomerKey serverSideEncryptionCustomerKey) { doSetProperty("serverSideEncryptionCustomerKey", serverSideEncryptionCustomerKey); return this; } /** * Server-side encryption for source object while copy/move objects. * * The option will be converted to a * <code>io.minio.ServerSideEncryptionCustomerKey</code> type. * * Group: security * * @param serverSideEncryptionCustomerKey the value to set * @return the dsl builder */ default MinioEndpointProducerBuilder serverSideEncryptionCustomerKey(String serverSideEncryptionCustomerKey) { doSetProperty("serverSideEncryptionCustomerKey", serverSideEncryptionCustomerKey); return this; } } /** * Advanced builder for endpoint producers for the Minio component. */ public
to
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleExplainTest.java
{ "start": 930, "end": 3000 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "EXPLAIN PLAN SET STATEMENT_ID='PLUS19628905' FOR select * from( select row_.*, rownum rownum_ from( SELECT h.id taskId, t.id tradeId, t.OUT_ORDER_ID orderId, t.SELLER_SEQ sellerSeq, t.BUYER_SEQ buyerSeq, h.RECORD_TYPE recordType, t.SELLER_LOGIN_ID sellerLoginId, t.SELLER_ADMIN_SEQ sellerAdminSeq, h.GMT_CREATE gmtTaskCreate, h.GMT_MODIFIED gmtTaskModified, h.GMT_FETCH_TASK gmtFetchTask, h.GMT_FINISH_TASK gmtFinishTask, h.STATUS status, h.OWNER owner FROM HT_TASK_TRADE_HISTORY h, escrow_trade t WHERE h.TRADE_ID= t.ID and h.OWNER='zhoufei.zhangzf' and h.STATUS in('running') ORDER BY h.TASK_FLOW_LEVEL, t.GMT_CREATE, h.GMT_MODIFIED DESC) row_ where rownum<= 100) where rownum_>= 80"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("\"DUAL\""))); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleExplainTest
java
spring-projects__spring-boot
system-test/spring-boot-image-system-tests/src/systemTest/java/org/springframework/boot/image/assertions/ContainerConfigAssert.java
{ "start": 2783, "end": 3225 }
class ____ extends AbstractMapAssert<LabelsAssert, Map<String, String>, String, String> { protected LabelsAssert(Map<String, String> labels) { super(labels, LabelsAssert.class); } } /** * Asserts for the JSON content in the {@code io.buildpacks.build.metadata} label. * * See <a href= * "https://github.com/buildpacks/spec/blob/main/platform.md#iobuildpacksbuildmetadata-json">the * spec</a> */ public static
LabelsAssert
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-structured-logging-log4j2/src/main/java/smoketest/structuredlogging/log4j2/DuplicateJsonMembersCustomizer.java
{ "start": 854, "end": 1109 }
class ____ implements StructuredLoggingJsonMembersCustomizer<Object> { @Override public void customize(Members<Object> members) { members.add("test").as(Objects::toString); members.add("test").as(Objects::toString); } }
DuplicateJsonMembersCustomizer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/NamedRegistry.java
{ "start": 699, "end": 789 }
class ____. Used to ensure implementations are registered only once. */ public
implementation
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingRCATest.java
{ "start": 14806, "end": 16500 }
class ____ extends Expression { private Expression left; private Expression right; private MathOperator op; public MathExpression() { } public MathExpression(Expression left, Expression right, MathOperator op) { this.left = left; this.right = right; this.op = op; } @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "left_expression_id") public Expression getLeft() { return left; } public void setLeft(Expression left) { this.left = left; } @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "right_expression_id") public Expression getRight() { return right; } public void setRight(Expression right) { this.right = right; } public MathOperator getOp() { return op; } public void setOp(MathOperator op) { this.op = op; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } MathExpression that = (MathExpression) o; if (left != null ? !left.equals(that.left) : that.left != null) { return false; } if (op != that.op) { return false; } return Objects.equals( right, that.right ); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (left != null ? left.hashCode() : 0); result = 31 * result + (right != null ? right.hashCode() : 0); result = 31 * result + (op != null ? op.hashCode() : 0); return result; } } @SuppressWarnings("unused") @Entity(name = "FieldExpression") public static
MathExpression
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
{ "start": 2930, "end": 3684 }
class ____ automatically opens a default "system" TCP connection to the * message broker that is used for sending messages that originate from the server * application (as opposed to from a client). Such messages are not associated with * any client and therefore do not have a session id header. The "system" connection * is effectively shared and cannot be used to receive messages. Several properties * are provided to configure the "system" connection including: * <ul> * <li>{@link #setSystemLogin}</li> * <li>{@link #setSystemPasscode}</li> * <li>{@link #setSystemHeartbeatSendInterval}</li> * <li>{@link #setSystemHeartbeatReceiveInterval}</li> * </ul> * * @author Rossen Stoyanchev * @author Andy Wilkinson * @since 4.0 */ public
also
java
elastic__elasticsearch
libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/DummyImplementations.java
{ "start": 11445, "end": 11691 }
class ____ extends ServerSocket { DummyBoundServerSocket() { super(new DummySocketImpl()); } @Override public boolean isBound() { return true; } } static
DummyBoundServerSocket
java
quarkusio__quarkus
extensions/oidc-token-propagation-reactive/deployment/src/test/java/io/quarkus/oidc/token/propagation/reactive/deployment/test/AccessTokenAnnotationTest.java
{ "start": 8449, "end": 8704 }
interface ____ { @AccessToken(exchangeTokenClient = "named") @GET String getUserName(); } // tests no AmbiguousResolutionException is raised @Singleton @Unremovable public static
NamedClientDefaultExchange_OnMethod
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/DoAsParam.java
{ "start": 899, "end": 1415 }
class ____ extends StringParam { /** Parameter name. */ public static final String NAME = "doas"; /** Default parameter value. */ public static final String DEFAULT = ""; private static final Domain DOMAIN = new Domain(NAME, null); /** * Constructor. * @param str a string representation of the parameter value. */ public DoAsParam(final String str) { super(DOMAIN, str == null || str.equals(DEFAULT)? null: str); } @Override public String getName() { return NAME; } }
DoAsParam
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AWS2S3EndpointBuilderFactory.java
{ "start": 52687, "end": 67443 }
interface ____ extends EndpointConsumerBuilder { default AWS2S3EndpointConsumerBuilder basic() { return (AWS2S3EndpointConsumerBuilder) this; } /** * Define the customer algorithm to use in case CustomerKey is enabled. * * The option is a: <code>java.lang.String</code> type. * * Group: common (advanced) * * @param customerAlgorithm the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder customerAlgorithm(String customerAlgorithm) { doSetProperty("customerAlgorithm", customerAlgorithm); return this; } /** * Define the id of the Customer key to use in case CustomerKey is * enabled. * * The option is a: <code>java.lang.String</code> type. * * Group: common (advanced) * * @param customerKeyId the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder customerKeyId(String customerKeyId) { doSetProperty("customerKeyId", customerKeyId); return this; } /** * Define the MD5 of Customer key to use in case CustomerKey is enabled. * * The option is a: <code>java.lang.String</code> type. * * Group: common (advanced) * * @param customerKeyMD5 the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder customerKeyMD5(String customerKeyMD5) { doSetProperty("customerKeyMD5", customerKeyMD5); return this; } /** * If this option is true and includeBody is false, then the * S3Object.close() method will be called on exchange completion. This * option is strongly related to includeBody option. In case of setting * includeBody to false and autocloseBody to false, it will be up to the * caller to close the S3Object stream. Setting autocloseBody to true, * will close the S3Object stream automatically. * * The option is a: <code>boolean</code> type. * * Default: true * Group: consumer (advanced) * * @param autocloseBody the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder autocloseBody(boolean autocloseBody) { doSetProperty("autocloseBody", autocloseBody); return this; } /** * If this option is true and includeBody is false, then the * S3Object.close() method will be called on exchange completion. This * option is strongly related to includeBody option. In case of setting * includeBody to false and autocloseBody to false, it will be up to the * caller to close the S3Object stream. Setting autocloseBody to true, * will close the S3Object stream automatically. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: consumer (advanced) * * @param autocloseBody the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder autocloseBody(String autocloseBody) { doSetProperty("autocloseBody", autocloseBody); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable in-progress repository * org.apache.camel.spi.IdempotentRepository. The in-progress repository * is used to account the current in progress files being consumed. By * default a memory based repository is used. * * The option is a: * <code>org.apache.camel.spi.IdempotentRepository</code> type. * * Group: consumer (advanced) * * @param inProgressRepository the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder inProgressRepository(org.apache.camel.spi.IdempotentRepository inProgressRepository) { doSetProperty("inProgressRepository", inProgressRepository); return this; } /** * A pluggable in-progress repository * org.apache.camel.spi.IdempotentRepository. The in-progress repository * is used to account the current in progress files being consumed. By * default a memory based repository is used. * * The option will be converted to a * <code>org.apache.camel.spi.IdempotentRepository</code> type. * * Group: consumer (advanced) * * @param inProgressRepository the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder inProgressRepository(String inProgressRepository) { doSetProperty("inProgressRepository", inProgressRepository); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) * * @param pollStrategy the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder pollStrategy(String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * Reference to a com.amazonaws.services.s3.AmazonS3 in the registry. * * The option is a: * <code>software.amazon.awssdk.services.s3.S3Client</code> type. * * Group: advanced * * @param amazonS3Client the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder amazonS3Client(software.amazon.awssdk.services.s3.S3Client amazonS3Client) { doSetProperty("amazonS3Client", amazonS3Client); return this; } /** * Reference to a com.amazonaws.services.s3.AmazonS3 in the registry. * * The option will be converted to a * <code>software.amazon.awssdk.services.s3.S3Client</code> type. * * Group: advanced * * @param amazonS3Client the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder amazonS3Client(String amazonS3Client) { doSetProperty("amazonS3Client", amazonS3Client); return this; } /** * An S3 Presigner for Request, used mainly in createDownloadLink * operation. * * The option is a: * <code>software.amazon.awssdk.services.s3.presigner.S3Presigner</code> * type. * * Group: advanced * * @param amazonS3Presigner the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder amazonS3Presigner(software.amazon.awssdk.services.s3.presigner.S3Presigner amazonS3Presigner) { doSetProperty("amazonS3Presigner", amazonS3Presigner); return this; } /** * An S3 Presigner for Request, used mainly in createDownloadLink * operation. * * The option will be converted to a * <code>software.amazon.awssdk.services.s3.presigner.S3Presigner</code> * type. * * Group: advanced * * @param amazonS3Presigner the value to set * @return the dsl builder */ default AdvancedAWS2S3EndpointConsumerBuilder amazonS3Presigner(String amazonS3Presigner) { doSetProperty("amazonS3Presigner", amazonS3Presigner); return this; } } /** * Builder for endpoint producers for the AWS S3 Storage Service component. */ public
AdvancedAWS2S3EndpointConsumerBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/internal/NullPrecedenceTest.java
{ "start": 1929, "end": 2334 }
class ____ { private long id; private String bar; public Foo() { } public Foo(long id, String bar) { this.id = id; this.bar = bar; } @Id @Column(nullable = false) public long getId() { return this.id; } public void setId(final long id) { this.id = id; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } } }
Foo
java
alibaba__nacos
client/src/main/java/com/alibaba/nacos/client/config/impl/ConfigFuzzyWatcherWrapper.java
{ "start": 900, "end": 2131 }
class ____ { long syncVersion = 0; FuzzyWatchEventWatcher fuzzyWatchEventWatcher; public ConfigFuzzyWatcherWrapper(FuzzyWatchEventWatcher fuzzyWatchEventWatcher) { this.fuzzyWatchEventWatcher = fuzzyWatchEventWatcher; } /** * Unique identifier for the listener. */ String uuid = UUID.randomUUID().toString(); private Set<String> syncGroupKeys = new HashSet<>(); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfigFuzzyWatcherWrapper that = (ConfigFuzzyWatcherWrapper) o; return Objects.equals(fuzzyWatchEventWatcher, that.fuzzyWatchEventWatcher) && Objects.equals(uuid, that.uuid); } @Override public int hashCode() { return Objects.hash(fuzzyWatchEventWatcher, uuid); } Set<String> getSyncGroupKeys() { return syncGroupKeys; } /** * Get the UUID (Unique Identifier) of the listener. * * @return The UUID of the listener */ String getUuid() { return uuid; } }
ConfigFuzzyWatcherWrapper
java
apache__camel
components/camel-mail/src/generated/java/org/apache/camel/component/mail/MailComponentConfigurer.java
{ "start": 731, "end": 20018 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.mail.MailConfiguration getOrCreateConfiguration(MailComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.mail.MailConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { MailComponent target = (MailComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionaljavamailproperties": case "additionalJavaMailProperties": getOrCreateConfiguration(target).setAdditionalJavaMailProperties(property(camelContext, java.util.Properties.class, value)); return true; case "alternativebodyheader": case "alternativeBodyHeader": getOrCreateConfiguration(target).setAlternativeBodyHeader(property(camelContext, java.lang.String.class, value)); return true; case "attachmentscontenttransferencodingresolver": case "attachmentsContentTransferEncodingResolver": getOrCreateConfiguration(target).setAttachmentsContentTransferEncodingResolver(property(camelContext, org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver.class, value)); return true; case "authenticator": getOrCreateConfiguration(target).setAuthenticator(property(camelContext, org.apache.camel.component.mail.MailAuthenticator.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bcc": getOrCreateConfiguration(target).setBcc(property(camelContext, java.lang.String.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "cc": getOrCreateConfiguration(target).setCc(property(camelContext, java.lang.String.class, value)); return true; case "closefolder": case "closeFolder": getOrCreateConfiguration(target).setCloseFolder(property(camelContext, boolean.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.mail.MailConfiguration.class, value)); return true; case "connectiontimeout": case "connectionTimeout": getOrCreateConfiguration(target).setConnectionTimeout(property(camelContext, int.class, value)); return true; case "contenttype": case "contentType": getOrCreateConfiguration(target).setContentType(property(camelContext, java.lang.String.class, value)); return true; case "contenttyperesolver": case "contentTypeResolver": target.setContentTypeResolver(property(camelContext, org.apache.camel.component.mail.ContentTypeResolver.class, value)); return true; case "copyto": case "copyTo": getOrCreateConfiguration(target).setCopyTo(property(camelContext, java.lang.String.class, value)); return true; case "debugmode": case "debugMode": getOrCreateConfiguration(target).setDebugMode(property(camelContext, boolean.class, value)); return true; case "decodefilename": case "decodeFilename": getOrCreateConfiguration(target).setDecodeFilename(property(camelContext, boolean.class, value)); return true; case "delete": getOrCreateConfiguration(target).setDelete(property(camelContext, boolean.class, value)); return true; case "disconnect": getOrCreateConfiguration(target).setDisconnect(property(camelContext, boolean.class, value)); return true; case "failonduplicatefileattachment": case "failOnDuplicateFileAttachment": getOrCreateConfiguration(target).setFailOnDuplicateFileAttachment(property(camelContext, boolean.class, value)); return true; case "fetchsize": case "fetchSize": getOrCreateConfiguration(target).setFetchSize(property(camelContext, int.class, value)); return true; case "foldername": case "folderName": getOrCreateConfiguration(target).setFolderName(property(camelContext, java.lang.String.class, value)); return true; case "from": getOrCreateConfiguration(target).setFrom(property(camelContext, java.lang.String.class, value)); return true; case "generatemissingattachmentnames": case "generateMissingAttachmentNames": getOrCreateConfiguration(target).setGenerateMissingAttachmentNames(property(camelContext, java.lang.String.class, value)); return true; case "handleduplicateattachmentnames": case "handleDuplicateAttachmentNames": getOrCreateConfiguration(target).setHandleDuplicateAttachmentNames(property(camelContext, java.lang.String.class, value)); return true; case "handlefailedmessage": case "handleFailedMessage": getOrCreateConfiguration(target).setHandleFailedMessage(property(camelContext, boolean.class, value)); return true; case "headerfilterstrategy": case "headerFilterStrategy": target.setHeaderFilterStrategy(property(camelContext, org.apache.camel.spi.HeaderFilterStrategy.class, value)); return true; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true; case "ignoreunsupportedcharset": case "ignoreUnsupportedCharset": getOrCreateConfiguration(target).setIgnoreUnsupportedCharset(property(camelContext, boolean.class, value)); return true; case "ignoreurischeme": case "ignoreUriScheme": getOrCreateConfiguration(target).setIgnoreUriScheme(property(camelContext, boolean.class, value)); return true; case "javamailproperties": case "javaMailProperties": getOrCreateConfiguration(target).setJavaMailProperties(property(camelContext, java.util.Properties.class, value)); return true; case "javamailsender": case "javaMailSender": getOrCreateConfiguration(target).setJavaMailSender(property(camelContext, org.apache.camel.component.mail.JavaMailSender.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "mapmailmessage": case "mapMailMessage": getOrCreateConfiguration(target).setMapMailMessage(property(camelContext, boolean.class, value)); return true; case "mimedecodeheaders": case "mimeDecodeHeaders": getOrCreateConfiguration(target).setMimeDecodeHeaders(property(camelContext, boolean.class, value)); return true; case "moveto": case "moveTo": getOrCreateConfiguration(target).setMoveTo(property(camelContext, java.lang.String.class, value)); return true; case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true; case "peek": getOrCreateConfiguration(target).setPeek(property(camelContext, boolean.class, value)); return true; case "replyto": case "replyTo": getOrCreateConfiguration(target).setReplyTo(property(camelContext, java.lang.String.class, value)); return true; case "session": getOrCreateConfiguration(target).setSession(property(camelContext, jakarta.mail.Session.class, value)); return true; case "skipfailedmessage": case "skipFailedMessage": getOrCreateConfiguration(target).setSkipFailedMessage(property(camelContext, boolean.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": getOrCreateConfiguration(target).setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "subject": getOrCreateConfiguration(target).setSubject(property(camelContext, java.lang.String.class, value)); return true; case "to": getOrCreateConfiguration(target).setTo(property(camelContext, java.lang.String.class, value)); return true; case "unseen": getOrCreateConfiguration(target).setUnseen(property(camelContext, boolean.class, value)); return true; case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": target.setUseGlobalSslContextParameters(property(camelContext, boolean.class, value)); return true; case "useinlineattachments": case "useInlineAttachments": getOrCreateConfiguration(target).setUseInlineAttachments(property(camelContext, boolean.class, value)); return true; case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "additionaljavamailproperties": case "additionalJavaMailProperties": return java.util.Properties.class; case "alternativebodyheader": case "alternativeBodyHeader": return java.lang.String.class; case "attachmentscontenttransferencodingresolver": case "attachmentsContentTransferEncodingResolver": return org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver.class; case "authenticator": return org.apache.camel.component.mail.MailAuthenticator.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bcc": return java.lang.String.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "cc": return java.lang.String.class; case "closefolder": case "closeFolder": return boolean.class; case "configuration": return org.apache.camel.component.mail.MailConfiguration.class; case "connectiontimeout": case "connectionTimeout": return int.class; case "contenttype": case "contentType": return java.lang.String.class; case "contenttyperesolver": case "contentTypeResolver": return org.apache.camel.component.mail.ContentTypeResolver.class; case "copyto": case "copyTo": return java.lang.String.class; case "debugmode": case "debugMode": return boolean.class; case "decodefilename": case "decodeFilename": return boolean.class; case "delete": return boolean.class; case "disconnect": return boolean.class; case "failonduplicatefileattachment": case "failOnDuplicateFileAttachment": return boolean.class; case "fetchsize": case "fetchSize": return int.class; case "foldername": case "folderName": return java.lang.String.class; case "from": return java.lang.String.class; case "generatemissingattachmentnames": case "generateMissingAttachmentNames": return java.lang.String.class; case "handleduplicateattachmentnames": case "handleDuplicateAttachmentNames": return java.lang.String.class; case "handlefailedmessage": case "handleFailedMessage": return boolean.class; case "headerfilterstrategy": case "headerFilterStrategy": return org.apache.camel.spi.HeaderFilterStrategy.class; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return boolean.class; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return boolean.class; case "ignoreunsupportedcharset": case "ignoreUnsupportedCharset": return boolean.class; case "ignoreurischeme": case "ignoreUriScheme": return boolean.class; case "javamailproperties": case "javaMailProperties": return java.util.Properties.class; case "javamailsender": case "javaMailSender": return org.apache.camel.component.mail.JavaMailSender.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "mapmailmessage": case "mapMailMessage": return boolean.class; case "mimedecodeheaders": case "mimeDecodeHeaders": return boolean.class; case "moveto": case "moveTo": return java.lang.String.class; case "password": return java.lang.String.class; case "peek": return boolean.class; case "replyto": case "replyTo": return java.lang.String.class; case "session": return jakarta.mail.Session.class; case "skipfailedmessage": case "skipFailedMessage": return boolean.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "subject": return java.lang.String.class; case "to": return java.lang.String.class; case "unseen": return boolean.class; case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": return boolean.class; case "useinlineattachments": case "useInlineAttachments": return boolean.class; case "username": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { MailComponent target = (MailComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionaljavamailproperties": case "additionalJavaMailProperties": return getOrCreateConfiguration(target).getAdditionalJavaMailProperties(); case "alternativebodyheader": case "alternativeBodyHeader": return getOrCreateConfiguration(target).getAlternativeBodyHeader(); case "attachmentscontenttransferencodingresolver": case "attachmentsContentTransferEncodingResolver": return getOrCreateConfiguration(target).getAttachmentsContentTransferEncodingResolver(); case "authenticator": return getOrCreateConfiguration(target).getAuthenticator(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bcc": return getOrCreateConfiguration(target).getBcc(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "cc": return getOrCreateConfiguration(target).getCc(); case "closefolder": case "closeFolder": return getOrCreateConfiguration(target).isCloseFolder(); case "configuration": return target.getConfiguration(); case "connectiontimeout": case "connectionTimeout": return getOrCreateConfiguration(target).getConnectionTimeout(); case "contenttype": case "contentType": return getOrCreateConfiguration(target).getContentType(); case "contenttyperesolver": case "contentTypeResolver": return target.getContentTypeResolver(); case "copyto": case "copyTo": return getOrCreateConfiguration(target).getCopyTo(); case "debugmode": case "debugMode": return getOrCreateConfiguration(target).isDebugMode(); case "decodefilename": case "decodeFilename": return getOrCreateConfiguration(target).isDecodeFilename(); case "delete": return getOrCreateConfiguration(target).isDelete(); case "disconnect": return getOrCreateConfiguration(target).isDisconnect(); case "failonduplicatefileattachment": case "failOnDuplicateFileAttachment": return getOrCreateConfiguration(target).isFailOnDuplicateFileAttachment(); case "fetchsize": case "fetchSize": return getOrCreateConfiguration(target).getFetchSize(); case "foldername": case "folderName": return getOrCreateConfiguration(target).getFolderName(); case "from": return getOrCreateConfiguration(target).getFrom(); case "generatemissingattachmentnames": case "generateMissingAttachmentNames": return getOrCreateConfiguration(target).getGenerateMissingAttachmentNames(); case "handleduplicateattachmentnames": case "handleDuplicateAttachmentNames": return getOrCreateConfiguration(target).getHandleDuplicateAttachmentNames(); case "handlefailedmessage": case "handleFailedMessage": return getOrCreateConfiguration(target).isHandleFailedMessage(); case "headerfilterstrategy": case "headerFilterStrategy": return target.getHeaderFilterStrategy(); case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled(); case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled(); case "ignoreunsupportedcharset": case "ignoreUnsupportedCharset": return getOrCreateConfiguration(target).isIgnoreUnsupportedCharset(); case "ignoreurischeme": case "ignoreUriScheme": return getOrCreateConfiguration(target).isIgnoreUriScheme(); case "javamailproperties": case "javaMailProperties": return getOrCreateConfiguration(target).getJavaMailProperties(); case "javamailsender": case "javaMailSender": return getOrCreateConfiguration(target).getJavaMailSender(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "mapmailmessage": case "mapMailMessage": return getOrCreateConfiguration(target).isMapMailMessage(); case "mimedecodeheaders": case "mimeDecodeHeaders": return getOrCreateConfiguration(target).isMimeDecodeHeaders(); case "moveto": case "moveTo": return getOrCreateConfiguration(target).getMoveTo(); case "password": return getOrCreateConfiguration(target).getPassword(); case "peek": return getOrCreateConfiguration(target).isPeek(); case "replyto": case "replyTo": return getOrCreateConfiguration(target).getReplyTo(); case "session": return getOrCreateConfiguration(target).getSession(); case "skipfailedmessage": case "skipFailedMessage": return getOrCreateConfiguration(target).isSkipFailedMessage(); case "sslcontextparameters": case "sslContextParameters": return getOrCreateConfiguration(target).getSslContextParameters(); case "subject": return getOrCreateConfiguration(target).getSubject(); case "to": return getOrCreateConfiguration(target).getTo(); case "unseen": return getOrCreateConfiguration(target).isUnseen(); case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": return target.isUseGlobalSslContextParameters(); case "useinlineattachments": case "useInlineAttachments": return getOrCreateConfiguration(target).isUseInlineAttachments(); case "username": return getOrCreateConfiguration(target).getUsername(); default: return null; } } }
MailComponentConfigurer
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/schema/CatalogSourceTable.java
{ "start": 2864, "end": 8530 }
class ____ extends FlinkPreparingTableBase { private final CatalogSchemaTable schemaTable; public CatalogSourceTable( RelOptSchema relOptSchema, List<String> names, RelDataType rowType, CatalogSchemaTable schemaTable) { super(relOptSchema, rowType, names, schemaTable.getStatistic()); this.schemaTable = schemaTable; } /** * Create a {@link CatalogSourceTable} from an anonymous {@link ContextResolvedTable}. This is * required to manually create a preparing table skipping the calcite catalog resolution. */ public static CatalogSourceTable createAnonymous( FlinkRelBuilder relBuilder, ContextResolvedTable contextResolvedTable, boolean isBatchMode) { Preconditions.checkArgument( contextResolvedTable.isAnonymous(), "ContextResolvedTable must be anonymous"); // Statistics are unknown for anonymous tables // Look at DatabaseCalciteSchema#getStatistic for more details FlinkStatistic flinkStatistic = FlinkStatistic.unknown(contextResolvedTable.getResolvedSchema()).build(); CatalogSchemaTable catalogSchemaTable = new CatalogSchemaTable(contextResolvedTable, flinkStatistic, !isBatchMode); return new CatalogSourceTable( relBuilder.getRelOptSchema(), contextResolvedTable.getIdentifier().toList(), catalogSchemaTable.getRowType(relBuilder.getTypeFactory()), catalogSchemaTable); } @Override public RelNode toRel(ToRelContext toRelContext) { final RelOptCluster cluster = toRelContext.getCluster(); final List<RelHint> hints = toRelContext.getTableHints(); final FlinkContext context = ShortcutUtils.unwrapContext(cluster); final FlinkRelBuilder relBuilder = FlinkRelBuilder.of(cluster, relOptSchema); // finalize catalog table with option hints final Map<String, String> hintedOptions = FlinkHints.getHintedOptions(hints); final ContextResolvedTable contextTableWithHints = computeContextResolvedTable(context, hintedOptions); // create table source final DynamicTableSource tableSource = createDynamicTableSource(context, contextTableWithHints.getResolvedTable()); // prepare table source and convert to RelNode return DynamicSourceUtils.convertSourceToRel( !schemaTable.isStreamingMode(), context.getTableConfig(), relBuilder, contextTableWithHints, schemaTable.getStatistic(), hints, tableSource); } private ContextResolvedTable computeContextResolvedTable( FlinkContext context, Map<String, String> hintedOptions) { ContextResolvedTable contextResolvedTable = schemaTable.getContextResolvedTable(); if (hintedOptions.isEmpty()) { return contextResolvedTable; } if (!context.getTableConfig().get(TableConfigOptions.TABLE_DYNAMIC_TABLE_OPTIONS_ENABLED)) { throw new ValidationException( String.format( "The '%s' hint is allowed only when the config option '%s' is set to true.", FlinkHints.HINT_NAME_OPTIONS, TableConfigOptions.TABLE_DYNAMIC_TABLE_OPTIONS_ENABLED.key())); } if (contextResolvedTable.getResolvedTable().getTableKind() == TableKind.VIEW) { throw new ValidationException( String.format( "View '%s' cannot be enriched with new options. " + "Hints can only be applied to tables.", contextResolvedTable.getIdentifier())); } return contextResolvedTable.copy( FlinkHints.mergeTableOptions( hintedOptions, contextResolvedTable.getResolvedTable().getOptions())); } private DynamicTableSource createDynamicTableSource( FlinkContext context, ResolvedCatalogTable catalogTable) { final Optional<DynamicTableSourceFactory> factoryFromCatalog = schemaTable .getContextResolvedTable() .getCatalog() .flatMap(Catalog::getFactory) .map( f -> f instanceof DynamicTableSourceFactory ? (DynamicTableSourceFactory) f : null); final Optional<DynamicTableSourceFactory> factoryFromModule = context.getModuleManager().getFactory(Module::getTableSourceFactory); // Since the catalog is more specific, we give it precedence over a factory provided by any // modules. final DynamicTableSourceFactory factory = firstPresent(factoryFromCatalog, factoryFromModule).orElse(null); return FactoryUtil.createDynamicTableSource( factory, schemaTable.getContextResolvedTable().getIdentifier(), catalogTable, Collections.emptyMap(), context.getTableConfig(), context.getClassLoader(), schemaTable.isTemporary()); } public CatalogTable getCatalogTable() { return schemaTable.getContextResolvedTable().getResolvedTable(); } }
CatalogSourceTable
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jmx/JmxAutoConfigurationTests.java
{ "start": 4955, "end": 5079 }
class ____ { @Bean Counter counter() { return new Counter(); } } @ManagedResource public static
TestConfiguration
java
apache__logging-log4j2
log4j-api-test/src/test/java/org/apache/logging/log4j/message/JsonMessage.java
{ "start": 1066, "end": 1991 }
class ____ implements Message { private static final long serialVersionUID = 1L; private static final ObjectMapper mapper = new ObjectMapper(); private final Object object; /** * Constructs a JsonMessage. * * @param object the Object to serialize. */ public JsonMessage(final Object object) { this.object = object; } @Override public String getFormattedMessage() { try { return mapper.writeValueAsString(object); } catch (final JsonProcessingException e) { StatusLogger.getLogger().catching(e); return object.toString(); } } @Override public String getFormat() { return object.toString(); } @Override public Object[] getParameters() { return new Object[] {object}; } @Override public Throwable getThrowable() { return null; } }
JsonMessage
java
quarkusio__quarkus
extensions/devservices/mysql/src/main/java/io/quarkus/devservices/mysql/deployment/MySQLDatasourceServiceConfigurator.java
{ "start": 742, "end": 2193 }
class ____ implements DatasourceServiceConfigurator { private final static String[] USERNAME_ENVS = new String[] { "MYSQL_USER" }; private final static String[] PASSWORD_ENVS = new String[] { "MYSQL_PASSWORD" }; private final static String[] DATABASE_ENVS = new String[] { "MYSQL_DATABASE" }; public RunningDevServicesDatasource composeRunningService(ContainerAddress containerAddress, DevServicesDatasourceContainerConfig containerConfig) { RunningContainer container = containerAddress.getRunningContainer(); String effectiveDbName = containerConfig.getDbName().orElse(DEFAULT_DATABASE_NAME); String effectiveUsername = containerConfig.getDbName().orElse(DEFAULT_DATABASE_USERNAME); String effectivePassword = containerConfig.getDbName().orElse(DEFAULT_DATABASE_PASSWORD); String jdbcUrl = getJdbcUrl(containerAddress, container.tryGetEnv(DATABASE_ENVS).orElse(effectiveDbName)); String reactiveUrl = getReactiveUrl(jdbcUrl); return new RunningDevServicesDatasource( containerAddress.getId(), jdbcUrl, reactiveUrl, container.tryGetEnv(USERNAME_ENVS).orElse(effectiveUsername), container.tryGetEnv(PASSWORD_ENVS).orElse(effectivePassword), null); } @Override public String getJdbcPrefix() { return "mysql"; } }
MySQLDatasourceServiceConfigurator
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/view/script/JRubyScriptTemplateTests.java
{ "start": 1433, "end": 2698 }
class ____ { @Test void renderTemplate() throws Exception { Map<String, Object> model = Map.of( "title", "Layout example", "body", "This is the body" ); String url = "org/springframework/web/reactive/result/view/script/jruby/template.erb"; MockServerHttpResponse response = renderViewWithModel(url, model); assertThat(response.getBodyAsString().block()) .isEqualTo("<html><head><title>Layout example</title></head><body><p>This is the body</p></body></html>"); } private static MockServerHttpResponse renderViewWithModel(String viewUrl, Map<String, Object> model) throws Exception { ScriptTemplateView view = createViewWithUrl(viewUrl); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); view.renderInternal(model, MediaType.TEXT_HTML, exchange).block(); return exchange.getResponse(); } private static ScriptTemplateView createViewWithUrl(String viewUrl) throws Exception { ApplicationContext ctx = new AnnotationConfigApplicationContext(ScriptTemplatingConfiguration.class); ScriptTemplateView view = new ScriptTemplateView(); view.setApplicationContext(ctx); view.setUrl(viewUrl); view.afterPropertiesSet(); return view; } @Configuration static
JRubyScriptTemplateTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingUnicode_create_Test.java
{ "start": 1255, "end": 2190 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeEqualNormalizingUnicode("\u00C4", "\u0041", "Ä", "A"); // WHEN String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting actual:%n" + " \"\u00C4\"%n" + "to be equal to:%n" + " \"\u0041\"%n" + "after they have been normalized according to the Normalizer.Form.NFC form.%n" + "The normalized strings should be equal.%n" + "Normalized actual : \"Ä\"%n" + "Normalized expected: \"A\"")); } }
ShouldBeEqualNormalizingUnicode_create_Test
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/DefaultStateTransitionManager.java
{ "start": 9034, "end": 10338 }
class ____ extends Phase { @Nullable private Temporal firstChangeEventTimestamp; private Cooldown( Temporal timeOfLastRescale, Supplier<Temporal> clock, DefaultStateTransitionManager context, Duration cooldownTimeout) { super(clock, context); this.scheduleRelativelyTo(this::finalizeCooldown, timeOfLastRescale, cooldownTimeout); } @Override void onChange() { if (hasSufficientResources() && firstChangeEventTimestamp == null) { firstChangeEventTimestamp = now(); } } private void finalizeCooldown() { if (firstChangeEventTimestamp == null) { context().progressToIdling(); } else { context().progressToStabilizing(firstChangeEventTimestamp); } } } /** * {@link Phase} which follows the {@link Cooldown} phase if no {@link * StateTransitionManager#onChange()} was observed, yet. The {@code * DefaultStateTransitionManager} waits for a first {@link StateTransitionManager#onChange()} * event. {@link StateTransitionManager#onTrigger()} events will be ignored. */ @VisibleForTesting static final
Cooldown
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/support/replication/ReplicationOperation.java
{ "start": 31529, "end": 31991 }
class ____ extends ElasticsearchException { public RetryOnPrimaryException(ShardId shardId, String msg) { this(shardId, msg, null); } RetryOnPrimaryException(ShardId shardId, String msg, Throwable cause) { super(msg, cause); setShard(shardId); } public RetryOnPrimaryException(StreamInput in) throws IOException { super(in); } } public
RetryOnPrimaryException
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/customtype/ObjectUserType.java
{ "start": 516, "end": 653 }
class ____ and the second one * containing binary data. * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public
name
java
quarkusio__quarkus
integration-tests/openapi/src/main/java/io/quarkus/it/openapi/jaxrs/IntegerResource.java
{ "start": 490, "end": 3167 }
class ____ { @GET @Path("/justInteger") public Integer justInteger() { return 0; } @POST @Path("/justInteger") public Integer justInteger(Integer body) { return body; } @GET @Path("/justInt") public int justInt() { return 0; } @POST @Path("/justInt") public int justInt(int body) { return body; } @GET @Path("/restResponseInteger") public RestResponse<Integer> restResponseInteger() { return RestResponse.ok(0); } @POST @Path("/restResponseInteger") public RestResponse<Integer> restResponseInteger(Integer body) { return RestResponse.ok(body); } @GET @Path("/optionalInteger") public Optional<Integer> optionalInteger() { return Optional.of(0); } @POST @Path("/optionalInteger") public Optional<Integer> optionalInteger(Optional<Integer> body) { return body; } @GET @Path("/optionalInt") public OptionalInt optionalInt() { return OptionalInt.of(0); } @POST @Path("/optionalInt") public OptionalInt optionalInt(OptionalInt body) { return body; } @GET @Path("/uniInteger") public Uni<Integer> uniInteger() { return Uni.createFrom().item(0); } @GET @Path("/completionStageInteger") public CompletionStage<Integer> completionStageInteger() { return CompletableFuture.completedStage(0); } @GET @Path("/completedFutureInteger") public CompletableFuture<Integer> completedFutureInteger() { return CompletableFuture.completedFuture(0); } @GET @Path("/listInteger") public List<Integer> listInteger() { return Arrays.asList(new Integer[] { 0 }); } @POST @Path("/listInteger") public List<Integer> listInteger(List<Integer> body) { return body; } @GET @Path("/arrayInteger") public Integer[] arrayInteger() { return new Integer[] { 0 }; } @POST @Path("/arrayInteger") public Integer[] arrayInteger(Integer[] body) { return body; } @GET @Path("/arrayInt") public int[] arrayInt() { return new int[] { 0 }; } @POST @Path("/arrayInt") public int[] arrayInt(int[] body) { return body; } @GET @Path("/mapInteger") public Map<Integer, Integer> mapInteger() { Map<Integer, Integer> m = new HashMap<>(); m.put(0, 0); return m; } @POST @Path("/mapInteger") public Map<Integer, Integer> mapInteger(Map<Integer, Integer> body) { return body; } }
IntegerResource
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/jakarta/JakartaXmlSmokeTests.java
{ "start": 1284, "end": 3242 }
class ____ { @Test public void testLoadingOrmXml(ServiceRegistryScope scope) { final ClassLoaderService cls = scope.getRegistry().getService( ClassLoaderService.class ); final MappingBinder mappingBinder = new MappingBinder( cls, MappingBinder.VALIDATING ); final InputStream inputStream = cls.locateResourceStream( "xml/jakarta/simple/orm.xml" ); try { final Binding<JaxbEntityMappingsImpl> binding = mappingBinder.bind( new StreamSource( inputStream ), new Origin( SourceType.RESOURCE, "xml/jakarta/simple/orm.xml" ) ); assertThat( binding.getRoot() .getEntities() .stream() .map( JaxbEntityImpl::getClazz ) ).containsOnly( "Lighter", "ApplicationServer" ); final JaxbPersistenceUnitMetadataImpl puMetadata = binding.getRoot().getPersistenceUnitMetadata(); final JaxbPersistenceUnitDefaultsImpl puDefaults = puMetadata.getPersistenceUnitDefaults(); final Stream<String> listenerNames = puDefaults.getEntityListenerContainer() .getEntityListeners() .stream() .map( JaxbEntityListenerImpl::getClazz ); assertThat( listenerNames ).containsOnly( "org.hibernate.jpa.test.pack.defaultpar.IncrementListener" ); } finally { try { inputStream.close(); } catch (IOException ignore) { } } } @Test public void testLoadingPersistenceXml(ServiceRegistryScope scope) { final ClassLoaderService cls = scope.getRegistry().getService( ClassLoaderService.class ); final Map<String, PersistenceUnitDescriptor> descriptors = PersistenceXmlParser.create() .parse( cls.locateResources( "xml/jakarta/simple/persistence.xml" ) ); String expectedPuName = "defaultpar"; assertThat( descriptors ).containsOnlyKeys( expectedPuName ); var descriptor = descriptors.get( expectedPuName ); assertThat( descriptor.getName() ).isEqualTo( expectedPuName ); assertThat( descriptor.getManagedClassNames() ).contains( "org.hibernate.jpa.test.pack.defaultpar.Lighter" ); } }
JakartaXmlSmokeTests
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/web/router/routematch/RouteMatchTest.java
{ "start": 833, "end": 1224 }
class ____ { @Test void testRouteMatchRetrieval(@Client("/")HttpClient httpClient) { BlockingHttpClient client = httpClient.toBlocking(); assertEquals("text/plain", client.retrieve(HttpRequest.GET("/routeMatch").accept(MediaType.TEXT_PLAIN), String.class)); } @Requires(property = "spec.name", value = "RouteMatchSpec") @Controller static
RouteMatchTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/JsonValueSerializationTest.java
{ "start": 5000, "end": 5330 }
class ____ { @JsonValue public List<Elem1806> getThings() { return Collections.singletonList(new Elem1806.Impl()); } } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes(@JsonSubTypes.Type(value = Elem1806.Impl.class, name = "impl"))
Bean1806
java
spring-projects__spring-security
oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/OAuth2TokenIntrospectionClaimAccessorTests.java
{ "start": 1175, "end": 6815 }
class ____ { private final Map<String, Object> claims = new HashMap<>(); private final OAuth2TokenIntrospectionClaimAccessor claimAccessor = (() -> this.claims); @BeforeEach public void setup() { this.claims.clear(); } @Test public void isActiveWhenActiveClaimNotExistingThenReturnFalse() { assertThat(this.claimAccessor.isActive()).isFalse(); } @Test public void isActiveWhenActiveClaimValueIsNullThenThrowsNullPointerException() { this.claims.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, null); assertThatNullPointerException().isThrownBy(this.claimAccessor::isActive); } @Test public void isActiveWhenActiveClaimValueIsTrueThenReturnTrue() { this.claims.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, "true"); assertThat(this.claimAccessor.isActive()).isTrue(); } @Test public void getUsernameWhenUsernameClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getUsername()).isNull(); } @Test public void getUsernameWhenUsernameClaimExistingThenReturnUsername() { String expectedUsernameValue = "username"; this.claims.put(OAuth2TokenIntrospectionClaimNames.USERNAME, expectedUsernameValue); assertThat(this.claimAccessor.getUsername()).isEqualTo(expectedUsernameValue); } @Test public void getClientIdWhenClientIdClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getUsername()).isNull(); } @Test public void getClientIdWhenClientIdClaimExistingThenReturnClientId() { String expectedClientIdValue = "clientId"; this.claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, expectedClientIdValue); assertThat(this.claimAccessor.getClientId()).isEqualTo(expectedClientIdValue); } @Test public void getScopesWhenScopeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getScopes()).isNull(); } @Test public void getScopesWhenScopeClaimExistingThenReturnScope() { List<String> expectedScopeValue = Arrays.asList("scope1", "scope2"); this.claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, expectedScopeValue); assertThat(this.claimAccessor.getScopes()).hasSameElementsAs(expectedScopeValue); } @Test public void getTokenTypeWhenTokenTypeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getTokenType()).isNull(); } @Test public void getTokenTypeWhenTokenTypeClaimExistingThenReturnTokenType() { String expectedTokenTypeValue = "tokenType"; this.claims.put(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE, expectedTokenTypeValue); assertThat(this.claimAccessor.getTokenType()).isEqualTo(expectedTokenTypeValue); } @Test public void getExpiresAtWhenExpiresAtClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getExpiresAt()).isNull(); } @Test public void getExpiresAtWhenExpiresAtClaimExistingThenReturnExpiresAt() { Instant expectedExpiresAtValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.EXP, expectedExpiresAtValue); assertThat(this.claimAccessor.getExpiresAt()).isEqualTo(expectedExpiresAtValue); } @Test public void getIssuedAtWhenIssuedAtClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getExpiresAt()).isNull(); } @Test public void getIssuedAtWhenIssuedAtClaimExistingThenReturnIssuedAt() { Instant expectedIssuedAtValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.IAT, expectedIssuedAtValue); assertThat(this.claimAccessor.getIssuedAt()).isEqualTo(expectedIssuedAtValue); } @Test public void getNotBeforeWhenNotBeforeClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getNotBefore()).isNull(); } @Test public void getNotBeforeWhenNotBeforeClaimExistingThenReturnNotBefore() { Instant expectedNotBeforeValue = Instant.now(); this.claims.put(OAuth2TokenIntrospectionClaimNames.NBF, expectedNotBeforeValue); assertThat(this.claimAccessor.getNotBefore()).isEqualTo(expectedNotBeforeValue); } @Test public void getSubjectWhenSubjectClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getSubject()).isNull(); } @Test public void getSubjectWhenSubjectClaimExistingThenReturnSubject() { String expectedSubjectValue = "subject"; this.claims.put(OAuth2TokenIntrospectionClaimNames.SUB, expectedSubjectValue); assertThat(this.claimAccessor.getSubject()).isEqualTo(expectedSubjectValue); } @Test public void getAudienceWhenAudienceClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getAudience()).isNull(); } @Test public void getAudienceWhenAudienceClaimExistingThenReturnAudience() { List<String> expectedAudienceValue = Arrays.asList("audience1", "audience2"); this.claims.put(OAuth2TokenIntrospectionClaimNames.AUD, expectedAudienceValue); assertThat(this.claimAccessor.getAudience()).hasSameElementsAs(expectedAudienceValue); } @Test public void getIssuerWhenIssuerClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getIssuer()).isNull(); } @Test public void getIssuerWhenIssuerClaimExistingThenReturnIssuer() throws MalformedURLException { URL expectedIssuerValue = new URL("https://issuer.com"); this.claims.put(OAuth2TokenIntrospectionClaimNames.ISS, expectedIssuerValue); assertThat(this.claimAccessor.getIssuer()).isEqualTo(expectedIssuerValue); } @Test public void getIdWhenJtiClaimNotExistingThenReturnNull() { assertThat(this.claimAccessor.getId()).isNull(); } @Test public void getIdWhenJtiClaimExistingThenReturnId() { String expectedIdValue = "id"; this.claims.put(OAuth2TokenIntrospectionClaimNames.JTI, expectedIdValue); assertThat(this.claimAccessor.getId()).isEqualTo(expectedIdValue); } }
OAuth2TokenIntrospectionClaimAccessorTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/ActionRunnable.java
{ "start": 1004, "end": 5880 }
class ____<Response> extends AbstractRunnable { protected final ActionListener<Response> listener; /** * Creates a {@link Runnable} that invokes the given listener with {@code null} after the given runnable has executed. * @param listener Listener to invoke * @param runnable Runnable to execute * @return Wrapped {@code Runnable} */ public static <T> ActionRunnable<T> run(ActionListener<T> listener, CheckedRunnable<Exception> runnable) { return new ActionRunnable<>(listener) { @Override protected void doRun() throws Exception { runnable.run(); listener.onResponse(null); } @Override public String toString() { return runnable.toString(); } }; } /** * Creates a {@link Runnable} that invokes the given listener with the return of the given supplier. * @param listener Listener to invoke * @param supplier Supplier that provides value to pass to listener * @return Wrapped {@code Runnable} */ public static <T> ActionRunnable<T> supply(ActionListener<T> listener, CheckedSupplier<T, Exception> supplier) { return ActionRunnable.wrap(listener, new CheckedConsumer<>() { @Override public void accept(ActionListener<T> l) throws Exception { l.onResponse(supplier.get()); } @Override public String toString() { return supplier.toString(); } }); } /** * Same as {@link #supply(ActionListener, CheckedSupplier)} but the supplier always returns an object of reference counted result type * which will have its reference count decremented after invoking the listener. */ public static <T extends RefCounted> ActionRunnable<T> supplyAndDecRef( ActionListener<T> listener, CheckedSupplier<T, Exception> supplier ) { return wrap(listener, new CheckedConsumer<>() { @Override public void accept(ActionListener<T> l) throws Exception { ActionListener.respondAndRelease(l, supplier.get()); } @Override public String toString() { return supplier.toString(); } }); } /** * Creates a {@link Runnable} that wraps the given listener and a consumer of it that is executed when the {@link Runnable} is run. * Invokes {@link ActionListener#onFailure(Exception)} on it if an exception is thrown on executing the consumer. * @param listener ActionListener to wrap * @param consumer Consumer of wrapped {@code ActionListener} * @param <T> Type of the given {@code ActionListener} * @return Wrapped {@code Runnable} */ public static <T> ActionRunnable<T> wrap(ActionListener<T> listener, CheckedConsumer<ActionListener<T>, Exception> consumer) { return new ActionRunnable<>(listener) { @Override protected void doRun() throws Exception { consumer.accept(listener); } @Override public String toString() { return "ActionRunnable#wrap[" + consumer + "]"; } }; } /** * Like {#wrap} except with a {@link Releasable} which is released after executing the consumer, or if the action is rejected. This is * particularly useful for submitting actions holding resources to a threadpool which might have a bounded queue. */ public static <T> ActionRunnable<T> wrapReleasing( ActionListener<T> listener, Releasable releasable, CheckedConsumer<ActionListener<T>, Exception> consumer ) { return new ActionRunnable<>(listener) { @Override protected void doRun() { try (releasable) { ActionListener.run(listener, consumer); } } @Override public void onFailure(Exception e) { try (releasable) { super.onFailure(e); } } @Override public String toString() { return "ActionRunnable#wrapReleasing[" + consumer + "]"; } }; } public ActionRunnable(ActionListener<Response> listener) { this.listener = listener; } /** * Calls the action listeners {@link ActionListener#onFailure(Exception)} method with the given exception. * This method is invoked for all exception thrown by {@link #doRun()} */ @Override public void onFailure(Exception e) { listener.onFailure(e); } @Override public String toString() { return getClass().getName() + "/" + listener; } }
ActionRunnable
java
apache__camel
components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvUnmarshalCommentMarkerSpringTest.java
{ "start": 1285, "end": 2446 }
class ____ extends CamelSpringTestSupport { @EndpointInject("mock:result") private MockEndpoint result; @SuppressWarnings("unchecked") @Test void testCsvUnmarshal() throws Exception { result.expectedMessageCount(1); template.sendBody("direct:start", "# Cool books list (comment)\n123|Camel in Action|1\n124|ActiveMQ in Action|2"); MockEndpoint.assertIsSatisfied(context); List<List<String>> body = result.getReceivedExchanges().get(0).getIn().getBody(List.class); assertEquals(2, body.size()); assertEquals("123", body.get(0).get(0)); assertEquals("Camel in Action", body.get(0).get(1)); assertEquals("1", body.get(0).get(2)); assertEquals("124", body.get(1).get(0)); assertEquals("ActiveMQ in Action", body.get(1).get(1)); assertEquals("2", body.get(1).get(2)); } @Override protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/dataformat/csv/CsvUnmarshalCommentMarkerSpringTest-context.xml"); } }
CsvUnmarshalCommentMarkerSpringTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EmbeddableWithPluralAttributeTest.java
{ "start": 1863, "end": 1950 }
class ____ { @Id private Integer id; private B b; } @Embeddable public static
A
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/BuildProfileTest.java
{ "start": 3513, "end": 3780 }
class ____ { @GET @Path("ok") public String ok() { return "ok2"; } } @IfBuildProperty(name = "some.prop1", stringValue = "v1") // will be enabled because the value matches @Provider public static
ResourceTest2
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/protocolrecords/GetTaskReportsRequest.java
{ "start": 994, "end": 1215 }
interface ____ { public abstract JobId getJobId(); public abstract TaskType getTaskType(); public abstract void setJobId(JobId jobId); public abstract void setTaskType(TaskType taskType); }
GetTaskReportsRequest
java
google__dagger
javatests/dagger/hilt/android/AndroidEntryPointBaseClassTest.java
{ "start": 3301, "end": 3398 }
class ____ extends Hilt_AndroidEntryPointBaseClassTest_LS {} @AndroidEntryPoint public static
LS