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
quarkusio__quarkus
extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/runtime/telemetry/TracesConnectionInterceptor.java
{ "start": 239, "end": 1228 }
class ____ implements ConnectionInterceptor { private final WebSocketTracesInterceptor tracesInterceptor; private final String path; private final EndpointKind endpointKind; private volatile Map<String, Object> contextData; TracesConnectionInterceptor(WebSocketTracesInterceptor tracesInterceptor, String path, EndpointKind endpointKind) { this.tracesInterceptor = tracesInterceptor; this.path = path; this.endpointKind = endpointKind; this.contextData = null; } @Override public void connectionOpened() { contextData = tracesInterceptor.onConnectionOpened(path, endpointKind); } @Override public void connectionOpeningFailed(Throwable cause) { tracesInterceptor.onConnectionOpeningFailed(cause, path, endpointKind, contextData); } @Override public Map<String, Object> getContextData() { return contextData == null ? Map.of() : contextData; } }
TracesConnectionInterceptor
java
quarkusio__quarkus
test-framework/common/src/main/java/io/quarkus/test/common/PathTestHelper.java
{ "start": 1124, "end": 7421 }
class ____ { private static final String TARGET = "target"; private static final Map<String, String> TEST_TO_MAIN_DIR_FRAGMENTS = new HashMap<>(); private static final List<String> TEST_DIRS; static { //region Eclipse TEST_TO_MAIN_DIR_FRAGMENTS.put( "bin" + File.separator + "test", "bin" + File.separator + "main"); //endregion //region Idea TEST_TO_MAIN_DIR_FRAGMENTS.put( "out" + File.separator + "test", "out" + File.separator + "production"); //endregion // region Gradle // region Java TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "native-test", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "test", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "integration-test", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "integrationTest", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "native-integrationTest", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "java" + File.separator + "native-integration-test", "classes" + File.separator + "java" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( //synthetic tmp dirs when there are multiple outputs "quarkus-app-classes-test", "quarkus-app-classes"); //endregion //region Kotlin TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "native-test", "classes" + File.separator + "kotlin" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "test", "classes" + File.separator + "kotlin" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "integration-test", "classes" + File.separator + "kotlin" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "integrationTest", "classes" + File.separator + "kotlin" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "native-integrationTest", "classes" + File.separator + "kotlin" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "kotlin" + File.separator + "native-integration-test", "classes" + File.separator + "kotlin" + File.separator + "main"); //endregion //region Scala TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "native-test", "classes" + File.separator + "scala" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "test", "classes" + File.separator + "scala" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "integration-test", "classes" + File.separator + "scala" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "integrationTest", "classes" + File.separator + "scala" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "native-integrationTest", "classes" + File.separator + "scala" + File.separator + "main"); TEST_TO_MAIN_DIR_FRAGMENTS.put( "classes" + File.separator + "scala" + File.separator + "native-integration-test", "classes" + File.separator + "scala" + File.separator + "main"); //endregion //endregion //region Maven TEST_TO_MAIN_DIR_FRAGMENTS.put( File.separator + "test-classes", File.separator + "classes"); //endregion String mappings = System.getenv(BootstrapConstants.TEST_TO_MAIN_MAPPINGS); if (mappings != null) { Stream.of(mappings.split(",")) .filter(s -> !s.isEmpty()) .forEach(s -> { String[] entry = s.split(":"); if (entry.length == 2) { TEST_TO_MAIN_DIR_FRAGMENTS.put(entry[0], entry[1]); } else { throw new IllegalStateException("Unable to parse additional test-to-main mapping: " + s); } }); } TEST_DIRS = List.of(TEST_TO_MAIN_DIR_FRAGMENTS.keySet().toArray(new String[0])); } private PathTestHelper() { } /** * Resolves the directory or the JAR file containing the test class. * * @param testClass the test class * @return directory or JAR containing the test class */ public static Path getTestClassesLocation(Class<?> testClass) { final String classFileName = fromClassNameToResourceName(testClass.getName()); URL resource = testClass.getClassLoader().getResource(classFileName); if (resource == null) { throw new IllegalStateException( "Could not find resource " + classFileName + " using
PathTestHelper
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/TokenPBImpl.java
{ "start": 1303, "end": 5220 }
class ____ extends Token { private TokenProto proto = TokenProto.getDefaultInstance(); private TokenProto.Builder builder = null; private boolean viaProto = false; private ByteBuffer identifier; private ByteBuffer password; public TokenPBImpl() { builder = TokenProto.newBuilder(); } public TokenPBImpl(TokenProto proto) { this.proto = proto; viaProto = true; } public synchronized TokenProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } protected final ByteBuffer convertFromProtoFormat(ByteString byteString) { return ProtoUtils.convertFromProtoFormat(byteString); } protected final ByteString convertToProtoFormat(ByteBuffer byteBuffer) { return ProtoUtils.convertToProtoFormat(byteBuffer); } private synchronized void mergeLocalToBuilder() { if (this.identifier != null) { builder.setIdentifier(convertToProtoFormat(this.identifier)); } if (this.password != null) { builder.setPassword(convertToProtoFormat(this.password)); } } private synchronized void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private synchronized void maybeInitBuilder() { if (viaProto || builder == null) { builder = TokenProto.newBuilder(proto); } viaProto = false; } @Override public synchronized ByteBuffer getIdentifier() { TokenProtoOrBuilder p = viaProto ? proto : builder; if (this.identifier != null) { return this.identifier; } if (!p.hasIdentifier()) { return null; } this.identifier = convertFromProtoFormat(p.getIdentifier()); return this.identifier; } @Override public synchronized void setIdentifier(ByteBuffer identifier) { maybeInitBuilder(); if (identifier == null) builder.clearIdentifier(); this.identifier = identifier; } @Override public synchronized ByteBuffer getPassword() { TokenProtoOrBuilder p = viaProto ? proto : builder; if (this.password != null) { return this.password; } if (!p.hasPassword()) { return null; } this.password = convertFromProtoFormat(p.getPassword()); return this.password; } @Override public synchronized void setPassword(ByteBuffer password) { maybeInitBuilder(); if (password == null) builder.clearPassword(); this.password = password; } @Override public synchronized String getKind() { TokenProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasKind()) { return null; } return (p.getKind()); } @Override public synchronized void setKind(String kind) { maybeInitBuilder(); if (kind == null) { builder.clearKind(); return; } builder.setKind((kind)); } @Override public synchronized String getService() { TokenProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasService()) { return null; } return (p.getService()); } @Override public synchronized void setService(String service) { maybeInitBuilder(); if (service == null) { builder.clearService(); return; } builder.setService((service)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Token { ") .append("kind: ").append(getKind()).append(", ") .append("service: ").append(getService()).append(" }"); return sb.toString(); } }
TokenPBImpl
java
apache__hadoop
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/NFS3Response.java
{ "start": 1037, "end": 1118 }
class ____ its subclasses contain * the response from NFSv3 handlers. */ public
and
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/ConnectionPoolSizeTest.java
{ "start": 3906, "end": 4187 }
class ____ { @Inject Vertx vertx; @GET public Uni<String> getSlowly() { return Uni.createFrom().emitter(emitter -> vertx.setTimer(1000 /* ms */, val -> emitter.complete("hello, world!"))); } } }
SlowResource
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/util/PageParams.java
{ "start": 860, "end": 3563 }
class ____ implements ToXContentObject, Writeable { public static final ParseField PAGE = new ParseField("page"); public static final ParseField FROM = new ParseField("from"); public static final ParseField SIZE = new ParseField("size"); public static final int DEFAULT_FROM = 0; public static final int DEFAULT_SIZE = 100; public static final ConstructingObjectParser<PageParams, Void> PARSER = new ConstructingObjectParser<>( PAGE.getPreferredName(), a -> new PageParams(a[0] == null ? DEFAULT_FROM : (int) a[0], a[1] == null ? DEFAULT_SIZE : (int) a[1]) ); static { PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), FROM); PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), SIZE); } private final int from; private final int size; public static PageParams defaultParams() { return new PageParams(DEFAULT_FROM, DEFAULT_SIZE); } public PageParams(StreamInput in) throws IOException { this(in.readVInt(), in.readVInt()); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(from); out.writeVInt(size); } public PageParams() { this.from = DEFAULT_FROM; this.size = DEFAULT_SIZE; } public PageParams(int from, int size) { if (from < 0) { throw new IllegalArgumentException("Parameter [" + FROM.getPreferredName() + "] cannot be < 0"); } if (size < 0) { throw new IllegalArgumentException("Parameter [" + PageParams.SIZE.getPreferredName() + "] cannot be < 0"); } this.from = from; this.size = size; } public int getFrom() { return from; } public int getSize() { return size; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FROM.getPreferredName(), from); builder.field(SIZE.getPreferredName(), size); builder.endObject(); return builder; } @Override public int hashCode() { return Objects.hash(from, size); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PageParams other = (PageParams) obj; return Objects.equals(from, other.from) && Objects.equals(size, other.size); } public static PageParams fromXContent(XContentParser contentParser) { return PARSER.apply(contentParser, null); } }
PageParams
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RMapCacheReactive.java
{ "start": 1910, "end": 18618 }
interface ____<K, V> extends RMapReactive<K, V>, RDestroyable { /** * Sets max size of the map. * Superfluous elements are evicted using LRU algorithm. * * @param maxSize - max size * @return void */ Mono<Void> setMaxSize(int maxSize); /** * Sets max size of the map and overrides current value. * Superfluous elements are evicted using defined algorithm. * * @param maxSize - max size * @param mode - eviction mode */ Mono<Void> setMaxSize(int maxSize, EvictionMode mode); /** * Tries to set max size of the map. * Superfluous elements are evicted using LRU algorithm. * * @param maxSize - max size * @return <code>true</code> if max size has been successfully set, otherwise <code>false</code>. */ Mono<Boolean> trySetMaxSize(int maxSize); /** * Tries to set max size of the map. * Superfluous elements are evicted using defined algorithm. * * @param maxSize - max size * @param mode - eviction mode * @return <code>true</code> if max size has been successfully set, otherwise <code>false</code>. */ Mono<Boolean> trySetMaxSize(int maxSize, EvictionMode mode); /** * If the specified key is not already associated * with a value, associate it with the given value. * <p> * Stores value mapped by key with specified time to live. * Entry expires after specified time to live. * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then stores infinitely. * @param unit - time unit * @return previous associated value */ Mono<V> putIfAbsent(K key, V value, long ttl, TimeUnit unit); /** * If the specified key is not already associated * with a value, associate it with the given value. * <p> * Stores value mapped by key with specified time to live and max idle time. * Entry expires when specified time to live or max idle time has expired. * <p> * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param ttlUnit - time unit * @param maxIdleTime - max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * @param maxIdleUnit - time unit * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return previous associated value */ Mono<V> putIfAbsent(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit); /** * If the specified key is not already associated * with a value, attempts to compute its value using the given mapping function and enters it into this map . * <p> * Stores value mapped by key with specified time to live. * Entry expires after specified time to live. * * @param key - map key * @param ttl - time to live for key\value entry. * If <code>0</code> then stores infinitely. * @param mappingFunction the mapping function to compute a value * @return current associated value */ Mono<V> computeIfAbsent(K key, Duration ttl, Function<? super K, ? extends V> mappingFunction); /** * Computes a new mapping for the specified key and its current mapped value. * <p> * Stores value mapped by key with specified time to live. * Entry expires after specified time to live. * * @param key - map key * @param ttl - time to live for key\value entry. * If <code>0</code> then stores infinitely. * @param remappingFunction - function to compute a value * @return the new value associated with the specified key, or {@code null} if none */ Mono<V> compute(K key, Duration ttl, BiFunction<? super K, ? super V, ? extends V> remappingFunction); /** * Stores value mapped by key with specified time to live. * Entry expires after specified time to live. * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then stores infinitely. * @param unit - time unit * @return previous associated value */ Mono<V> put(K key, V value, long ttl, TimeUnit unit); /** * Stores value mapped by key with specified time to live and max idle time. * Entry expires when specified time to live or max idle time has expired. * <p> * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param ttlUnit - time unit * @param maxIdleTime - max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * @param maxIdleUnit - time unit * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return previous associated value */ Mono<V> put(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit); /** * Associates the specified <code>value</code> with the specified <code>key</code> * in batch. * <p> * If {@link MapWriter} is defined then new map entries will be stored in write-through mode. * * @param map - mappings to be stored in this map * @param ttl - time to live for all key\value entries. * If <code>0</code> then stores infinitely. * @param ttlUnit - time unit */ Mono<Void> putAll(java.util.Map<? extends K, ? extends V> map, long ttl, TimeUnit ttlUnit); /** * Stores value mapped by key with specified time to live. * Entry expires after specified time to live. * <p> * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * <p> * Works faster than usual {@link #put(Object, Object, long, TimeUnit)} * as it not returns previous value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then stores infinitely. * @param unit - time unit * * @return <code>true</code> if key is a new key in the hash and value was set. * <code>false</code> if key already exists in the hash and the value was updated. */ Mono<Boolean> fastPut(K key, V value, long ttl, TimeUnit unit); /** * Stores value mapped by key with specified time to live and max idle time. * Entry expires when specified time to live or max idle time has expired. * <p> * If the map previously contained a mapping for * the key, the old value is replaced by the specified value. * <p> * Works faster than usual {@link #put(Object, Object, long, TimeUnit, long, TimeUnit)} * as it not returns previous value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param ttlUnit - time unit * @param maxIdleTime - max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * @param maxIdleUnit - time unit * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * @return <code>true</code> if key is a new key in the hash and value was set. * <code>false</code> if key already exists in the hash and the value was updated. */ Mono<Boolean> fastPut(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit); /** * If the specified key is not already associated * with a value, associate it with the given value. * <p> * Stores value mapped by key with specified time to live and max idle time. * Entry expires when specified time to live or max idle time has expired. * <p> * Works faster than usual {@link #putIfAbsent(Object, Object, long, TimeUnit, long, TimeUnit)} * as it not returns previous value. * * @param key - map key * @param value - map value * @param ttl - time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param ttlUnit - time unit * @param maxIdleTime - max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * @param maxIdleUnit - time unit * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return <code>true</code> if key is a new key in the hash and value was set. * <code>false</code> if key already exists in the hash */ Mono<Boolean> fastPutIfAbsent(K key, V value, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit); /** * Use {@link #expireEntry(Object, Duration, Duration)} instead. * * @param key - map key * @param ttl - time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param ttlUnit - time unit * @param maxIdleTime - max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * @param maxIdleUnit - time unit * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return returns <code>false</code> if entry already expired or doesn't exist, * otherwise returns <code>true</code>. */ @Deprecated Mono<Boolean> updateEntryExpiration(K key, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit); /** * Updates time to live and max idle time of specified entry by key. * Entry expires when specified time to live or max idle time was reached. * <p> * Returns <code>false</code> if entry already expired or doesn't exist, * otherwise returns <code>true</code>. * * @param key map key * @param ttl time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param maxIdleTime max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return returns <code>false</code> if entry already expired or doesn't exist, * otherwise returns <code>true</code>. */ Mono<Boolean> expireEntry(K key, Duration ttl, Duration maxIdleTime); /** * Updates time to live and max idle time of specified entries by keys. * Entries expires when specified time to live or max idle time was reached. * <p> * Returns amount of updated entries. * * @param keys map keys * @param ttl time to live for key\value entries. * If <code>0</code> then time to live doesn't affect entry expiration. * @param maxIdleTime max idle time for key\value entries. * If <code>0</code> then max idle time doesn't affect entry expiration. * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entries are stored infinitely. * * @return amount of updated entries. */ Mono<Integer> expireEntries(Set<K> keys, Duration ttl, Duration maxIdleTime); /** * Sets time to live and max idle time of specified entry by key. * If these parameters weren't set before. * Entry expires when specified time to live or max idle time was reached. * <p> * Returns <code>false</code> if entry already has expiration time or doesn't exist, * otherwise returns <code>true</code>. * * @param key map key * @param ttl time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param maxIdleTime max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return returns <code>false</code> if entry already has expiration time or doesn't exist, * otherwise returns <code>true</code>. */ Mono<Boolean> expireEntryIfNotSet(K key, Duration ttl, Duration maxIdleTime); /** * Sets time to live and max idle time of specified entries by keys. * If these parameters weren't set before. * Entries expire when specified time to live or max idle time was reached. * <p> * Returns amount of updated entries. * * @param keys map keys * @param ttl time to live for key\value entry. * If <code>0</code> then time to live doesn't affect entry expiration. * @param maxIdleTime max idle time for key\value entry. * If <code>0</code> then max idle time doesn't affect entry expiration. * <p> * if <code>maxIdleTime</code> and <code>ttl</code> params are equal to <code>0</code> * then entry stores infinitely. * * @return amount of updated entries. */ Mono<Integer> expireEntriesIfNotSet(Set<K> keys, Duration ttl, Duration maxIdleTime); /** * Returns the value mapped by defined <code>key</code> or {@code null} if value is absent. * <p> * If map doesn't contain value for specified key and {@link MapLoader} is defined * then value will be loaded in read-through mode. * <p> * Idle time of entry is not taken into account. * Entry last access time isn't modified if map limited by size. * * @param key the key * @return the value mapped by defined <code>key</code> or {@code null} if value is absent */ Mono<V> getWithTTLOnly(K key); /** * Returns map slice contained the mappings with defined <code>keys</code>. * <p> * If map doesn't contain value/values for specified key/keys and {@link MapLoader} is defined * then value/values will be loaded in read-through mode. * <p> * NOTE: Idle time of entry is not taken into account. * Entry last access time isn't modified if map limited by size. * * @param keys map keys * @return Map slice */ Mono<Map<K, V>> getAllWithTTLOnly(Set<K> keys); /** * Returns the number of entries in cache. * This number can reflects expired entries too * due to non realtime cleanup process. * */ @Override Mono<Integer> size(); /** * Remaining time to live of map entry associated with a <code>key</code>. * * @param key - map key * @return time in milliseconds * -2 if the key does not exist. * -1 if the key exists but has no associated expire. */ Mono<Long> remainTimeToLive(K key); /** * Adds map entry listener * * @see org.redisson.api.map.event.EntryCreatedListener * @see org.redisson.api.map.event.EntryUpdatedListener * @see org.redisson.api.map.event.EntryRemovedListener * @see org.redisson.api.map.event.EntryExpiredListener * * @param listener - entry listener * @return listener id */ Mono<Integer> addListener(MapEntryListener listener); }
RMapCacheReactive
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/PreDestroyOnTargetClassAndOutsideAndSuperclassesTest.java
{ "start": 827, "end": 1305 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyBean.class, MyInterceptorBinding.class, MyInterceptor.class); @Test public void test() { ArcContainer arc = Arc.container(); arc.instance(MyBean.class).destroy(); assertEquals(List.of("MyInterceptorSuperclass", "MyInterceptor", "MyBeanSuperclass", "MyBean"), MyBean.invocations); } static
PreDestroyOnTargetClassAndOutsideAndSuperclassesTest
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/ReflectUtilsTest.java
{ "start": 21618, "end": 21791 }
class ____ implements Foo<Foo1, Foo2> { public Foo3(Foo foo) {} @Override public Foo1 hello(Foo2 foo2) { return null; } } }
Foo3
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsShellPermissions.java
{ "start": 7848, "end": 8542 }
class ____ extends Chown { public static final String NAME = "chgrp"; public static final String USAGE = "[-R] GROUP PATH..."; public static final String DESCRIPTION = "This is equivalent to -chown ... :GROUP ..."; static private final Pattern chgrpPattern = Pattern.compile("^\\s*(" + allowedChars + "+)\\s*$"); @Override protected void parseOwnerGroup(String groupStr) { Matcher matcher = chgrpPattern.matcher(groupStr); if (!matcher.matches()) { throw new IllegalArgumentException( "'" + groupStr + "' does not match expected pattern for group"); } owner = null; group = matcher.group(1); } } }
Chgrp
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java
{ "start": 19319, "end": 19841 }
class ____ implements AsyncConfigurer { @Bean public AsyncInterface asyncBean() { return new AsyncService(); } @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("Custom-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } } @Configuration @EnableAsync(proxyTargetClass = true) static
Spr14949ConfigA
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThatPath_Test.java
{ "start": 924, "end": 1226 }
class ____ { private Path actual; @BeforeEach void before() { actual = Path.of("."); } @Test void should_create_Assert() { // GIVEN AbstractPathAssert<?> assertions = assertThatPath(actual); // WHEN/THEN then(assertions).isNotNull(); } }
Assertions_assertThatPath_Test
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/domain/sample/AnnotatedAuditableUser.java
{ "start": 773, "end": 842 }
class ____ extends AbstractAnnotatedAuditable { }
AnnotatedAuditableUser
java
mockito__mockito
mockito-core/src/main/java/org/mockito/AdditionalAnswers.java
{ "start": 18582, "end": 19201 }
interface ____ the answer - a void method * @param <A> input parameter type 1 * @param <B> input parameter type 2 * @param <C> input parameter type 3 * @param <D> input parameter type 4 * @param <E> input parameter type 5 * @return the answer object to use * @since 2.1.0 */ public static <A, B, C, D, E> Answer<Void> answerVoid(VoidAnswer5<A, B, C, D, E> answer) { return toAnswer(answer); } /** * Creates an answer from a functional interface - allows for a strongly typed answer to be created * idiomatically in Java 8 * * @param answer
to
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/repository/legacy/resolver/conflict/ConflictResolverFactory.java
{ "start": 1004, "end": 1682 }
interface ____ { // constants -------------------------------------------------------------- /** The plexus role for this component. */ String ROLE = ConflictResolverFactory.class.getName(); // methods ---------------------------------------------------------------- /** * Gets a conflict resolver of the specified type. * * @param type the type of conflict resolver to obtain * @return the conflict resolver * @throws ConflictResolverNotFoundException * if the specified type was not found */ ConflictResolver getConflictResolver(String type) throws ConflictResolverNotFoundException; }
ConflictResolverFactory
java
apache__avro
lang/java/mapred/src/test/java/org/apache/avro/mapreduce/TestKeyValueWordCount.java
{ "start": 2286, "end": 4996 }
class ____ extends Reducer<Text, IntWritable, Text, IntWritable> { @Override protected void reduce(Text word, Iterable<IntWritable> counts, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable count : counts) { sum += count.get(); } context.write(word, new IntWritable(sum)); } } @Test void keyValueMapReduce() throws ClassNotFoundException, IOException, InterruptedException, URISyntaxException { // Configure a word count job over our test input file. Job job = Job.getInstance(); FileInputFormat.setInputPaths(job, new Path(getClass().getResource("/org/apache/avro/mapreduce/mapreduce-test-input.txt").toURI().toString())); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(LineCountMapper.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setOutputFormatClass(AvroKeyValueOutputFormat.class); Path outputPath = new Path(mTempDir.getPath() + "/out-wordcount"); FileOutputFormat.setOutputPath(job, outputPath); // Run the job. assertTrue(job.waitForCompletion(true)); // Verify that the Avro container file generated had the right KeyValuePair // generic records. File avroFile = new File(outputPath.toString(), "part-r-00000.avro"); DatumReader<GenericRecord> datumReader = new SpecificDatumReader<>( AvroKeyValue.getSchema(Schema.create(Schema.Type.STRING), Schema.create(Schema.Type.INT))); DataFileReader<GenericRecord> avroFileReader = new DataFileReader<>(avroFile, datumReader); assertTrue(avroFileReader.hasNext()); AvroKeyValue<CharSequence, Integer> appleRecord = new AvroKeyValue<>(avroFileReader.next()); assertNotNull(appleRecord.get()); assertEquals("apple", appleRecord.getKey().toString()); assertEquals(3, appleRecord.getValue().intValue()); assertTrue(avroFileReader.hasNext()); AvroKeyValue<CharSequence, Integer> bananaRecord = new AvroKeyValue<>(avroFileReader.next()); assertNotNull(bananaRecord.get()); assertEquals("banana", bananaRecord.getKey().toString()); assertEquals(2, bananaRecord.getValue().intValue()); assertTrue(avroFileReader.hasNext()); AvroKeyValue<CharSequence, Integer> carrotRecord = new AvroKeyValue<>(avroFileReader.next()); assertEquals("carrot", carrotRecord.getKey().toString()); assertEquals(1, carrotRecord.getValue().intValue()); assertFalse(avroFileReader.hasNext()); avroFileReader.close(); } }
IntSumReducer
java
quarkusio__quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ValidationPhaseBuildItem.java
{ "start": 1911, "end": 2341 }
class ____ extends MultiBuildItem { private final List<Throwable> values; public ValidationErrorBuildItem(Throwable... values) { this.values = Arrays.asList(values); } public ValidationErrorBuildItem(List<Throwable> values) { this.values = values; } public List<Throwable> getValues() { return values; } } }
ValidationErrorBuildItem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/columndiscriminator/Author.java
{ "start": 175, "end": 662 }
class ____ { private Long id; private String name; private String email; private List<Book> books = new ArrayList<>(); public Author(String name, String email) { this.name = name; this.email = email; } protected Author() { // default } public Long id() { return id; } public String name() { return name; } public String email() { return email; } public List<Book> books() { return books; } public void addBook(Book book) { books.add(book); } }
Author
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
{ "start": 39429, "end": 39984 }
class ____ * not match - see {@link #throwableOfType(Throwable, Class, int)} for the opposite. * * <p> * A {@code null} throwable returns {@code null}. A {@code null} type returns {@code null}. No match in the chain returns {@code null}. A negative start * index is treated as zero. A start index greater than the number of throwables returns {@code null}. * </p> * * @param <T> the type of Throwable you are searching. * @param throwable the throwable to inspect, may be null. * @param clazz the
do
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java
{ "start": 1832, "end": 2090 }
interface ____ the implementation of * an introduction. There is no such distinction between target and proxy in AspectJ itself. * * @author Rod Johnson * @author Juergen Hoeller * @author Adrian Colyer * @author Ramnivas Laddad * @since 2.0 */ public
in
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/row/ParquetRowDataWriter.java
{ "start": 7825, "end": 7970 }
interface ____ { void write(RowData row, int ordinal); void write(ArrayData arrayData, int ordinal); } private
FieldWriter
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/io/FilePermissionsTests.java
{ "start": 1588, "end": 3429 }
class ____ { @TempDir @SuppressWarnings("NullAway.Init") Path tempDir; @Test @DisabledOnOs(OS.WINDOWS) void umaskForPath() throws IOException { FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions .asFileAttribute(PosixFilePermissions.fromString("rw-r-----")); Path tempFile = Files.createTempFile(this.tempDir, "umask", null, fileAttribute); assertThat(FilePermissions.umaskForPath(tempFile)).isEqualTo(0640); } @Test @DisabledOnOs(OS.WINDOWS) void umaskForPathWithNonExistentFile() { assertThatIOException() .isThrownBy(() -> FilePermissions.umaskForPath(Paths.get(this.tempDir.toString(), "does-not-exist"))); } @Test @EnabledOnOs(OS.WINDOWS) void umaskForPathOnWindowsFails() throws IOException { Path tempFile = Files.createTempFile("umask", null); assertThatIllegalStateException().isThrownBy(() -> FilePermissions.umaskForPath(tempFile)) .withMessageContaining("Unsupported file type for retrieving Posix attributes"); } @Test @SuppressWarnings("NullAway") // Test null check void umaskForPathWithNullPath() { assertThatIllegalArgumentException().isThrownBy(() -> FilePermissions.umaskForPath(null)); } @Test void posixPermissionsToUmask() { Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrw-r--"); assertThat(FilePermissions.posixPermissionsToUmask(permissions)).isEqualTo(0764); } @Test void posixPermissionsToUmaskWithEmptyPermissions() { Set<PosixFilePermission> permissions = Collections.emptySet(); assertThat(FilePermissions.posixPermissionsToUmask(permissions)).isZero(); } @Test @SuppressWarnings("NullAway") // Test null check void posixPermissionsToUmaskWithNullPermissions() { assertThatIllegalArgumentException().isThrownBy(() -> FilePermissions.posixPermissionsToUmask(null)); } }
FilePermissionsTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/format/BooleanFormatTest.java
{ "start": 1422, "end": 3698 }
class ____ extends BooleanWrapper { public AltBoolean() { } public AltBoolean(Boolean b) { super(b); } } /* /********************************************************************** /* Test methods /********************************************************************** */ private final static ObjectMapper MAPPER = newJsonMapper(); @Test public void testShapeViaDefaults() throws Exception { assertEquals(a2q("{'b':true}"), MAPPER.writeValueAsString(new BooleanWrapper(true))); ObjectMapper m = jsonMapperBuilder() .withConfigOverride(Boolean.class, cfg -> cfg.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.NUMBER) )).build(); assertEquals(a2q("{'b':1}"), m.writeValueAsString(new BooleanWrapper(true))); m = jsonMapperBuilder() .withConfigOverride(Boolean.class, cfg -> cfg.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING) )).build(); assertEquals(a2q("{'b':'true'}"), m.writeValueAsString(new BooleanWrapper(true))); } // [databind#3080] @Test public void testPrimitiveShapeViaDefaults() throws Exception { assertEquals(a2q("{'b':true}"), MAPPER.writeValueAsString(new PrimitiveBooleanWrapper(true))); ObjectMapper m = jsonMapperBuilder() .withConfigOverride(Boolean.TYPE, cfg -> cfg.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.NUMBER)) ).build(); assertEquals(a2q("{'b':1}"), m.writeValueAsString(new PrimitiveBooleanWrapper(true))); m = jsonMapperBuilder() .withConfigOverride(Boolean.TYPE, cfg -> cfg.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING)) ).build(); assertEquals(a2q("{'b':'true'}"), m.writeValueAsString(new PrimitiveBooleanWrapper(true))); } @Test public void testShapeOnProperty() throws Exception { assertEquals(a2q("{'b1':1,'b2':0,'b3':true}"), MAPPER.writeValueAsString(new BeanWithBoolean(true, false, true))); } }
AltBoolean
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/spec/OverSpec.java
{ "start": 3953, "end": 4174 }
class ____ to {@link org.apache.calcite.rel.core.Window.Group}, but different * from Group, the partition spec is defined in OverSpec. */ @JsonIgnoreProperties(ignoreUnknown = true) public static
corresponds
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/model/SubscriberStatus.java
{ "start": 751, "end": 2081 }
class ____ implements Serializable { private static final long serialVersionUID = 1065466896062351086L; private String groupKey; private String md5; private Long lastTime; private Boolean status; private String serverIp; public SubscriberStatus() { } public SubscriberStatus(String groupKey, Boolean status, String md5, Long lastTime) { this.groupKey = groupKey; this.md5 = md5; this.lastTime = lastTime; this.status = status; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public Long getLastTime() { return lastTime; } public void setLastTime(Long lastTime) { this.lastTime = lastTime; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getGroupKey() { return groupKey; } public void setGroupKey(String groupKey) { this.groupKey = groupKey; } public String getServerIp() { return serverIp; } public void setServerIp(String serverIp) { this.serverIp = serverIp; } }
SubscriberStatus
java
apache__logging-log4j2
log4j-api-test/src/test/java/org/apache/logging/log4j/util/ConstantsTest.java
{ "start": 941, "end": 1265 }
class ____ { @Test void testJdkVersionDetection() { assertEquals(1, Constants.getMajorVersion("1.1.2")); assertEquals(8, Constants.getMajorVersion("1.8.2")); assertEquals(9, Constants.getMajorVersion("9.1.1")); assertEquals(11, Constants.getMajorVersion("11.1.1")); } }
ConstantsTest
java
google__dagger
javatests/artifacts/dagger-ksp/java-app/src/main/java/app/AssistedInjectClasses.java
{ "start": 1397, "end": 1462 }
interface ____ { Foo create(String str); } static
FooFactory
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/processingstep/MonitoringModuleGenerator.java
{ "start": 1982, "end": 3959 }
class ____ extends SourceFileGenerator<XTypeElement> { private final MonitoringModules monitoringModules; @Inject MonitoringModuleGenerator( XFiler filer, XProcessingEnv processingEnv, MonitoringModules monitoringModules) { super(filer, processingEnv); this.monitoringModules = monitoringModules; } @Override public XElement originatingElement(XTypeElement componentElement) { return componentElement; } @Override public ImmutableList<XTypeSpec> topLevelTypes(XTypeElement componentElement) { XClassName name = generatedMonitoringModuleName(componentElement); monitoringModules.add(name); return ImmutableList.of( classBuilder(name) .addAnnotation(XTypeNames.MODULE) .addModifiers(ABSTRACT) .addFunction(privateConstructor()) .addFunction(setOfFactories()) .addFunction(monitor(componentElement)) .build()); } private XFunSpec privateConstructor() { return constructorBuilder().addModifiers(PRIVATE).build(); } private XFunSpec setOfFactories() { return methodBuilder("setOfFactories") .addAnnotation(XTypeNames.MULTIBINDS) .addModifiers(ABSTRACT) .returns(setOf(XTypeNames.PRODUCTION_COMPONENT_MONITOR_FACTORY)) .build(); } private XFunSpec monitor(XTypeElement componentElement) { return methodBuilder("monitor") .returns(XTypeNames.PRODUCTION_COMPONENT_MONITOR) .addModifiers(STATIC) .addAnnotation(XTypeNames.PROVIDES) .addAnnotation(XTypeNames.PRODUCTION_SCOPE) .addParameter("component", javaxProviderOf(componentElement.getType().asTypeName())) .addParameter( "factories", javaxProviderOf(setOf(XTypeNames.PRODUCTION_COMPONENT_MONITOR_FACTORY))) .addStatement( "return %T.createMonitorForComponent(component, factories)", XTypeNames.MONITORS) .build(); } }
MonitoringModuleGenerator
java
apache__camel
components/camel-thymeleaf/src/test/java/org/apache/camel/component/thymeleaf/ThymeleafDefaultResolverAllParamsTest.java
{ "start": 1561, "end": 4633 }
class ____ extends ThymeleafAbstractBaseTest { @Test public void testThymeleaf() throws InterruptedException { MockEndpoint mock = getMockEndpoint(MOCK_RESULT); mock.expectedMessageCount(1); mock.message(0).body().contains(THANK_YOU_FOR_YOUR_ORDER); mock.message(0).body().endsWith(SPAZZ_TESTING_SERVICE); mock.message(0).header(ThymeleafConstants.THYMELEAF_TEMPLATE).isNull(); mock.message(0).header(ThymeleafConstants.THYMELEAF_VARIABLE_MAP).isNull(); mock.message(0).header(FIRST_NAME).isEqualTo(JANE); template.request(DIRECT_START, templateHeaderProcessor); mock.assertIsSatisfied(); ThymeleafEndpoint thymeleafEndpoint = context.getEndpoint( "thymeleaf:dontcare?allowTemplateFromHeader=true&allowContextMapAll=true&checkExistence=false&order=1&resolver=DEFAULT", ThymeleafEndpoint.class); assertAll("properties", () -> assertNotNull(thymeleafEndpoint), () -> assertTrue(thymeleafEndpoint.isAllowContextMapAll()), () -> assertNull(thymeleafEndpoint.getCacheable()), () -> assertNull(thymeleafEndpoint.getCacheTimeToLive()), () -> assertFalse(thymeleafEndpoint.getCheckExistence()), () -> assertNull(thymeleafEndpoint.getEncoding()), () -> assertEquals(ExchangePattern.InOut, thymeleafEndpoint.getExchangePattern()), () -> assertEquals(ORDER, thymeleafEndpoint.getOrder()), () -> assertNull(thymeleafEndpoint.getPrefix()), () -> assertEquals(ThymeleafResolverType.DEFAULT, thymeleafEndpoint.getResolver()), () -> assertNull(thymeleafEndpoint.getSuffix()), () -> assertNotNull(thymeleafEndpoint.getTemplateEngine()), () -> assertNull(thymeleafEndpoint.getTemplateMode())); assertEquals(1, thymeleafEndpoint.getTemplateEngine().getTemplateResolvers().size()); ITemplateResolver resolver = thymeleafEndpoint.getTemplateEngine().getTemplateResolvers().stream().findFirst().get(); assertTrue(resolver instanceof DefaultTemplateResolver); DefaultTemplateResolver templateResolver = (DefaultTemplateResolver) resolver; assertAll("templateResolver", () -> assertFalse(templateResolver.getCheckExistence()), () -> assertEquals(ORDER, templateResolver.getOrder()), () -> assertEquals(TemplateMode.HTML, templateResolver.getTemplateMode())); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(DIRECT_START) .setBody(simple(SPAZZ_TESTING_SERVICE)) .to("thymeleaf:dontcare?allowTemplateFromHeader=true&allowContextMapAll=true&checkExistence=false&order=1&resolver=DEFAULT") .to(MOCK_RESULT); } }; } }
ThymeleafDefaultResolverAllParamsTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/strings/Strings_assertIsBase64Url_Test.java
{ "start": 1034, "end": 1801 }
class ____ extends StringsBaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN String actual = null; // WHEN var assertionError = expectAssertionError(() -> strings.assertIsBase64Url(INFO, actual)); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_actual_has_invalid_Base64Url_characters() { // GIVEN String actual = "inv@lid"; // WHEN var assertionError = expectAssertionError(() -> strings.assertIsBase64Url(INFO, actual)); // THEN then(assertionError).hasMessage(shouldBeBase64Url(actual).create()); } @Test void should_succeeds_if_actual_is_Base64Url_encoded() { strings.assertIsBase64Url(INFO, "QXNzZXJ0Sisr"); } }
Strings_assertIsBase64Url_Test
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/bulk/OperationEnum.java
{ "start": 1633, "end": 2366 }
enum ____ { @XmlEnumValue("insert") INSERT("insert"), @XmlEnumValue("upsert") UPSERT("upsert"), @XmlEnumValue("update") UPDATE("update"), @XmlEnumValue("delete") DELETE("delete"), @XmlEnumValue("hardDelete") HARD_DELETE("hardDelete"), @XmlEnumValue("query") QUERY("query"); private final String value; OperationEnum(String v) { value = v; } public String value() { return value; } public static OperationEnum fromValue(String v) { for (OperationEnum c : OperationEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
OperationEnum
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/legacy/core/ContextUtil.java
{ "start": 1011, "end": 1932 }
class ____ { /** * Delegates to {@link org.apache.logging.log4j.core.LoggerContext#reconfigure()} if appropriate. * * @param loggerContext The target logger context. */ public static void reconfigure(final LoggerContext loggerContext) { if (loggerContext instanceof org.apache.logging.log4j.core.LoggerContext) { ((org.apache.logging.log4j.core.LoggerContext) loggerContext).reconfigure(); } } /** * Delegates to {@link org.apache.logging.log4j.core.LoggerContext#close()} if appropriate. * * @param loggerContext The target logger context. */ public static void shutdown(final LoggerContext loggerContext) { if (loggerContext instanceof org.apache.logging.log4j.core.LoggerContext) { ((org.apache.logging.log4j.core.LoggerContext) loggerContext).close(); } } private ContextUtil() {} }
ContextUtil
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Attachment.java
{ "start": 1244, "end": 2777 }
class ____ extends BodyPartSource { private final boolean inline; private final Set<String> warnings; protected Attachment(String id, String name, String contentType, boolean inline) { this(id, name, contentType, inline, Collections.emptySet()); } protected Attachment(String id, String name, String contentType, boolean inline, Set<String> warnings) { super(id, name, contentType); this.inline = inline; assert warnings != null; this.warnings = warnings; } @Override public final MimeBodyPart bodyPart() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); part.setContentID(id); part.setFileName(name); part.setDisposition(inline ? INLINE : ATTACHMENT); writeTo(part); return part; } public abstract String type(); public boolean isInline() { return inline; } public Set<String> getWarnings() { return warnings; } /** * intentionally not emitting path as it may come as an information leak */ @Override public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() .field("type", type()) .field("id", id) .field("name", name) .field("content_type", contentType) .endObject(); } protected abstract void writeTo(MimeBodyPart part) throws MessagingException; public static
Attachment
java
google__dagger
javatests/dagger/internal/codegen/bindinggraphvalidation/SetMultibindingValidationTest.java
{ "start": 12659, "end": 13294 }
interface ____ {", " @Singleton", " @Binds @IntoSet Foo bindFoo(FooImplWithMult impl);", "", " @Provides @IntoSet static Long provideLong() {", " return 0L;", " }", "}"); Source childModule = CompilerTests.javaSource( "test.ChildModule", "package test;", "", "import dagger.Binds;", "import dagger.Provides;", "import dagger.multibindings.IntoSet;", "import javax.inject.Inject;", "", "@dagger.Module", "
ParentModule
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/dataset/ClusterDataSetIdPathParameter.java
{ "start": 1135, "end": 1807 }
class ____ extends MessagePathParameter<IntermediateDataSetID> { public static final String KEY = "datasetid"; public ClusterDataSetIdPathParameter() { super(KEY); } @Override protected IntermediateDataSetID convertFromString(String value) { return new IntermediateDataSetID(new AbstractID(StringUtils.hexStringToByte(value))); } @Override protected String convertToString(IntermediateDataSetID value) { return value.toString(); } @Override public String getDescription() { return "32-character hexadecimal string value that identifies a cluster data set."; } }
ClusterDataSetIdPathParameter
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxArray.java
{ "start": 1110, "end": 2036 }
class ____<T> extends Flux<T> implements Fuseable, SourceProducer<T> { final T[] array; @SafeVarargs public FluxArray(T... array) { this.array = Objects.requireNonNull(array, "array"); } @SuppressWarnings("unchecked") public static <T> void subscribe(CoreSubscriber<? super T> s, T[] array) { if (array.length == 0) { Operators.complete(s); return; } if (s instanceof ConditionalSubscriber) { s.onSubscribe(new ArrayConditionalSubscription<>((ConditionalSubscriber<? super T>) s, array)); } else { s.onSubscribe(new ArraySubscription<>(s, array)); } } @Override public void subscribe(CoreSubscriber<? super T> actual) { subscribe(actual, array); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.BUFFERED) return array.length; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return SourceProducer.super.scanUnsafe(key); } static final
FluxArray
java
quarkusio__quarkus
independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/MethodUtilsTest.java
{ "start": 4236, "end": 4491 }
class ____<V> extends SuperSuperClass<Integer, V> { void fromSuperClass(int param) { } void notOverridenFromSuperClass(int param) { } void almostMatchingGeneric(V param) { } } public static
SuperClass
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Spr6602Tests.java
{ "start": 1964, "end": 2157 }
class ____ { @Bean public Foo foo() { return new Foo(barFactory().getObject()); } @Bean public BarFactory barFactory() { return new BarFactory(); } } public static
FooConfig
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/creation/bytebuddy/InlineDelegateByteBuddyMockMakerTest.java
{ "start": 27183, "end": 27390 }
class ____ extends Outer { final Object p2; Inner(Object p1, Object p2) { super(p1); this.p2 = p2; } } } public static
Inner
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/reventity/CustomDataRevEntity.java
{ "start": 986, "end": 2273 }
class ____ { @Id @GeneratedValue(generator = "EnversTestingRevisionGenerator") @RevisionNumber private int customId; @RevisionTimestamp private long customTimestamp; private String data; public int getCustomId() { return customId; } public void setCustomId(int customId) { this.customId = customId; } public long getCustomTimestamp() { return customTimestamp; } public void setCustomTimestamp(long customTimestamp) { this.customTimestamp = customTimestamp; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof CustomDataRevEntity) ) { return false; } CustomDataRevEntity that = (CustomDataRevEntity) o; if ( customId != that.customId ) { return false; } if ( customTimestamp != that.customTimestamp ) { return false; } if ( data != null ? !data.equals( that.data ) : that.data != null ) { return false; } return true; } @Override public int hashCode() { int result = customId; result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); result = 31 * result + (data != null ? data.hashCode() : 0); return result; } }
CustomDataRevEntity
java
google__guava
android/guava/src/com/google/common/cache/CacheBuilderSpec.java
{ "start": 15673, "end": 16019 }
class ____ implements ValueParser { @Override public void parse(CacheBuilderSpec spec, String key, @Nullable String value) { checkArgument(value == null, "recordStats does not take values"); checkArgument(spec.recordStats == null, "recordStats already set"); spec.recordStats = true; } } /** Base
RecordStatsParser
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
{ "start": 126121, "end": 162247 }
interface ____ { void consume( String tableExpression, int relativePosition, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier); } private void collectAttributesIndexesForTable(int naturalTableIndex, Consumer<Integer> indexConsumer) { forEachAttributeMapping( (attributeIndex, attributeMapping) -> { if ( isPropertyOfTable( attributeIndex, naturalTableIndex ) ) { indexConsumer.accept( attributeIndex ); } } ); } protected abstract boolean isIdentifierTable(String tableExpression); protected InsertCoordinator buildInsertCoordinator() { return new InsertCoordinatorStandard( this, factory ); } protected UpdateCoordinator buildUpdateCoordinator() { // we only have updates to issue for entities with one or more singular attributes for ( int i = 0; i < attributeMappings.size(); i++ ) { if ( attributeMappings.get( i ) instanceof SingularAttributeMapping ) { return new UpdateCoordinatorStandard( this, factory ); } } // otherwise, nothing to update return new UpdateCoordinatorNoOp( this ); } protected UpdateCoordinator buildMergeCoordinator() { // we only have updates to issue for entities with one or more singular attributes for ( int i = 0; i < attributeMappings.size(); i++ ) { if ( attributeMappings.get( i ) instanceof SingularAttributeMapping ) { return new MergeCoordinator( this, factory ); } } // otherwise, nothing to update return new UpdateCoordinatorNoOp( this ); } protected DeleteCoordinator buildDeleteCoordinator() { return softDeleteMapping == null ? new DeleteCoordinatorStandard( this, factory ) : new DeleteCoordinatorSoft( this, factory ); } @Override public void addDiscriminatorToInsertGroup(MutationGroupBuilder insertGroupBuilder) { } @Override public void addSoftDeleteToInsertGroup(MutationGroupBuilder insertGroupBuilder) { if ( softDeleteMapping != null ) { final TableInsertBuilder insertBuilder = insertGroupBuilder.getTableDetailsBuilder( getIdentifierTableName() ); final var mutatingTable = insertBuilder.getMutatingTable(); final var columnReference = new ColumnReference( mutatingTable, softDeleteMapping ); final var nonDeletedValueBinding = softDeleteMapping.createNonDeletedValueBinding( columnReference ); insertBuilder.addValueColumn( nonDeletedValueBinding ); } } protected String substituteBrackets(String sql) { return sql == null ? null : new SQLQueryParser( sql, null, getFactory() ).process(); } @Override public final void postInstantiate() throws MappingException { doLateInit(); } /** * Load an instance using either the {@code forUpdateLoader} or the outer joining {@code loader}, * depending upon the value of the {@code lock} parameter */ @Override public Object load(Object id, Object optionalObject, LockMode lockMode, SharedSessionContractImplementor session) { return load( id, optionalObject, lockMode.toLockOptions(), session ); } /** * Load an instance using either the {@code forUpdateLoader} or the outer joining {@code loader}, * depending upon the value of the {@code lock} parameter */ @Override public Object load(Object id, Object optionalObject, LockOptions lockOptions, SharedSessionContractImplementor session) throws HibernateException { return doLoad( id, optionalObject, lockOptions, null, session ); } @Override public Object load(Object id, Object optionalObject, LockOptions lockOptions, SharedSessionContractImplementor session, Boolean readOnly) throws HibernateException { return doLoad( id, optionalObject, lockOptions, readOnly, session ); } private Object doLoad(Object id, Object optionalObject, LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) throws HibernateException { if ( CORE_LOGGER.isTraceEnabled() ) { CORE_LOGGER.fetchingEntity( infoString( this, id, getFactory() ) ); } final var loader = determineLoaderToUse( session, lockOptions ); return optionalObject == null ? loader.load( id, lockOptions, readOnly, session ) : loader.load( id, optionalObject, lockOptions, readOnly, session ); } protected SingleIdEntityLoader<?> determineLoaderToUse(SharedSessionContractImplementor session, LockOptions lockOptions) { if ( hasNamedQueryLoader() ) { return getSingleIdLoader(); } final var influencers = session.getLoadQueryInfluencers(); if ( isAffectedByInfluencers( influencers, true ) ) { return buildSingleIdEntityLoader( influencers, lockOptions ); } return getSingleIdLoader(); // if ( hasNamedQueryLoader() ) { // return getSingleIdLoader(); // } // else { // final boolean hasNonDefaultLockOptions = lockOptions != null // && lockOptions.getLockMode().isPessimistic() // && lockOptions.hasNonDefaultOptions(); // final LoadQueryInfluencers influencers = session.getLoadQueryInfluencers(); // // final boolean needsUniqueLoader = hasNonDefaultLockOptions // || isAffectedByInfluencers( influencers, true ); // return needsUniqueLoader // ? buildSingleIdEntityLoader( influencers, lockOptions ) // : getSingleIdLoader(); // } } private boolean hasNamedQueryLoader() { return queryLoaderName != null; } public SingleIdEntityLoader<?> getSingleIdLoader() { return singleIdLoader; } @Override public Object initializeEnhancedEntityUsedAsProxy( Object entity, String nameOfAttributeBeingAccessed, SharedSessionContractImplementor session) { if ( getBytecodeEnhancementMetadata().extractLazyInterceptor( entity ) instanceof EnhancementAsProxyLazinessInterceptor proxyInterceptor ) { final var entityKey = proxyInterceptor.getEntityKey(); final Object id = entityKey.getIdentifier(); final Object loaded = loadEnhancedEntityUsedAsProxy( entity, session, entityKey ); if ( loaded == null ) { final var persistenceContext = session.getPersistenceContext(); persistenceContext.removeEntry( entity ); persistenceContext.removeEntity( entityKey ); factory.getEntityNotFoundDelegate().handleEntityNotFound( entityKey.getEntityName(), id ); } return readEnhancedEntityAttribute( entity, id, nameOfAttributeBeingAccessed, session ); } else { throw new AssertionFailure( "The BytecodeLazyAttributeInterceptor was not an instance of EnhancementAsProxyLazinessInterceptor" ); } } private Object loadEnhancedEntityUsedAsProxy( Object entity, SharedSessionContractImplementor session, EntityKey entityKey) { if ( canReadFromCache && session.isEventSource() ) { final Object cachedEntity = session.loadFromSecondLevelCache( this, entityKey, entity, LockMode.NONE ); if ( cachedEntity != null ) { return cachedEntity; } } final var lockOptions = new LockOptions(); return determineLoaderToUse( session, lockOptions ) .load( entityKey.getIdentifier(), entity, lockOptions, session ); } private Object readEnhancedEntityAttribute( Object entity, Object id, String nameOfAttributeBeingAccessed, SharedSessionContractImplementor session) { final var interceptor = getBytecodeEnhancementMetadata() .injectInterceptor( entity, id, session ); final Object value; if ( nameOfAttributeBeingAccessed == null ) { return null; } else if ( interceptor.isAttributeLoaded( nameOfAttributeBeingAccessed ) ) { value = getPropertyValue( entity, nameOfAttributeBeingAccessed ); } else { value = initializeLazyProperty( nameOfAttributeBeingAccessed, entity, session ); } return interceptor.readObject( entity, nameOfAttributeBeingAccessed, value ); } @Override public List<?> multiLoad(Object[] ids, EventSource session, MultiIdLoadOptions loadOptions) { return multiLoad( ids, (SharedSessionContractImplementor) session, loadOptions ); } @Override public List<?> multiLoad(Object[] ids, SharedSessionContractImplementor session, MultiIdLoadOptions loadOptions) { return multiIdLoader.load( ids, loadOptions, session ); } @Override public void registerAffectingFetchProfile(String fetchProfileName) { if ( affectingFetchProfileNames == null ) { affectingFetchProfileNames = new HashSet<>(); } affectingFetchProfileNames.add( fetchProfileName ); } @Override public boolean isAffectedByEntityGraph(LoadQueryInfluencers loadQueryInfluencers) { final var graph = loadQueryInfluencers.getEffectiveEntityGraph().getGraph(); return graph != null && graph.appliesTo( getFactory().getJpaMetamodel().entity( getEntityName() ) ); } @Override public boolean isAffectedByEnabledFetchProfiles(LoadQueryInfluencers loadQueryInfluencers) { if ( affectingFetchProfileNames != null && loadQueryInfluencers.hasEnabledFetchProfiles() ) { for ( String profileName : loadQueryInfluencers.getEnabledFetchProfileNames() ) { if ( affectingFetchProfileNames.contains( profileName ) ) { return true; } } } return false; } @Override public boolean isAffectedByEnabledFilters( LoadQueryInfluencers loadQueryInfluencers, boolean onlyApplyForLoadByKeyFilters) { if ( filterHelper != null && loadQueryInfluencers.hasEnabledFilters() ) { return filterHelper.isAffectedBy( loadQueryInfluencers.getEnabledFilters(), onlyApplyForLoadByKeyFilters ) || isAffectedByEnabledFilters( new HashSet<>(), loadQueryInfluencers, onlyApplyForLoadByKeyFilters ); } else { return false; } } /** * Locate the property-indices of all properties considered to be dirty. * * @param currentState The current state of the entity (the state to be checked). * @param previousState The previous state of the entity (the state to be checked against). * @param entity The entity for which we are checking state dirtiness. * @param session The session in which the check is occurring. * * @return {@code null} or the indices of the dirty properties * */ @Override public int[] findDirty(Object[] currentState, Object[] previousState, Object entity, SharedSessionContractImplementor session) throws HibernateException { final int[] dirty = DirtyHelper.findDirty( getDirtyCheckablePropertyTypes(), currentState, previousState, propertyColumnUpdateable, session ); if ( dirty == null ) { return null; } else { logDirtyProperties( dirty ); return dirty; } } /** * Locate the property-indices of all properties considered to be dirty. * * @param old The old state of the entity. * @param current The current state of the entity. * @param entity The entity for which we are checking state modification. * @param session The session in which the check is occurring. * * @return {@code null} or the indices of the modified properties * */ @Override public int[] findModified(Object[] old, Object[] current, Object entity, SharedSessionContractImplementor session) throws HibernateException { final int[] modified = DirtyHelper.findModified( getProperties(), current, old, propertyColumnUpdateable, getPropertyUpdateability(), session ); if ( modified == null ) { return null; } else { logDirtyProperties( modified ); return modified; } } /** * Which properties appear in the SQL update? * (Initialized, updateable ones!) */ public boolean[] getPropertyUpdateability(Object entity) { return hasUninitializedLazyProperties( entity ) ? getNonLazyPropertyUpdateability() : getPropertyUpdateability(); } private void logDirtyProperties(int[] properties) { if ( CORE_LOGGER.isTraceEnabled() ) { for ( int property : properties ) { CORE_LOGGER.propertyIsDirty( qualify( getEntityName(), getAttributeMapping( property ).getAttributeName() ) ); } } } @Override public SessionFactoryImplementor getFactory() { return factory; } private Dialect getDialect() { return factory.getJdbcServices().getDialect(); } @Override public EntityMetamodel getEntityMetamodel() { return this; } @Override public boolean canReadFromCache() { return canReadFromCache; } @Override public boolean canWriteToCache() { return canWriteToCache; } @Override public boolean hasCache() { return canWriteToCache; } @Override public EntityDataAccess getCacheAccessStrategy() { return cacheAccessStrategy; } @Override public CacheEntryStructure getCacheEntryStructure() { return cacheEntryHelper.getCacheEntryStructure(); } @Override public CacheEntry buildCacheEntry(Object entity, Object[] state, Object version, SharedSessionContractImplementor session) { return cacheEntryHelper.buildCacheEntry( entity, state, version, session ); } @Override public boolean hasNaturalIdCache() { return naturalIdRegionAccessStrategy != null; } @Override public NaturalIdDataAccess getNaturalIdCacheAccessStrategy() { return naturalIdRegionAccessStrategy; } // temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public final String getEntityName() { return getName(); } @Override public @Nullable String getJpaEntityName() { return jpaEntityName; } @Override public boolean hasIdentifierProperty() { return !getIdentifierProperty().isVirtual(); } @Override public BasicType<?> getVersionType() { final var versionProperty = getVersionProperty(); return versionProperty == null ? null : (BasicType<?>) versionProperty.getType(); } @Override public boolean isIdentifierAssignedByInsert() { return getIdentifierProperty().isIdentifierAssignedByInsert(); } @Override public void afterReassociate(Object entity, SharedSessionContractImplementor session) { final var metadata = getBytecodeEnhancementMetadata(); if ( metadata.isEnhancedForLazyLoading() ) { final var interceptor = metadata.extractLazyInterceptor( entity ); if ( interceptor == null ) { metadata.injectInterceptor( entity, getIdentifier( entity, session ), session ); } else { interceptor.setSession( session ); } } handleNaturalIdReattachment( entity, session ); } private void handleNaturalIdReattachment(Object entity, SharedSessionContractImplementor session) { if ( naturalIdMapping != null ) { if ( naturalIdMapping.isMutable() ) { final var persistenceContext = session.getPersistenceContextInternal(); final var naturalIdResolutions = persistenceContext.getNaturalIdResolutions(); final Object id = getIdentifier( entity, session ); // for reattachment of mutable natural-ids, we absolutely positively have to grab the snapshot from the // database, because we have no other way to know if the state changed while detached. final Object[] entitySnapshot = persistenceContext.getDatabaseSnapshot( id, this ); final Object naturalIdSnapshot = naturalIdFromSnapshot( entitySnapshot ); naturalIdResolutions.removeSharedResolution( id, naturalIdSnapshot, this, false ); final Object naturalId = naturalIdMapping.extractNaturalIdFromEntity( entity ); naturalIdResolutions.manageLocalResolution( id, naturalId, this, CachedNaturalIdValueSource.UPDATE ); } // otherwise we assume there were no changes to natural id during detachment for now, // that is validated later during flush. } } private Object naturalIdFromSnapshot(Object[] entitySnapshot) { return entitySnapshot == PersistenceContext.NO_ROW ? null : naturalIdMapping.extractNaturalIdFromEntityState( entitySnapshot ); } @Override public Boolean isTransient(Object entity, SharedSessionContractImplementor session) throws HibernateException { final Object id = getIdentifier( entity, session ); // we *always* assume an instance with a null // identifier or no identifier property is unsaved! if ( id == null ) { return true; } // check the version unsaved-value, if appropriate if ( isVersioned() ) { // let this take precedence if defined, since it works for // assigned identifiers final Object version = getVersion( entity ); final Boolean isUnsaved = versionMapping.getUnsavedStrategy().isUnsaved( version ); if ( isUnsaved != null ) { if ( isUnsaved ) { if ( version == null ) { final var persistenceContext = session.getPersistenceContext(); if ( persistenceContext.hasLoadContext() && !persistenceContext.getLoadContexts().isLoadingFinished() ) { // check if we're currently loading this entity instance, the version // will be null, but the entity cannot be considered transient final var holder = persistenceContext.getEntityHolder( new EntityKey( id, this ) ); if ( holder != null && holder.isEventuallyInitialized() && holder.getEntity() == entity ) { return false; } } } if ( getGenerator() != null ) { final Boolean unsaved = identifierMapping.getUnsavedStrategy().isUnsaved( id ); if ( unsaved != null && !unsaved ) { throw new PropertyValueException( "Detached entity with generated id '" + id + "' has an uninitialized version value '" + version + "'", getEntityName(), getVersionColumnName() ); } } } return isUnsaved; } } // check the id unsaved-value final Boolean result = identifierMapping.getUnsavedStrategy().isUnsaved( id ); if ( result != null ) { return result; } // check to see if it is in the second-level cache if ( session.getCacheMode().isGetEnabled() && canReadFromCache() ) { final Object cacheKey = getCacheAccessStrategy() .generateCacheKey( id, this, session.getFactory(), session.getTenantIdentifier() ); final Object cacheEntry = fromSharedCache( session, cacheKey, this, getCacheAccessStrategy() ); if ( cacheEntry != null ) { return false; } } return null; } @Override public boolean hasProxy() { // skip proxy instantiation if entity is bytecode enhanced return isLazy() && !getBytecodeEnhancementMetadata().isEnhancedForLazyLoading(); } @Override @Deprecated public IdentifierGenerator getIdentifierGenerator() throws HibernateException { return getIdentifierProperty().getIdentifierGenerator(); } @Override public Generator getGenerator() { return getIdentifierProperty().getGenerator(); } @Override public BeforeExecutionGenerator getVersionGenerator() { return versionGenerator; } @Override public String getRootEntityName() { return getRootName(); } @Override public String getMappedSuperclass() { return getSuperclass(); } @Override public boolean isConcreteProxy() { return concreteProxy; } @Override public EntityMappingType resolveConcreteProxyTypeForId(Object id, SharedSessionContractImplementor session) { if ( !concreteProxy ) { return this; } else { var concreteTypeLoader = this.concreteTypeLoader; if ( concreteTypeLoader == null ) { this.concreteTypeLoader = concreteTypeLoader = new EntityConcreteTypeLoader( this, session.getFactory() ); } return concreteTypeLoader.getConcreteType( id, session ); } } /** * {@inheritDoc} * * Warning: * When there are duplicated property names in the subclasses * then this method may return the wrong results. * To ensure correct results, this method should only be used when * {@literal this} is the concrete EntityPersister (since the * concrete EntityPersister cannot have duplicated property names). * * @deprecated by the supertypes */ @Override @Deprecated public Type getPropertyType(String propertyName) throws MappingException { // todo (PropertyMapping) : caller also deprecated (aka, easy to remove) return propertyMapping.toType( propertyName ); } @Override public boolean isSelectBeforeUpdateRequired() { return isSelectBeforeUpdate(); } public final OptimisticLockStyle optimisticLockStyle() { return getOptimisticLockStyle(); } @Override public Object createProxy(Object id, SharedSessionContractImplementor session) throws HibernateException { return representationStrategy.getProxyFactory().getProxy( id, session ); } @Override public String toString() { return unqualify( getClass().getName() ) + '(' + getName() + ')'; } @Override public boolean isInstrumented() { return getBytecodeEnhancementMetadata().isEnhancedForLazyLoading(); } @Override public boolean hasInsertGeneratedProperties() { return hasInsertGeneratedValues(); } @Override public boolean hasUpdateGeneratedProperties() { return hasUpdateGeneratedValues(); } @Override public boolean hasPreInsertGeneratedProperties() { return hasPreInsertGeneratedValues(); } @Override public boolean hasPreUpdateGeneratedProperties() { return hasPreUpdateGeneratedValues(); } @Override public boolean isVersionPropertyGenerated() { return isVersioned() && ( isVersionGeneratedOnExecution() || isVersionGeneratedBeforeExecution() ); } private Generator versionPropertyGenerator() { return getGenerators()[ this.getVersionPropertyIndex() ]; } public boolean isVersionGeneratedOnExecution() { final var strategy = versionPropertyGenerator(); return strategy != null && strategy.generatesSometimes() && strategy.generatedOnExecution(); } public boolean isVersionGeneratedBeforeExecution() { final var strategy = versionPropertyGenerator(); return strategy != null && strategy.generatesSometimes() && !strategy.generatedOnExecution(); } @Override public void afterInitialize(Object entity, SharedSessionContractImplementor session) { if ( isPersistentAttributeInterceptable( entity ) && getRepresentationStrategy().getMode() == POJO ) { final var interceptor = getBytecodeEnhancementMetadata() .extractLazyInterceptor( entity ); assert interceptor != null; if ( interceptor.getLinkedSession() == null ) { interceptor.setSession( session ); } } } @Override public boolean[] getNonLazyPropertyUpdateability() { return getNonlazyPropertyUpdateability(); } @Override public CascadeStyle[] getPropertyCascadeStyles() { return getCascadeStyles(); } @Override public final Class<?> getMappedClass() { return this.getMappedJavaType().getJavaTypeClass(); } @Override public Class<?> getConcreteProxyClass() { final var proxyJavaType = getRepresentationStrategy().getProxyJavaType(); return proxyJavaType != null ? proxyJavaType.getJavaTypeClass() : javaType.getJavaTypeClass(); } @Override public void setPropertyValues(Object object, Object[] values) { if ( accessOptimizer != null ) { accessOptimizer.setPropertyValues( object, values ); } else { final int size = getAttributeMappings().size(); if ( getBytecodeEnhancementMetadata().isEnhancedForLazyLoading() ) { for ( int i = 0; i < size; i++ ) { final Object value = values[i]; if ( value != UNFETCHED_PROPERTY ) { setterCache[i].set( object, value ); } } } else { for ( int i = 0; i < size; i++ ) { setterCache[i].set( object, values[i] ); } } } } @Override public void setPropertyValue(Object object, int i, Object value) { setterCache[i].set( object, value ); } @Override public Object[] getPropertyValues(Object object) { if ( accessOptimizer != null ) { return accessOptimizer.getPropertyValues( object ); } else { final var enhancementMetadata = getBytecodeEnhancementMetadata(); final var attributeMappings = getAttributeMappings(); final var values = new Object[attributeMappings.size()]; if ( enhancementMetadata.isEnhancedForLazyLoading() ) { final var lazyAttributesMetadata = enhancementMetadata.getLazyAttributesMetadata(); for ( int i = 0; i < attributeMappings.size(); i++ ) { final var attributeMapping = attributeMappings.get( i ); if ( !lazyAttributesMetadata.isLazyAttribute( attributeMapping.getAttributeName() ) || enhancementMetadata.isAttributeLoaded( object, attributeMapping.getAttributeName() ) ) { values[i] = getterCache[i].get( object ); } else { values[i] = LazyPropertyInitializer.UNFETCHED_PROPERTY; } } } else { for ( int i = 0; i < attributeMappings.size(); i++ ) { values[i] = getterCache[i].get( object ); } } return values; } } @Override public Object getPropertyValue(Object object, int i) { return getterCache[i].get( object ); } @Override public Object getPropertyValue(Object object, String path) { final String basePropertyName = root( path ); final boolean isBasePath = basePropertyName.length() == path.length(); final var attributeMapping = findAttributeMapping( basePropertyName ); final Object baseValue; final MappingType baseValueType; if ( attributeMapping != null ) { baseValue = getterCache[ attributeMapping.getStateArrayPosition() ].get( object ); baseValueType = attributeMapping.getMappedType(); } else if ( identifierMapping instanceof NonAggregatedIdentifierMapping nonAggregatedIdentifierMapping ) { final var mapping = nonAggregatedIdentifierMapping.findSubPart( path, null ) .asAttributeMapping(); baseValue = mapping == null ? null : mapping.getValue( object ); baseValueType = mapping == null ? null : mapping.getMappedType(); } else { baseValue = null; baseValueType = null; } return isBasePath ? baseValue : getPropertyValue( baseValue, (ManagedMappingType) baseValueType, path, basePropertyName ); } private Object getPropertyValue( Object baseValue, ManagedMappingType baseValueType, String path, String prefix) { if ( baseValueType == null ) { // TODO: is this necessary? Should it be an exception instead? return baseValue; } else { final int afterDot = prefix.length() + 1; final int nextDotIndex = path.indexOf( '.', afterDot ); final String pathSoFar = nextDotIndex < 0 ? path : path.substring( 0, nextDotIndex ); final var attributeMapping = baseValueType.findAttributeMapping( pathSoFar.substring( afterDot ) ); final var value = attributeMapping.getValue( baseValue ); final var type = nextDotIndex < 0 ? null : (ManagedMappingType) attributeMapping.getMappedType(); return getPropertyValue( value, type, path, pathSoFar ); } } @Override public Object getIdentifier(Object entity, SharedSessionContractImplementor session) { return identifierMapping.getIdentifier( entity ); } @Override public Object getIdentifier(Object entity, MergeContext mergeContext) { return identifierMapping.getIdentifier( entity, mergeContext ); } @Override public void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session) { identifierMapping.setIdentifier( entity, id, session ); } @Override public Object getVersion(Object object) { final var versionMapping = getVersionMapping(); return versionMapping == null ? null : versionMapping.getVersionAttribute().getPropertyAccess().getGetter().get( object ); } @Override public Object instantiate(Object id, SharedSessionContractImplementor session) { final Object instance = getRepresentationStrategy().getInstantiator().instantiate(); linkToSession( instance, session ); if ( id != null ) { setIdentifier( instance, id, session ); } return instance; } protected void linkToSession(Object entity, SharedSessionContractImplementor session) { if ( session != null ) { processIfPersistentAttributeInterceptable( entity, this::setSession, session ); } } private void setSession(PersistentAttributeInterceptable entity, SharedSessionContractImplementor session) { final var interceptor = getBytecodeEnhancementMetadata() .extractLazyInterceptor( entity ); if ( interceptor != null ) { interceptor.setSession( session ); } } @Override public boolean isInstance(Object object) { return getRepresentationStrategy().getInstantiator().isInstance( object ); } @Override public boolean hasUninitializedLazyProperties(Object object) { return getBytecodeEnhancementMetadata().hasUnFetchedAttributes( object ); } @Override public void resetIdentifier( Object entity, Object currentId, Object currentVersion, SharedSessionContractImplementor session) { if ( !getGenerator().allowAssignedIdentifiers() ) { // reset the identifier final Object defaultIdentifier = identifierMapping.getUnsavedStrategy().getDefaultValue( currentId ); setIdentifier( entity, defaultIdentifier, session ); } // reset the version if ( versionMapping != null ) { final Object defaultVersion = versionMapping.getUnsavedStrategy().getDefaultValue( currentVersion ); versionMapping.getVersionAttribute().getPropertyAccess().getSetter().set( entity, defaultVersion ); } } @Override public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory) { if ( instance != null && hasSubclasses() && !getRepresentationStrategy().getInstantiator().isSameClass( instance ) ) { // todo (6.0) : this previously used `org.hibernate.tuple.entity.EntityTuplizer#determineConcreteSubclassEntityName` // - we may need something similar here... for ( var subclassMappingType : subclassMappingTypes.values() ) { final var persister = subclassMappingType.getEntityPersister(); if ( persister.getRepresentationStrategy().getInstantiator().isSameClass( instance ) ) { return persister; } } } return this; } @Override public boolean hasMultipleTables() { return false; } @Override public Object[] getPropertyValuesToInsert( Object entity, Map<Object,Object> mergeMap, SharedSessionContractImplementor session) throws HibernateException { if ( shouldGetAllProperties( entity ) && accessOptimizer != null ) { return accessOptimizer.getPropertyValues( entity ); } else { final var result = new Object[attributeMappings.size()]; for ( int i = 0; i < attributeMappings.size(); i++ ) { result[i] = getterCache[i].getForInsert( entity, mergeMap, session ); } return result; } } protected boolean shouldGetAllProperties(Object entity) { final var metadata = getBytecodeEnhancementMetadata(); return !metadata.isEnhancedForLazyLoading() || !metadata.hasUnFetchedAttributes( entity ); } @Override public void processInsertGeneratedProperties( Object id, Object entity, Object[] state, GeneratedValues generatedValues, SharedSessionContractImplementor session) { if ( insertGeneratedValuesProcessor == null ) { throw new UnsupportedOperationException( "Entity has no insert-generated properties - '" + getEntityName() + "'" ); } insertGeneratedValuesProcessor.processGeneratedValues( entity, id, state, generatedValues, session ); } protected List<? extends ModelPart> initInsertGeneratedProperties(List<AttributeMapping> generatedAttributes) { final int originalSize = generatedAttributes.size(); final List<ModelPart> generatedBasicAttributes = new ArrayList<>( originalSize ); for ( var generatedAttribute : generatedAttributes ) { // todo (7.0) : support non selectable mappings? Component, ToOneAttributeMapping, ... if ( generatedAttribute.asBasicValuedModelPart() != null && generatedAttribute.getContainingTableExpression().equals( getRootTableName() ) ) { generatedBasicAttributes.add( generatedAttribute ); } } final List<ModelPart> identifierList = isIdentifierAssignedByInsert() ? List.of( getIdentifierMapping() ) : emptyList(); return originalSize > 0 && generatedBasicAttributes.size() == originalSize ? unmodifiableList( combine( identifierList, generatedBasicAttributes ) ) : identifierList; } @Override public List<? extends ModelPart> getInsertGeneratedProperties() { return insertGeneratedProperties; } @Override public void processUpdateGeneratedProperties( Object id, Object entity, Object[] state, GeneratedValues generatedValues, SharedSessionContractImplementor session) { if ( updateGeneratedValuesProcessor == null ) { throw new AssertionFailure( "Entity has no update-generated properties - '" + getEntityName() + "'" ); } updateGeneratedValuesProcessor.processGeneratedValues( entity, id, state, generatedValues, session ); } protected List<? extends ModelPart> initUpdateGeneratedProperties(List<AttributeMapping> generatedAttributes) { final int originalSize = generatedAttributes.size(); final List<ModelPart> generatedBasicAttributes = new ArrayList<>( originalSize ); for ( var generatedAttribute : generatedAttributes ) { if ( generatedAttribute instanceof SelectableMapping selectableMapping && selectableMapping.getContainingTableExpression().equals( getSubclassTableName( 0 ) ) ) { generatedBasicAttributes.add( generatedAttribute ); } } return generatedBasicAttributes.size() == originalSize ? unmodifiableList( generatedBasicAttributes ) : emptyList(); } @Override public List<? extends ModelPart> getUpdateGeneratedProperties() { return updateGeneratedProperties; } @Override public String getIdentifierPropertyName() { return getIdentifierProperty().getName(); } @Override public Type getIdentifierType() { return getIdentifierProperty().getType(); } @Override public boolean hasSubselectLoadableCollections() { return hasSubselectLoadableCollections; } @Override public boolean hasCollectionNotReferencingPK() { return hasCollectionNotReferencingPK; } protected void verifyHasNaturalId() { if ( ! hasNaturalIdentifier() ) { throw new HibernateException( "Entity does not define a natural id : " + getEntityName() ); } } @Override public Object getNaturalIdentifierSnapshot(Object id, SharedSessionContractImplementor session) { verifyHasNaturalId(); if ( CORE_LOGGER.isTraceEnabled() ) { CORE_LOGGER.gettingCurrentNaturalIdSnapshot( getEntityName(), id ); } return getNaturalIdLoader().resolveIdToNaturalId( id, session ); } @Override public NaturalIdLoader<?> getNaturalIdLoader() { verifyHasNaturalId(); if ( naturalIdLoader == null ) { naturalIdLoader = naturalIdMapping.makeLoader( this ); } return naturalIdLoader; } @Override public MultiNaturalIdLoader<?> getMultiNaturalIdLoader() { verifyHasNaturalId(); if ( multiNaturalIdLoader == null ) { multiNaturalIdLoader = naturalIdMapping.makeMultiLoader( this ); } return multiNaturalIdLoader; } @Override public Object loadEntityIdByNaturalId( Object[] naturalIdValues, LockOptions lockOptions, SharedSessionContractImplementor session) { verifyHasNaturalId(); return getNaturalIdLoader().resolveNaturalIdToId( naturalIdValues, session ); } public static int getTableId(String tableName, String[] tables) { for ( int j = 0; j < tables.length; j++ ) { if ( tableName.equalsIgnoreCase( tables[j] ) ) { return j; } } throw new AssertionFailure( "Table " + tableName + " not found" ); } @Override public EntityRepresentationStrategy getRepresentationStrategy() { return representationStrategy; } @Override @Deprecated(forRemoval = true) public BytecodeEnhancementMetadata getInstrumentationMetadata() { return getBytecodeEnhancementMetadata(); } @Override public String getTableNameForColumn(String columnName) { return getTableName( determineTableNumberForColumn( columnName ) ); } protected int determineTableNumberForColumn(String columnName) { return 0; } protected String determineTableName(Table table) { return table.getSubselect() != null ? "( " + createSqlQueryParser( table ).process() + " )" : factory.getSqlStringGenerationContext().format( table.getQualifiedTableName() ); } private SQLQueryParser createSqlQueryParser(Table table) { return new SQLQueryParser( table.getSubselect(), null, // NOTE: this allows finer control over catalog and schema used for // placeholder handling (`{h-catalog}`, `{h-schema}`, `{h-domain}`) new ExplicitSqlStringGenerationContext( table.getCatalog(), table.getSchema(), factory ) ); } @Override public EntityEntryFactory getEntityEntryFactory() { return entityEntryFactory; } /** * Consolidated these onto a single helper because the 2 pieces work in tandem. */ public
MutabilityOrderedTableConsumer
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/QuarkusWorker.java
{ "start": 356, "end": 1496 }
class ____<P extends QuarkusParams> implements WorkAction<P> { Properties buildSystemProperties() { Properties props = new Properties(); props.putAll(getParameters().getBuildSystemProperties().get()); return props; } CuratedApplication createAppCreationContext() throws BootstrapException { QuarkusParams params = getParameters(); Path buildDir = params.getTargetDirectory().getAsFile().get().toPath(); String baseName = params.getBaseName().get(); ApplicationModel appModel = params.getAppModel().get(); return QuarkusBootstrap.builder() .setBaseClassLoader(getClass().getClassLoader()) .setExistingModel(appModel) .setTargetDirectory(buildDir) .setBaseName(baseName) .setBuildSystemProperties(buildSystemProperties()) .setAppArtifact(appModel.getAppArtifact()) .setLocalProjectDiscovery(false) .setIsolateDeployment(true) .setDependencyInfoProvider(() -> null) .build().bootstrap(); } }
QuarkusWorker
java
quarkusio__quarkus
integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java
{ "start": 45236, "end": 46007 }
class ____ not visible", devModeClient.getHttpResponse("/hello")); } @Test public void testThatTheApplicationIsReloadedOnNewResource() throws MavenInvocationException, IOException { testDir = initProject("projects/classic", "projects/project-classic-run-new-resource"); runAndCheck(); File source = new File(testDir, "src/main/java/org/acme/MyNewResource.java"); String myNewResource = "package org.acme;\n" + "\n" + "import jakarta.ws.rs.GET;\n" + "import jakarta.ws.rs.Path;\n" + "import jakarta.ws.rs.Produces;\n" + "import jakarta.ws.rs.core.MediaType;\n" + "\n" + "@Path(\"/foo\")\n" + "public
is
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 2047, "end": 2321 }
interface ____ {", " Foo getFoo();", "}"); Source injectable = CompilerTests.javaSource( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "
MyComponent
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
{ "start": 3845, "end": 4473 }
class ____ { // BUG: Diagnostic contains: @Test public void shouldDoSomething() { Mockito.verify(null); } } """) .doTest(); } @Test public void containsAssertAsIdentifier_shouldBeTest() { compilationHelper .addSourceLines( "Test.java", """ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.common.truth.Truth.assertThat; import java.util.Collections; @RunWith(JUnit4.class) public
Test
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/fs/ByteBufferReadable.java
{ "start": 1075, "end": 1216 }
interface ____ borrowed from {@code ByteBufferReadable} and {@code * ByteBufferPositionedReadable} in Apache Hadoop. */ @Experimental public
is
java
alibaba__nacos
common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java
{ "start": 27792, "end": 28469 }
class ____ { public String parentField = "parentValue"; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TestOfParent that = (TestOfParent) o; return parentField != null ? parentField.equals(that.parentField) : that.parentField == null; } @Override public int hashCode() { return parentField != null ? parentField.hashCode() : 0; } } static
TestOfParent
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/test/java/org/elasticsearch/xpack/esql/core/async/AsyncTaskManagementServiceTests.java
{ "start": 2872, "end": 3503 }
class ____ extends ActionResponse { private final String string; private final String id; public TestResponse(String string, String id) { this.string = string; this.id = id; } public TestResponse(StreamInput input) throws IOException { this.string = input.readOptionalString(); this.id = input.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(string); out.writeOptionalString(id); } } public static
TestResponse
java
apache__camel
components/camel-gson/src/test/java/org/apache/camel/component/gson/GsonFieldNamePolicyTest.java
{ "start": 1213, "end": 2673 }
class ____ extends CamelTestSupport { @Test public void testUnmarshalPojo() { String json = "{\"id\":\"123\",\"first_name\":\"Donald\",\"last_name\":\"Duck\"}"; PersonPojo pojo = template.requestBody("direct:backPojo", json, PersonPojo.class); assertNotNull(pojo); assertEquals(123, pojo.getId()); assertEquals("Donald", pojo.getFirstName()); assertEquals("Duck", pojo.getLastName()); } @Test public void testMarshalPojo() { PersonPojo pojo = new PersonPojo(); pojo.setId(123); pojo.setFirstName("Donald"); pojo.setLastName("Duck"); String json = template.requestBody("direct:inPojo", pojo, String.class); assertTrue(json.contains("\"id\":123")); assertTrue(json.contains("\"first_name\":\"Donald\"")); assertTrue(json.contains("\"last_name\":\"Duck\"")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { GsonDataFormat formatPojo = new GsonDataFormat(); formatPojo.setUnmarshalType(PersonPojo.class); formatPojo.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); from("direct:inPojo").marshal(formatPojo); from("direct:backPojo").unmarshal(formatPojo); } }; } }
GsonFieldNamePolicyTest
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/method/AbstractFallbackMethodSecurityMetadataSource.java
{ "start": 3366, "end": 3879 }
class ____ the original method. return findAttributes(method.getDeclaringClass()); } return Collections.emptyList(); } /** * Obtains the security metadata applicable to the specified method invocation. * * <p> * Note that the {@link Method#getDeclaringClass()} may not equal the * <code>targetClass</code>. Both parameters are provided to assist subclasses which * may wish to provide advanced capabilities related to method metadata being * "registered" against a method even if the target
of
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ProtoStringFieldReferenceEqualityTest.java
{ "start": 1432, "end": 1651 }
class ____ extends com.google.protobuf.GeneratedMessage { public abstract String getMessage(); } """) .addSourceLines( "Test.java", """
Proto
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/client/JobInitializationException.java
{ "start": 986, "end": 1248 }
class ____ extends JobExecutionException { private static final long serialVersionUID = 2818087325120827526L; public JobInitializationException(JobID jobID, String msg, Throwable cause) { super(jobID, msg, cause); } }
JobInitializationException
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/AnnotationIntrospector.java
{ "start": 11572, "end": 12001 }
class ____ introspect */ public PropertyName findRootName(MapperConfig<?> config, AnnotatedClass ac) { return null; } /** * Method for checking whether properties that have specified type * (class, not generics aware) should be completely ignored for * serialization and deserialization purposes. * * @param config Effective mapper configuration in use * @param ac Annotated
to
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/config/RetryConfigTest.java
{ "start": 433, "end": 5819 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(jar -> jar.addClasses(RetryConfigBean.class, TestException.class, TestConfigExceptionA.class, TestConfigExceptionB.class, TestConfigExceptionB1.class)) .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/maxRetries\".retry.max-retries", "10") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/maxDuration\".retry.max-duration", "1") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/maxDuration\".retry.max-duration-unit", "seconds") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/delay\".retry.delay", "2000") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/delay\".retry.delay-unit", "micros") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/retryOn\".retry.retry-on", "io.quarkus.smallrye.faulttolerance.test.config.TestConfigExceptionA,io.quarkus.smallrye.faulttolerance.test.config.TestConfigExceptionB") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/abortOn\".retry.abort-on", "io.quarkus.smallrye.faulttolerance.test.config.TestConfigExceptionA,io.quarkus.smallrye.faulttolerance.test.config.TestConfigExceptionB1") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/jitter\".retry.jitter", "1") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.RetryConfigBean/jitter\".retry.jitter-unit", "seconds"); @Inject private RetryConfigBean bean; @Test public void maxRetries() { AtomicInteger counter = new AtomicInteger(); assertThatThrownBy(() -> bean.maxRetries(counter)).isExactlyInstanceOf(TestException.class); assertThat(counter).hasValue(11); } @Test public void maxDuration() { long startTime = System.nanoTime(); assertThatThrownBy(() -> bean.maxDuration()).isExactlyInstanceOf(TestException.class); long endTime = System.nanoTime(); Duration duration = Duration.ofNanos(endTime - startTime); assertThat(duration).isLessThan(Duration.ofSeconds(8)); } @Test public void delay() { long startTime = System.nanoTime(); assertThatThrownBy(() -> bean.delay()).isExactlyInstanceOf(TestException.class); long endTime = System.nanoTime(); Duration duration = Duration.ofNanos(endTime - startTime); assertThat(duration).isLessThan(Duration.ofSeconds(8)); } @Test public void retryOn() { AtomicInteger counter = new AtomicInteger(); counter.set(0); assertThatThrownBy(() -> bean.retryOn(new TestException(), counter)).isExactlyInstanceOf(TestException.class); assertThat(counter).hasValue(1); counter.set(0); assertThatThrownBy(() -> bean.retryOn(new TestConfigExceptionA(), counter)) .isExactlyInstanceOf(TestConfigExceptionA.class); assertThat(counter).hasValue(2); counter.set(0); assertThatThrownBy(() -> bean.retryOn(new TestConfigExceptionB(), counter)) .isExactlyInstanceOf(TestConfigExceptionB.class); assertThat(counter).hasValue(2); counter.set(0); assertThatThrownBy(() -> bean.retryOn(new TestConfigExceptionB1(), counter)) .isExactlyInstanceOf(TestConfigExceptionB1.class); assertThat(counter).hasValue(2); } @Test public void abortOn() { AtomicInteger counter = new AtomicInteger(); counter.set(0); assertThatThrownBy(() -> bean.abortOn(new TestException(), counter)).isExactlyInstanceOf(TestException.class); assertThat(counter).hasValue(1); counter.set(0); assertThatThrownBy(() -> bean.abortOn(new TestConfigExceptionA(), counter)) .isExactlyInstanceOf(TestConfigExceptionA.class); assertThat(counter).hasValue(1); counter.set(0); assertThatThrownBy(() -> bean.abortOn(new TestConfigExceptionB(), counter)) .isExactlyInstanceOf(TestConfigExceptionB.class); assertThat(counter).hasValue(2); counter.set(0); assertThatThrownBy(() -> bean.abortOn(new TestConfigExceptionB1(), counter)) .isExactlyInstanceOf(TestConfigExceptionB1.class); assertThat(counter).hasValue(1); } @Test public void jitter() { assertThatThrownBy(() -> bean.jitter()).isExactlyInstanceOf(TestConfigExceptionA.class); } }
RetryConfigTest
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/ClientCallImpl.java
{ "start": 26002, "end": 27724 }
class ____ extends ContextRunnable { StreamClosed() { super(context); } @Override public void runInContext() { try (TaskCloseable ignore = PerfMark.traceTask("ClientCall$Listener.onClose")) { PerfMark.attachTag(tag); PerfMark.linkIn(link); runInternal(); } } private void runInternal() { cancellationHandler.tearDown(); Status status = savedStatus; Metadata trailers = savedTrailers; if (exceptionStatus != null) { // Ideally exceptionStatus == savedStatus, as exceptionStatus was passed to cancel(). // However the cancel is racy and this closed() may have already been queued when the // cancellation occurred. Since other calls like onMessage() will throw away data if // exceptionStatus != null, it is semantically essential that we _not_ use a status // provided by the server. status = exceptionStatus; // Replace trailers to prevent mixing sources of status and trailers. trailers = new Metadata(); } try { closeObserver(observer, status, trailers); } finally { channelCallsTracer.reportCallEnded(status.isOk()); } } } callExecutor.execute(new StreamClosed()); } @Override public void onReady() { if (method.getType().clientSendsOneMessage()) { return; } try (TaskCloseable ignore = PerfMark.traceTask("ClientStreamListener.onReady")) { PerfMark.attachTag(tag); final Link link = PerfMark.linkOut(); final
StreamClosed
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/injectionPoints/InjectionPointTransformerTest.java
{ "start": 3145, "end": 3216 }
interface ____ { } @ApplicationScoped static
AnotherQualifier
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/utils/ClassUtils.java
{ "start": 872, "end": 1479 }
class ____ { public static <T> Class<T> resolveGenericType(Class<?> declaredClass) { return (Class<T>) ResolvableType.forClass(declaredClass).getSuperType().resolveGeneric(0); } public static <T> Class<T> resolveGenericTypeByInterface(Class<?> declaredClass) { return (Class<T>) ResolvableType.forClass(declaredClass).getInterfaces()[0].resolveGeneric(0); } public static Class findClassByName(String className) { try { return Class.forName(className); } catch (Exception e) { throw new RuntimeException("this
ClassUtils
java
apache__camel
components/camel-openstack/src/main/java/org/apache/camel/component/openstack/keystone/KeystoneEndpoint.java
{ "start": 2081, "end": 5407 }
class ____ extends AbstractOpenstackEndpoint { @UriParam(enums = "regions,domains,projects,users,groups") @Metadata(required = true) String subsystem; @UriPath @Metadata(required = true) private String host; @UriParam(defaultValue = "default") private String domain = "default"; @UriParam @Metadata(required = true) private String project; @UriParam private String operation; @UriParam @Metadata(required = true, secret = true) private String username; @UriParam @Metadata(required = true, secret = true) private String password; @UriParam private Config config; public KeystoneEndpoint(String uri, KeystoneComponent component) { super(uri, component); } @Override public Producer createProducer() throws Exception { switch (getSubsystem()) { case KeystoneConstants.REGIONS: return new RegionProducer(this, createClient()); case KeystoneConstants.DOMAINS: return new DomainProducer(this, createClient()); case KeystoneConstants.PROJECTS: return new ProjectProducer(this, createClient()); case KeystoneConstants.USERS: return new UserProducer(this, createClient()); case KeystoneConstants.GROUPS: return new GroupProducer(this, createClient()); default: throw new IllegalArgumentException("Can't create producer with subsystem " + subsystem); } } public String getSubsystem() { return subsystem; } /** * OpenStack Keystone subsystem */ public void setSubsystem(String subsystem) { this.subsystem = subsystem; } @Override public String getDomain() { return domain; } /** * Authentication domain */ public void setDomain(String domain) { this.domain = domain; } @Override public String getProject() { return project; } /** * The project ID */ public void setProject(String project) { this.project = project; } @Override public String getOperation() { return operation; } /** * The operation to do */ public void setOperation(String operation) { this.operation = operation; } @Override public String getUsername() { return username; } /** * OpenStack username */ public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return password; } /** * OpenStack password */ public void setPassword(String password) { this.password = password; } @Override public String getHost() { return host; } /** * OpenStack host url */ public void setHost(String host) { this.host = host; } @Override public Config getConfig() { return config; } /** * OpenStack configuration */ public void setConfig(Config config) { this.config = config; } // V2 API is not supported (is deprecated) @Override public String getApiVersion() { return V3; } }
KeystoneEndpoint
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/plugins/Plugin.java
{ "start": 3461, "end": 5112 }
interface ____ { /** * A client to make requests to the system */ Client client(); /** * A service to allow watching and updating cluster state */ ClusterService clusterService(); /** * A service to reroute shards to other nodes */ RerouteService rerouteService(); /** * A service to allow retrieving an executor to run an async action */ ThreadPool threadPool(); /** * A service to watch for changes to node local files */ ResourceWatcherService resourceWatcherService(); /** * A service to allow running scripts on the local node */ ScriptService scriptService(); /** * The registry for extensible xContent parsing */ NamedXContentRegistry xContentRegistry(); /** * The environment for path and setting configurations */ Environment environment(); /** * The node environment used coordinate access to the data paths */ NodeEnvironment nodeEnvironment(); /** * The registry for {@link NamedWriteable} object parsing */ NamedWriteableRegistry namedWriteableRegistry(); /** * A service that resolves expression to index and alias names */ IndexNameExpressionResolver indexNameExpressionResolver(); /** * A service that manages snapshot repositories. */ RepositoriesService repositoriesService(); /** * An
PluginServices
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/ErrorBlock.java
{ "start": 1028, "end": 1104 }
class ____ used to display an error message to the user in the UI. */ public
is
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSQLExceptionTest.java
{ "start": 133, "end": 395 }
class ____ extends TestCase { public void test_wall() throws Exception { WallSQLException ex = new WallSQLException("", new RuntimeException()); assertEquals("", ex.getMessage()); assertNotNull(ex.getCause()); } }
WallSQLExceptionTest
java
apache__rocketmq
controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerTest.java
{ "start": 3142, "end": 20952 }
class ____ { private List<String> baseDirs; private List<DLedgerController> controllers; public DLedgerController launchController(final String group, final String peers, final String selfId, final boolean isEnableElectUncleanMaster) { String tmpdir = System.getProperty("java.io.tmpdir"); final String path = (StringUtils.endsWith(tmpdir, File.separator) ? tmpdir : tmpdir + File.separator) + group + File.separator + selfId; baseDirs.add(path); final ControllerConfig config = new ControllerConfig(); config.setControllerDLegerGroup(group); config.setControllerDLegerPeers(peers); config.setControllerDLegerSelfId(selfId); config.setControllerStorePath(path); config.setMappedFileSize(10 * 1024 * 1024); config.setEnableElectUncleanMaster(isEnableElectUncleanMaster); config.setScanInactiveMasterInterval(1000); final DLedgerController controller = new DLedgerController(config, (str1, str2, str3) -> true); controller.startup(); return controller; } @Before public void startup() { this.baseDirs = new ArrayList<>(); this.controllers = new ArrayList<>(); } @After public void tearDown() { for (Controller controller : this.controllers) { controller.shutdown(); } for (String dir : this.baseDirs) { new File(dir).delete(); } } public void registerNewBroker(Controller leader, String clusterName, String brokerName, String brokerAddress, Long expectBrokerId) throws Exception { // Get next brokerId final GetNextBrokerIdRequestHeader getNextBrokerIdRequest = new GetNextBrokerIdRequestHeader(clusterName, brokerName); RemotingCommand remotingCommand = leader.getNextBrokerId(getNextBrokerIdRequest).get(2, TimeUnit.SECONDS); GetNextBrokerIdResponseHeader getNextBrokerIdResp = (GetNextBrokerIdResponseHeader) remotingCommand.readCustomHeader(); Long nextBrokerId = getNextBrokerIdResp.getNextBrokerId(); String registerCheckCode = brokerAddress + ";" + System.currentTimeMillis(); // Check response assertEquals(expectBrokerId, nextBrokerId); // Apply brokerId final ApplyBrokerIdRequestHeader applyBrokerIdRequestHeader = new ApplyBrokerIdRequestHeader(clusterName, brokerName, nextBrokerId, registerCheckCode); RemotingCommand remotingCommand1 = leader.applyBrokerId(applyBrokerIdRequestHeader).get(2, TimeUnit.SECONDS); // Check response assertEquals(ResponseCode.SUCCESS, remotingCommand1.getCode()); // Register success final RegisterBrokerToControllerRequestHeader registerBrokerToControllerRequestHeader = new RegisterBrokerToControllerRequestHeader(clusterName, brokerName, nextBrokerId, brokerAddress); RemotingCommand remotingCommand2 = leader.registerBroker(registerBrokerToControllerRequestHeader).get(2, TimeUnit.SECONDS); assertEquals(ResponseCode.SUCCESS, remotingCommand2.getCode()); } public void brokerTryElectMaster(Controller leader, String clusterName, String brokerName, String brokerAddress, Long brokerId, boolean exceptSuccess) throws Exception { final ElectMasterRequestHeader electMasterRequestHeader = ElectMasterRequestHeader.ofBrokerTrigger(clusterName, brokerName, brokerId); RemotingCommand command = leader.electMaster(electMasterRequestHeader).get(2, TimeUnit.SECONDS); ElectMasterResponseHeader header = (ElectMasterResponseHeader) command.readCustomHeader(); assertEquals(exceptSuccess, ResponseCode.SUCCESS == command.getCode()); } private boolean alterNewInSyncSet(Controller leader, String brokerName, Long masterBrokerId, Integer masterEpoch, Set<Long> newSyncStateSet, Integer syncStateSetEpoch) throws Exception { final AlterSyncStateSetRequestHeader alterRequest = new AlterSyncStateSetRequestHeader(brokerName, masterBrokerId, masterEpoch); final RemotingCommand response = leader.alterSyncStateSet(alterRequest, new SyncStateSet(newSyncStateSet, syncStateSetEpoch)).get(10, TimeUnit.SECONDS); if (null == response || response.getCode() != ResponseCode.SUCCESS) { return false; } final RemotingCommand getInfoResponse = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(brokerName)).get(10, TimeUnit.SECONDS); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) getInfoResponse.readCustomHeader(); final SyncStateSet syncStateSet = RemotingSerializable.decode(getInfoResponse.getBody(), SyncStateSet.class); assertArrayEquals(syncStateSet.getSyncStateSet().toArray(), newSyncStateSet.toArray()); assertEquals(syncStateSet.getSyncStateSetEpoch(), syncStateSetEpoch + 1); return true; } public DLedgerController waitLeader(final List<DLedgerController> controllers) throws Exception { if (controllers.isEmpty()) { return null; } DLedgerController c1 = controllers.get(0); DLedgerController dLedgerController = await().atMost(Duration.ofSeconds(10)).until(() -> { String leaderId = c1.getMemberState().getLeaderId(); if (null == leaderId) { return null; } for (DLedgerController controller : controllers) { if (controller.getMemberState().getSelfId().equals(leaderId) && controller.isLeaderState()) { return controller; } } return null; }, item -> item != null); return dLedgerController; } public DLedgerController mockMetaData(boolean enableElectUncleanMaster) throws Exception { String group = UUID.randomUUID().toString(); String peers = String.format("n0-localhost:%d;n1-localhost:%d;n2-localhost:%d", 30000, 30001, 30002); DLedgerController c0 = launchController(group, peers, "n0", enableElectUncleanMaster); DLedgerController c1 = launchController(group, peers, "n1", enableElectUncleanMaster); DLedgerController c2 = launchController(group, peers, "n2", enableElectUncleanMaster); controllers.add(c0); controllers.add(c1); controllers.add(c2); DLedgerController leader = waitLeader(controllers); // register registerNewBroker(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[0], 1L); registerNewBroker(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[1], 2L); registerNewBroker(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[2], 3L); // try elect brokerTryElectMaster(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[0], 1L, true); brokerTryElectMaster(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[1], 2L, false); brokerTryElectMaster(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[2], 3L, false); final RemotingCommand getInfoResponse = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) getInfoResponse.readCustomHeader(); assertEquals(1, replicaInfo.getMasterEpoch().intValue()); assertEquals(DEFAULT_IP[0], replicaInfo.getMasterAddress()); // Try alter SyncStateSet final HashSet<Long> newSyncStateSet = new HashSet<>(); newSyncStateSet.add(1L); newSyncStateSet.add(2L); newSyncStateSet.add(3L); assertTrue(alterNewInSyncSet(leader, DEFAULT_BROKER_NAME, 1L, 1, newSyncStateSet, 1)); return leader; } public void setBrokerAlivePredicate(DLedgerController controller, Long... deathBroker) { controller.setBrokerAlivePredicate((clusterName, brokerName, brokerId) -> { for (Long broker : deathBroker) { if (broker.equals(brokerId)) { return false; } } return true; }); } public void setBrokerElectPolicy(DLedgerController controller, Long... deathBroker) { controller.setElectPolicy(new DefaultElectPolicy((clusterName, brokerName, brokerId) -> { for (Long broker : deathBroker) { if (broker.equals(brokerId)) { return false; } } return true; }, null)); } @Test public void testElectMaster() throws Exception { final DLedgerController leader = mockMetaData(false); final ElectMasterRequestHeader request = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME); setBrokerElectPolicy(leader, 1L); final RemotingCommand resp = leader.electMaster(request).get(10, TimeUnit.SECONDS); final ElectMasterResponseHeader response = (ElectMasterResponseHeader) resp.readCustomHeader(); assertEquals(2, response.getMasterEpoch().intValue()); assertNotEquals(1L, response.getMasterBrokerId().longValue()); assertNotEquals(DEFAULT_IP[0], response.getMasterAddress()); } @Test public void testBrokerLifecycleListener() throws Exception { final DLedgerController leader = mockMetaData(false); assertTrue(leader.isLeaderState()); // Mock that master broker has been inactive, and try to elect a new master from sync-state-set // But we shut down two controller, so the ElectMasterEvent will be appended to DLedger failed. // So the statemachine still keep the stale master's information List<DLedgerController> removed = controllers.stream().filter(controller -> controller != leader).collect(Collectors.toList()); for (DLedgerController dLedgerController : removed) { dLedgerController.shutdown(); controllers.remove(dLedgerController); } final ElectMasterRequestHeader request = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME); setBrokerElectPolicy(leader, 1L); Exception exception = null; RemotingCommand remotingCommand = null; try { remotingCommand = leader.electMaster(request).get(5, TimeUnit.SECONDS); } catch (Exception e) { exception = e; } assertTrue(exception != null || remotingCommand != null && remotingCommand.getCode() == ResponseCode.CONTROLLER_NOT_LEADER); // Shut down leader controller leader.shutdown(); controllers.remove(leader); // Restart two controller for (DLedgerController controller : removed) { if (controller != leader) { ControllerConfig config = controller.getControllerConfig(); DLedgerController newController = launchController(config.getControllerDLegerGroup(), config.getControllerDLegerPeers(), config.getControllerDLegerSelfId(), false); controllers.add(newController); newController.startup(); } } DLedgerController newLeader = waitLeader(controllers); setBrokerAlivePredicate(newLeader, 1L); // Check if the statemachine is stale final RemotingCommand resp = newLeader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)). get(10, TimeUnit.SECONDS); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) resp.readCustomHeader(); assertEquals(1, replicaInfo.getMasterBrokerId().longValue()); assertEquals(1, replicaInfo.getMasterEpoch().intValue()); // Register broker's lifecycle listener AtomicBoolean atomicBoolean = new AtomicBoolean(false); newLeader.registerBrokerLifecycleListener((clusterName, brokerName, brokerId) -> { assertEquals(DEFAULT_BROKER_NAME, brokerName); atomicBoolean.set(true); }); Thread.sleep(2000); assertTrue(atomicBoolean.get()); } @Test public void testAllReplicasShutdownAndRestartWithUnEnableElectUnCleanMaster() throws Exception { final DLedgerController leader = mockMetaData(false); final HashSet<Long> newSyncStateSet = new HashSet<>(); newSyncStateSet.add(1L); assertTrue(alterNewInSyncSet(leader, DEFAULT_BROKER_NAME, 1L, 1, newSyncStateSet, 2)); // Now we trigger electMaster api, which means the old master is shutdown and want to elect a new master. // However, the syncStateSet in statemachine is {1}, not more replicas can be elected as master, it will be failed. final ElectMasterRequestHeader electRequest = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME); setBrokerElectPolicy(leader, 1L); leader.electMaster(electRequest).get(10, TimeUnit.SECONDS); final RemotingCommand resp = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)). get(10, TimeUnit.SECONDS); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) resp.readCustomHeader(); final SyncStateSet syncStateSet = RemotingSerializable.decode(resp.getBody(), SyncStateSet.class); assertEquals(syncStateSet.getSyncStateSet(), newSyncStateSet); assertEquals(null, replicaInfo.getMasterAddress()); assertEquals(2, replicaInfo.getMasterEpoch().intValue()); // Now, we start broker - id[2]address[127.0.0.1:9001] to try elect, but it was not in syncStateSet, so it will not be elected as master. final ElectMasterRequestHeader request1 = ElectMasterRequestHeader.ofBrokerTrigger(DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, 2L); final ElectMasterResponseHeader r1 = (ElectMasterResponseHeader) leader.electMaster(request1).get(10, TimeUnit.SECONDS).readCustomHeader(); assertEquals(null, r1.getMasterBrokerId()); assertEquals(null, r1.getMasterAddress()); // Now, we start broker - id[1]address[127.0.0.1:9000] to try elect, it will be elected as master setBrokerElectPolicy(leader); final ElectMasterRequestHeader request2 = ElectMasterRequestHeader.ofBrokerTrigger(DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, 1L); final ElectMasterResponseHeader r2 = (ElectMasterResponseHeader) leader.electMaster(request2).get(10, TimeUnit.SECONDS).readCustomHeader(); assertEquals(1L, r2.getMasterBrokerId().longValue()); assertEquals(DEFAULT_IP[0], r2.getMasterAddress()); assertEquals(3, r2.getMasterEpoch().intValue()); } @Test public void testEnableElectUnCleanMaster() throws Exception { final DLedgerController leader = mockMetaData(true); final HashSet<Long> newSyncStateSet = new HashSet<>(); newSyncStateSet.add(1L); assertTrue(alterNewInSyncSet(leader, DEFAULT_BROKER_NAME, 1L, 1, newSyncStateSet, 2)); // Now we trigger electMaster api, which means the old master is shutdown and want to elect a new master. // However, event if the syncStateSet in statemachine is {DEFAULT_IP[0]} // the option {enableElectUncleanMaster = true}, so the controller sill can elect a new master final ElectMasterRequestHeader electRequest = ElectMasterRequestHeader.ofControllerTrigger(DEFAULT_BROKER_NAME); setBrokerElectPolicy(leader, 1L); final CompletableFuture<RemotingCommand> future = leader.electMaster(electRequest); future.get(10, TimeUnit.SECONDS); final RemotingCommand resp = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) resp.readCustomHeader(); final SyncStateSet syncStateSet = RemotingSerializable.decode(resp.getBody(), SyncStateSet.class); final HashSet<Long> newSyncStateSet2 = new HashSet<>(); newSyncStateSet2.add(replicaInfo.getMasterBrokerId()); assertEquals(syncStateSet.getSyncStateSet(), newSyncStateSet2); assertNotEquals(1L, replicaInfo.getMasterBrokerId().longValue()); assertNotEquals(DEFAULT_IP[0], replicaInfo.getMasterAddress()); assertEquals(2, replicaInfo.getMasterEpoch().intValue()); } @Test public void testChangeControllerLeader() throws Exception { final DLedgerController leader = mockMetaData(false); leader.shutdown(); this.controllers.remove(leader); // Wait leader again final DLedgerController newLeader = waitLeader(this.controllers); assertNotNull(newLeader); RemotingCommand response = await().atMost(Duration.ofSeconds(10)).until(() -> { final RemotingCommand resp = newLeader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); if (resp.getCode() == ResponseCode.SUCCESS) { return resp; } return null; }, item -> item != null); final GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) response.readCustomHeader(); final SyncStateSet syncStateSetResult = RemotingSerializable.decode(response.getBody(), SyncStateSet.class); assertEquals(replicaInfo.getMasterAddress(), DEFAULT_IP[0]); assertEquals(1, replicaInfo.getMasterEpoch().intValue()); final HashSet<Long> syncStateSet = new HashSet<>(); syncStateSet.add(1L); syncStateSet.add(2L); syncStateSet.add(3L); assertEquals(syncStateSetResult.getSyncStateSet(), syncStateSet); } }
DLedgerControllerTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java
{ "start": 4928, "end": 5915 }
class ____ implements BeanPostProcessor, PriorityOrdered { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Jsr250MethodSecurityMetadataSource) { ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultHttpSecurityExpressionHandler http) { http.setDefaultRolePrefix(""); } return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } } }
DefaultRolesPrefixPostProcessor
java
elastic__elasticsearch
x-pack/plugin/core/src/javaRestTest/java/org/elasticsearch/xpack/core/LicenseInstallationIT.java
{ "start": 1559, "end": 8971 }
class ____ extends ESRestTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .setting("xpack.security.enabled", "true") .setting("xpack.license.self_generated.type", "trial") .keystore("bootstrap.password", "x-pack-test-password") .user("x_pack_rest_user", "x-pack-test-password") .systemProperty("es.queryable_built_in_roles_enabled", "false") .build(); @Override protected Settings restClientSettings() { String token = basicAuthHeaderValue("x_pack_rest_user", new SecureString("x-pack-test-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } /** * Resets the license to a valid trial, no matter what state the license is in after each test. */ @Before public void resetLicenseToTrial() throws Exception { License signedTrial = TestUtils.generateSignedLicense("trial", License.VERSION_CURRENT, -1, TimeValue.timeValueDays(14)); Request putTrialRequest = new Request("PUT", "/_license"); XContentBuilder builder = JsonXContent.contentBuilder(); builder = signedTrial.toXContent(builder, ToXContent.EMPTY_PARAMS); putTrialRequest.setJsonEntity("{\"licenses\":[\n " + Strings.toString(builder) + "\n]}"); assertBusy(() -> { Response putLicenseResponse = client().performRequest(putTrialRequest); logger.info("put trial license response when reseting license is [{}]", EntityUtils.toString(putLicenseResponse.getEntity())); assertOK(putLicenseResponse); }); assertClusterUsingTrialLicense(); } /** * Tests that we can install a valid, signed license via the REST API. */ public void testInstallLicense() throws Exception { long futureExpiryDate = System.currentTimeMillis() + TimeValue.timeValueDays(randomIntBetween(1, 1000)).millis(); License signedLicense = generateRandomLicense(UUID.randomUUID().toString(), futureExpiryDate); Request putLicenseRequest = createPutLicenseRequest(signedLicense); Response putLicenseResponse = client().performRequest(putLicenseRequest); assertOK(putLicenseResponse); Map<String, Object> responseMap = entityAsMap(putLicenseResponse); assertThat(responseMap.get("acknowledged").toString().toLowerCase(Locale.ROOT), equalTo("true")); assertThat(responseMap.get("license_status").toString().toLowerCase(Locale.ROOT), equalTo("valid")); Request getLicenseRequest = new Request("GET", "/_license"); Response getLicenseResponse = client().performRequest(getLicenseRequest); @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) entityAsMap(getLicenseResponse).get("license"); assertThat(innerMap.get("status"), equalTo("active")); assertThat(innerMap.get("type"), equalTo(signedLicense.type())); assertThat(innerMap.get("uid"), equalTo(signedLicense.uid())); } /** * Tests that we can try to install an expired license, and that it will be recognized as valid but expired. */ public void testInstallExpiredLicense() throws Exception { // Use a very expired license to avoid any funkiness with e.g. grace periods long pastExpiryDate = System.currentTimeMillis() - TimeValue.timeValueDays(randomIntBetween(30, 1000)).millis(); License signedLicense = generateRandomLicense(UUID.randomUUID().toString(), pastExpiryDate); Request putLicenseRequest = createPutLicenseRequest(signedLicense); Response putLicenseResponse = client().performRequest(putLicenseRequest); assertOK(putLicenseResponse); Map<String, Object> responseMap = entityAsMap(putLicenseResponse); assertThat(responseMap.get("acknowledged").toString().toLowerCase(Locale.ROOT), equalTo("true")); assertThat(responseMap.get("license_status").toString().toLowerCase(Locale.ROOT), equalTo("expired")); assertClusterUsingTrialLicense(); } /** * Tests that license overrides work as expected - i.e. that the override date will be used instead of the date * in the license itself. */ public void testInstallOverriddenExpiredLicense() throws Exception { long futureExpiryDate = System.currentTimeMillis() + TimeValue.timeValueDays(randomIntBetween(1, 1000)).millis(); License signedLicense = generateRandomLicense("12345678-abcd-0000-0000-000000000000", futureExpiryDate); Request putLicenseRequest = createPutLicenseRequest(signedLicense); Response putLicenseResponse = client().performRequest(putLicenseRequest); assertOK(putLicenseResponse); Map<String, Object> responseMap = entityAsMap(putLicenseResponse); assertThat(responseMap.get("acknowledged").toString().toLowerCase(Locale.ROOT), equalTo("true")); assertThat(responseMap.get("license_status").toString().toLowerCase(Locale.ROOT), equalTo("expired")); assertClusterUsingTrialLicense(); } private Request createPutLicenseRequest(License signedLicense) throws IOException { Request putLicenseRequest = new Request("PUT", "/_license"); XContentBuilder xContent = JsonXContent.contentBuilder(); xContent = signedLicense.toXContent(xContent, ToXContent.EMPTY_PARAMS); putLicenseRequest.setJsonEntity("{\"licenses\":[\n " + Strings.toString(xContent) + "\n]}"); putLicenseRequest.addParameter("acknowledge", "true"); return putLicenseRequest; } private License generateRandomLicense(String licenseId, long expiryDate) throws Exception { int version = randomIntBetween(VERSION_NO_FEATURE_TYPE, VERSION_CURRENT); License.LicenseType type = version < VERSION_ENTERPRISE ? randomValueOtherThan(License.LicenseType.ENTERPRISE, () -> randomFrom(LicenseSettings.ALLOWABLE_UPLOAD_TYPES)) : randomFrom(LicenseSettings.ALLOWABLE_UPLOAD_TYPES); final License.Builder builder = License.builder() .uid(licenseId) .version(version) .expiryDate(expiryDate) .issueDate(randomLongBetween(0, System.currentTimeMillis())) .type(type) .issuedTo(this.getTestName() + " customer") .issuer(this.getTestName() + " issuer"); if (type.equals(License.LicenseType.ENTERPRISE)) { builder.maxResourceUnits(randomIntBetween(1, 10000)); } else { builder.maxNodes(randomIntBetween(1, 100)); } License signedLicense = TestUtils.generateSignedLicense(builder); return signedLicense; } private void assertClusterUsingTrialLicense() throws Exception { Request getLicenseRequest = new Request("GET", "/_license"); assertBusy(() -> { Response getLicenseResponse = client().performRequest(getLicenseRequest); @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) entityAsMap(getLicenseResponse).get("license"); assertThat("the cluster should be using a trial license", innerMap.get("type"), equalTo("trial")); }); } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
LicenseInstallationIT
java
quarkusio__quarkus
integration-tests/hibernate-search-orm-opensearch/src/test/java/io/quarkus/it/hibernate/search/orm/opensearch/HibernateSearchOpenSearchTest.java
{ "start": 231, "end": 1252 }
class ____ { @Test public void testSearch() throws Exception { RestAssured.when().put("/test/hibernate-search/init-data").then() .statusCode(204); RestAssured.when().get("/test/hibernate-search/search").then() .statusCode(200) .body(is("OK")); RestAssured.when().put("/test/hibernate-search/purge").then() .statusCode(200) .body(is("OK")); RestAssured.when().put("/test/hibernate-search/refresh").then() .statusCode(200) .body(is("OK")); RestAssured.when().get("/test/hibernate-search/search-empty").then() .statusCode(200); RestAssured.when().put("/test/hibernate-search/mass-indexer").then() .statusCode(200) .body(is("OK")); RestAssured.when().get("/test/hibernate-search/search").then() .statusCode(200) .body(is("OK")); } }
HibernateSearchOpenSearchTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_ignoringCollectionOrder_Test.java
{ "start": 19870, "end": 20894 }
class ____ { String name; Type type; PersonWithEnum(String name, Type type) { this.name = name; this.type = type; } @Override public String toString() { return "Person [name=%s, type=%s]".formatted(name, type); } } @Test public void should_not_remove_already_visited_enum_dual_values_as_they_cant_produce_cycles() { // GIVEN List<PersonWithEnum> persons = list(new PersonWithEnum("name-1", FIRST), new PersonWithEnum("name-2", FIRST), new PersonWithEnum("name-2", SECOND)); // WHEN/THEN assertThat(persons).usingRecursiveComparison(recursiveComparisonConfiguration) .ignoringCollectionOrder() .isEqualTo(list(new PersonWithEnum("name-2", SECOND), new PersonWithEnum("name-2", FIRST), new PersonWithEnum("name-1", FIRST))); } static
PersonWithEnum
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Client.java
{ "start": 11876, "end": 14333 }
class ____ { final int id; // call id final int retry; // retry count final Writable rpcRequest; // the serialized rpc request private final CompletableFuture<Writable> rpcResponseFuture; final RPC.RpcKind rpcKind; // Rpc EngineKind private final Object externalHandler; private AlignmentContext alignmentContext; private Call(RPC.RpcKind rpcKind, Writable param) { this.rpcKind = rpcKind; this.rpcRequest = param; final Integer id = callId.get(); if (id == null) { this.id = nextCallId(); } else { callId.set(null); this.id = id; } final Integer rc = retryCount.get(); if (rc == null) { this.retry = 0; } else { this.retry = rc; } this.externalHandler = EXTERNAL_CALL_HANDLER.get(); this.rpcResponseFuture = new CompletableFuture<>(); } @Override public String toString() { return getClass().getSimpleName() + id; } /** Indicate when the call is complete and the * value or error are available. Notifies by default. */ protected synchronized void callComplete() { if (externalHandler != null) { synchronized (externalHandler) { externalHandler.notify(); } } } /** * Set an AlignmentContext for the call to update when call is done. * * @param ac alignment context to update. */ public synchronized void setAlignmentContext(AlignmentContext ac) { this.alignmentContext = ac; } /** Set the exception when there is an error. * Notify the caller the call is done. * * @param error exception thrown by the call; either local or remote */ public synchronized void setException(IOException error) { rpcResponseFuture.completeExceptionally(error); callComplete(); } /** Set the return value when there is no error. * Notify the caller the call is done. * * @param rpcResponse return value of the rpc call. */ public synchronized void setRpcResponse(Writable rpcResponse) { rpcResponseFuture.complete(rpcResponse); callComplete(); } } /** Thread that reads responses and notifies callers. Each connection owns a * socket connected to a remote address. Calls are multiplexed through this * socket: responses may be delivered out of order. */ private
Call
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/resource/bitmap/GlideBitmapFactory.java
{ "start": 9677, "end": 13258 }
class ____ { /** Transforms a bitmap so that the output alpha is opaque. */ private static final ColorMatrixColorFilter OPAQUE_FILTER = new ColorMatrixColorFilter( new float[] { 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 255f }); private GainmapCopier() {} /** * Converts single channel gainmap to triple channel, where a single channel gainmap is defined * as a gainmap with a bitmap config of {@link Config#ALPHA_8}. * * <p>If the input gainmap is not single channel or the copy operation fails, then this method * will just return the original gainmap. */ public static Gainmap convertSingleChannelGainmapToTripleChannelGainmap(Gainmap gainmap) { Bitmap gainmapContents = gainmap.getGainmapContents(); if (gainmapContents.getConfig() != Config.ALPHA_8) { return gainmap; } Bitmap newContents = copyAlpha8ToOpaqueArgb888(gainmapContents); Gainmap newGainmap = new Gainmap(newContents); float[] tempFloatArray = gainmap.getRatioMin(); newGainmap.setRatioMin(tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]); tempFloatArray = gainmap.getRatioMax(); newGainmap.setRatioMax(tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]); tempFloatArray = gainmap.getGamma(); newGainmap.setGamma(tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]); tempFloatArray = gainmap.getEpsilonSdr(); newGainmap.setEpsilonSdr(tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]); tempFloatArray = gainmap.getEpsilonHdr(); newGainmap.setEpsilonHdr(tempFloatArray[0], tempFloatArray[1], tempFloatArray[2]); newGainmap.setDisplayRatioForFullHdr(gainmap.getDisplayRatioForFullHdr()); newGainmap.setMinDisplayRatioForHdrTransition(gainmap.getMinDisplayRatioForHdrTransition()); return newGainmap; } /** * Converts an {@link Config#ALPHA_8} bitmap to a {@link Config#ARGB_8888} bitmap with the alpha * channel set to unity so that the output bitmap is opaque. * * @throws IllegalArgumentException if called with a bitmap with a config that is not {@link * Config#ALPHA_8} */ private static Bitmap copyAlpha8ToOpaqueArgb888(Bitmap bitmap) { Preconditions.checkArgument(bitmap.getConfig() == Config.ALPHA_8); // We have to use a canvas operation with an opaque alpha filter to draw the gainmap. We can't // use bitmap.copy(Config.ARGB_8888, /* isMutable= */ false) because copying from A8 to RBGA // will result in zero-valued RGB values. Bitmap newContents = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(newContents); Paint paint = new Paint(); paint.setColorFilter(OPAQUE_FILTER); canvas.drawBitmap(bitmap, /* left= */ 0f, /* top= */ 0f, paint); canvas.setBitmap(null); return newContents; } } /** * Determines if a gainmap decoding workaround is required to mitigate an Android U bug with * decoding bitmaps with gainmaps. When the following conditions are present, Android U will not * be able to decode a gainmap, with hardware bitmap operation failing for the gainmap: * * <ul> * <li>The HWUI is configured to use skiagl. * <li>The gainmap is single channel. * <li>The bitmap owning the bitmap is a hardware bitmap. * </ul> * * <p>Callers should use this
GainmapCopier
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/repositories/UnknownTypeRepositoryTests.java
{ "start": 819, "end": 1573 }
class ____ extends ESTestCase { private ProjectId projectId = randomProjectIdOrDefault(); private UnknownTypeRepository repository = new UnknownTypeRepository(projectId, new RepositoryMetadata("name", "type", Settings.EMPTY)); public void testShouldThrowWhenGettingMetadata() { assertThat(repository.getProjectId(), equalTo(projectId)); expectThrows(RepositoryException.class, () -> repository.getSnapshotGlobalMetadata(new SnapshotId("name", "uuid"), false)); } public void testShouldNotThrowWhenApplyingLifecycleChanges() { repository.start(); repository.stop(); } public void testShouldNotThrowWhenClosingToAllowRemovingRepo() { repository.close(); } }
UnknownTypeRepositoryTests
java
grpc__grpc-java
cronet/src/main/java/io/grpc/cronet/InternalCronetCallOptions.java
{ "start": 980, "end": 1725 }
class ____ { // Prevent instantiation private InternalCronetCallOptions() {} public static CallOptions withAnnotation(CallOptions callOptions, Object annotation) { return CronetClientStream.withAnnotation(callOptions, annotation); } /** * Returns Cronet annotations for gRPC included in the given {@code callOptions}. Annotations * are attached via {@link #withAnnotation(CallOptions, Object)}. */ public static Collection<Object> getAnnotations(CallOptions callOptions) { Collection<Object> annotations = callOptions.getOption(CronetClientStream.CRONET_ANNOTATIONS_KEY); if (annotations == null) { annotations = Collections.emptyList(); } return annotations; } }
InternalCronetCallOptions
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/AllowParameterConstraintsOnParallelMethodsTest.java
{ "start": 448, "end": 1399 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap .create(JavaArchive.class) .addClasses(RealizationOfTwoInterface.class, InterfaceWithNoConstraints.class, AnotherInterfaceWithMethodParameterConstraint.class) .add(new StringAsset( "quarkus.hibernate-validator.method-validation.allow-parameter-constraints-on-parallel-methods=true"), "application.properties")); @Inject Validator validator; @Test public void allowParameterConstraintsInHierarchyWithMultipleRootMethods() { validator.forExecutables().validateParameters( new RealizationOfTwoInterface(), RealizationOfTwoInterface.class.getDeclaredMethods()[0], new Object[] { "foo" }); } private
AllowParameterConstraintsOnParallelMethodsTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/SemanticQueryWalker.java
{ "start": 7966, "end": 16969 }
interface ____<T> { T visitUpdateStatement(SqmUpdateStatement<?> statement); T visitSetClause(SqmSetClause setClause); T visitAssignment(SqmAssignment<?> assignment); T visitInsertSelectStatement(SqmInsertSelectStatement<?> statement); T visitInsertValuesStatement(SqmInsertValuesStatement<?> statement); T visitConflictClause(SqmConflictClause<?> sqmConflictClause); T visitDeleteStatement(SqmDeleteStatement<?> statement); T visitSelectStatement(SqmSelectStatement<?> statement); T visitCteStatement(SqmCteStatement<?> sqmCteStatement); T visitCteContainer(SqmCteContainer consumer); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // from-clause / domain paths T visitFromClause(SqmFromClause fromClause); T visitRootPath(SqmRoot<?> sqmRoot); T visitRootDerived(SqmDerivedRoot<?> sqmRoot); T visitRootFunction(SqmFunctionRoot<?> sqmRoot); T visitRootCte(SqmCteRoot<?> sqmRoot); T visitCrossJoin(SqmCrossJoin<?> joinedFromElement); T visitPluralPartJoin(SqmPluralPartJoin<?, ?> joinedFromElement); T visitQualifiedEntityJoin(SqmEntityJoin<?,?> joinedFromElement); T visitQualifiedAttributeJoin(SqmAttributeJoin<?, ?> joinedFromElement); default T visitCorrelatedCteJoin(SqmCorrelatedCteJoin<?> join){ return visitQualifiedCteJoin( join ); } default T visitCorrelatedDerivedJoin(SqmCorrelatedDerivedJoin<?> join){ return visitQualifiedDerivedJoin( join ); } default T visitCorrelatedCrossJoin(SqmCorrelatedCrossJoin<?> join) { return visitCrossJoin( join ); } default T visitCorrelatedEntityJoin(SqmCorrelatedEntityJoin<?,?> join) { return visitQualifiedEntityJoin( join ); } default T visitCorrelatedPluralPartJoin(SqmCorrelatedPluralPartJoin<?, ?> join) { return visitPluralPartJoin( join ); } default T visitBagJoin(SqmBagJoin<?,?> join){ return visitQualifiedAttributeJoin( join ); } default T visitCorrelatedBagJoin(SqmCorrelatedBagJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitCorrelatedListJoin(SqmCorrelatedListJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitCorrelatedMapJoin(SqmCorrelatedMapJoin<?, ?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitCorrelatedSetJoin(SqmCorrelatedSetJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitCorrelatedSingularJoin(SqmCorrelatedSingularJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitListJoin(SqmListJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitMapJoin(SqmMapJoin<?, ?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitSetJoin(SqmSetJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } default T visitSingularJoin(SqmSingularJoin<?, ?> join) { return visitQualifiedAttributeJoin( join ); } T visitQualifiedDerivedJoin(SqmDerivedJoin<?> joinedFromElement); T visitQualifiedFunctionJoin(SqmFunctionJoin<?> joinedFromElement); T visitQualifiedCteJoin(SqmCteJoin<?> joinedFromElement); T visitBasicValuedPath(SqmBasicValuedSimplePath<?> path); T visitEmbeddableValuedPath(SqmEmbeddedValuedSimplePath<?> path); T visitAnyValuedValuedPath(SqmAnyValuedSimplePath<?> path); T visitNonAggregatedCompositeValuedPath(NonAggregatedCompositeSimplePath<?> path); T visitEntityValuedPath(SqmEntityValuedSimplePath<?> path); T visitPluralValuedPath(SqmPluralValuedSimplePath<?> path); T visitFkExpression(SqmFkExpression<?> fkExpression); T visitDiscriminatorPath(DiscriminatorSqmPath<?> sqmPath); T visitIndexedPluralAccessPath(SqmIndexedCollectionAccessPath<?> path); T visitElementAggregateFunction(SqmElementAggregateFunction<?> path); T visitIndexAggregateFunction(SqmIndexAggregateFunction<?> path); T visitFunctionPath(SqmFunctionPath<?> functionPath); T visitTreatedPath(SqmTreatedPath<?, @Nullable ?> sqmTreatedPath); T visitCorrelation(SqmCorrelation<?, ?> correlation); default T visitCorrelatedRootJoin(SqmCorrelatedRootJoin<?> correlatedRootJoin){ return visitCorrelation( correlatedRootJoin ); } default T visitCorrelatedRoot(SqmCorrelatedRoot<?> correlatedRoot){ return visitCorrelation( correlatedRoot ); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Query spec T visitQueryGroup(SqmQueryGroup<?> queryGroup); T visitQuerySpec(SqmQuerySpec<?> querySpec); T visitSelectClause(SqmSelectClause selectClause); T visitSelection(SqmSelection<?> selection); T visitValues(SqmValues values); T visitGroupByClause(List<SqmExpression<?>> groupByClauseExpressions); T visitHavingClause(SqmPredicate clause); T visitDynamicInstantiation(SqmDynamicInstantiation<?> sqmDynamicInstantiation); T visitJpaCompoundSelection(SqmJpaCompoundSelection<?> selection); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // expressions - general T visitLiteral(SqmLiteral<?> literal); T visitEnumLiteral(SqmEnumLiteral<?> sqmEnumLiteral); T visitFieldLiteral(SqmFieldLiteral<?> sqmFieldLiteral); <N extends Number> T visitHqlNumericLiteral(SqmHqlNumericLiteral<N> numericLiteral); T visitTuple(SqmTuple<?> sqmTuple); T visitCollation(SqmCollation sqmCollate); T visitBinaryArithmeticExpression(SqmBinaryArithmetic<?> expression); T visitSubQueryExpression(SqmSubQuery<?> expression); T visitModifiedSubQueryExpression(SqmModifiedSubQueryExpression<?> expression); T visitSimpleCaseExpression(SqmCaseSimple<?, ?> expression); T visitSearchedCaseExpression(SqmCaseSearched<?> expression); T visitAny(SqmAny<?> sqmAny); T visitEvery(SqmEvery<?> sqmEvery); T visitSummarization(SqmSummarization<?> sqmSummarization); T visitPositionalParameterExpression(SqmPositionalParameter<?> expression); T visitNamedParameterExpression(SqmNamedParameter<?> expression); T visitJpaCriteriaParameter(JpaCriteriaParameter<?> expression); T visitEntityTypeLiteralExpression(SqmLiteralEntityType<?> expression); T visitEmbeddableTypeLiteralExpression(SqmLiteralEmbeddableType<?> expression); T visitAnyDiscriminatorTypeExpression(AnyDiscriminatorSqmPath<?> expression); T visitAnyDiscriminatorTypeValueExpression(SqmAnyDiscriminatorValue<?> expression); T visitParameterizedEntityTypeExpression(SqmParameterizedEntityType<?> expression); T visitUnaryOperationExpression(SqmUnaryOperation<?> expression); T visitFunction(SqmFunction<?> tSqmFunction); T visitSetReturningFunction(SqmSetReturningFunction<?> tSqmFunction); T visitExtractUnit(SqmExtractUnit<?> extractUnit); T visitFormat(SqmFormat sqmFormat); T visitCastTarget(SqmCastTarget<?> sqmCastTarget); T visitTrimSpecification(SqmTrimSpecification trimSpecification); T visitDistinct(SqmDistinct<?> distinct); T visitStar(SqmStar sqmStar); T visitOver(SqmOver<?> over); T visitWindow(SqmWindow widow); T visitOverflow(SqmOverflow<?> sqmOverflow); T visitCoalesce(SqmCoalesce<?> sqmCoalesce); T visitToDuration(SqmToDuration<?> toDuration); T visitByUnit(SqmByUnit sqmByUnit); T visitDurationUnit(SqmDurationUnit<?> durationUnit); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // predicates T visitWhereClause(@Nullable SqmWhereClause whereClause); T visitGroupedPredicate(SqmGroupedPredicate predicate); T visitJunctionPredicate(SqmJunctionPredicate predicate); T visitComparisonPredicate(SqmComparisonPredicate predicate); T visitIsEmptyPredicate(SqmEmptinessPredicate predicate); T visitIsNullPredicate(SqmNullnessPredicate predicate); T visitIsTruePredicate(SqmTruthnessPredicate predicate); T visitBetweenPredicate(SqmBetweenPredicate predicate); T visitLikePredicate(SqmLikePredicate predicate); T visitMemberOfPredicate(SqmMemberOfPredicate predicate); T visitNegatedPredicate(SqmNegatedPredicate predicate); T visitInListPredicate(SqmInListPredicate<?> predicate); T visitInSubQueryPredicate(SqmInSubQueryPredicate<?> predicate); T visitBooleanExpressionPredicate(SqmBooleanExpressionPredicate predicate); T visitExistsPredicate(SqmExistsPredicate sqmExistsPredicate); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorting T visitOrderByClause(SqmOrderByClause orderByClause); T visitSortSpecification(SqmSortSpecification sortSpecification); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // paging T visitOffsetExpression(SqmExpression<?> expression); T visitFetchExpression(SqmExpression<?> expression); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // misc T visitPluralAttributeSizeFunction(SqmCollectionSize function); T visitMapEntryFunction(SqmMapEntryReference<?, ?> function); T visitFullyQualifiedClass(Class<?> namedClass); T visitAsWrapperExpression(AsWrapperSqmExpression<?> expression); T visitNamedExpression(SqmNamedExpression<?> expression); }
SemanticQueryWalker
java
hibernate__hibernate-orm
hibernate-vector/src/main/java/org/hibernate/vector/internal/MariaDBJdbcLiteralFormatterVector.java
{ "start": 468, "end": 1321 }
class ____<T> extends BasicJdbcLiteralFormatter<T> { private final JdbcLiteralFormatter<Object> elementFormatter; public MariaDBJdbcLiteralFormatterVector(JavaType<T> javaType, JdbcLiteralFormatter<?> elementFormatter) { super( javaType ); //noinspection unchecked this.elementFormatter = (JdbcLiteralFormatter<Object>) elementFormatter; } @Override public void appendJdbcLiteral(SqlAppender appender, T value, Dialect dialect, WrapperOptions wrapperOptions) { final Object[] objects = unwrap( value, Object[].class, wrapperOptions ); appender.appendSql( "vec_fromtext('" ); char separator = '['; for ( Object o : objects ) { appender.appendSql( separator ); elementFormatter.appendJdbcLiteral( appender, o, dialect, wrapperOptions ); separator = ','; } appender.appendSql( "]')" ); } }
MariaDBJdbcLiteralFormatterVector
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/SnapshotTestHelper.java
{ "start": 5202, "end": 9718 }
class ____ { private final MiniDFSCluster cluster; private final FSNamesystem fsn; private final FSDirectory fsdir; private final DistributedFileSystem hdfs; private final FsShell shell = new FsShell(); private final Path snapshotDir = new Path("/"); private final AtomicInteger snapshotCount = new AtomicInteger(); private final AtomicInteger trashMoveCount = new AtomicInteger(); private final AtomicInteger printTreeCount = new AtomicInteger(); private final AtomicBoolean printTree = new AtomicBoolean(); MyCluster(Configuration conf) throws Exception { cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(1) .format(true) .build(); fsn = cluster.getNamesystem(); fsdir = fsn.getFSDirectory(); cluster.waitActive(); hdfs = cluster.getFileSystem(); hdfs.allowSnapshot(snapshotDir); createSnapshot(); shell.setConf(cluster.getConfiguration(0)); runShell("-mkdir", "-p", ".Trash"); } void setPrintTree(boolean print) { printTree.set(print); } boolean getPrintTree() { return printTree.get(); } Path getTrashPath(Path p) throws Exception { final Path trash = hdfs.getTrashRoot(p); final Path resolved = hdfs.resolvePath(p); return new Path(trash, "Current/" + resolved.toUri().getPath()); } int runShell(String... argv) { return shell.run(argv); } String createSnapshot() throws Exception { final String name = "s" + snapshotCount.getAndIncrement(); SnapshotTestHelper.createSnapshot(hdfs, snapshotDir, name); return name; } void deleteSnapshot(String snapshotName) throws Exception { LOG.info("Before delete snapshot " + snapshotName); hdfs.deleteSnapshot(snapshotDir, snapshotName); } boolean assertExists(Path path) throws Exception { if (path == null) { return false; } if (!hdfs.exists(path)) { final String err = "Path not found: " + path; printFs(err); throw new AssertionError(err); } return true; } void printFs(String label) { final PrintStream out = System.out; out.println(); out.println(); out.println("XXX " + printTreeCount.getAndIncrement() + ": " + label); if (printTree.get()) { fsdir.getRoot().dumpTreeRecursively(out); } } void shutdown() { LOG.info("snapshotCount: {}", snapshotCount); cluster.shutdown(); } Path mkdirs(String dir) throws Exception { return mkdirs(new Path(dir)); } Path mkdirs(Path dir) throws Exception { final String label = "mkdirs " + dir; LOG.info(label); hdfs.mkdirs(dir); assertTrue(hdfs.exists(dir), label); return dir; } Path createFile(String file) throws Exception { return createFile(new Path(file)); } Path createFile(Path file) throws Exception { final String label = "createFile " + file; LOG.info(label); DFSTestUtil.createFile(hdfs, file, 0, (short)1, 0L); assertTrue(hdfs.exists(file), label); return file; } String rename(Path src, Path dst) throws Exception { assertExists(src); final String snapshot = createSnapshot(); final String label = "rename " + src + " -> " + dst; final boolean renamed = hdfs.rename(src, dst); LOG.info("{}: success? {}", label, renamed); assertTrue(renamed, label); return snapshot; } Path moveToTrash(Path path, boolean printFs) throws Exception { return moveToTrash(path.toString(), printFs); } Path moveToTrash(String path, boolean printFs) throws Exception { final Log4jRecorder recorder = Log4jRecorder.record( LoggerFactory.getLogger(TrashPolicyDefault.class)); runShell("-rm", "-r", path); final String label = "moveToTrash-" + trashMoveCount.getAndIncrement() + " " + path; if (printFs) { printFs(label); } else { LOG.info(label); } final String recorded = recorder.getRecorded(); LOG.info("Recorded: {}", recorded); final String pattern = " to trash at: "; final int i = recorded.indexOf(pattern); if (i > 0) { final String sub = recorded.substring(i + pattern.length()); return new Path(sub.trim()); } return null; } } /** Records log messages from a Log4j logger. */ public static final
MyCluster
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/shortarrays/ShortArrays_assertContainsSequence_Test.java
{ "start": 1698, "end": 8012 }
class ____ extends ShortArraysBaseTest { @Override protected void initActualArray() { actual = arrayOf(6, 8, 10, 12); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsSequence(someInfo(), null, arrayOf(8))) .withMessage(actualIsNull()); } @Test void should_throw_error_if_sequence_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertContainsSequence(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_pass_if_actual_and_given_values_are_empty() { actual = emptyArray(); arrays.assertContainsSequence(someInfo(), actual, emptyArray()); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContainsSequence(someInfo(), actual, emptyArray())); } @Test void should_fail_if_sequence_is_bigger_than_actual() { AssertionInfo info = someInfo(); short[] sequence = { 6, 8, 10, 12, 20, 22 }; Throwable error = catchThrowable(() -> arrays.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verifyFailureThrownWhenSequenceNotFound(info, sequence); } @Test void should_fail_if_actual_does_not_contain_whole_sequence() { AssertionInfo info = someInfo(); short[] sequence = { 6, 20 }; Throwable error = catchThrowable(() -> arrays.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verifyFailureThrownWhenSequenceNotFound(info, sequence); } @Test void should_fail_if_actual_contains_first_elements_of_sequence() { AssertionInfo info = someInfo(); short[] sequence = { 6, 20, 22 }; Throwable error = catchThrowable(() -> arrays.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verifyFailureThrownWhenSequenceNotFound(info, sequence); } private void verifyFailureThrownWhenSequenceNotFound(AssertionInfo info, short[] sequence) { verify(failures).failure(info, shouldContainSequence(actual, sequence)); } @Test void should_pass_if_actual_contains_sequence() { arrays.assertContainsSequence(someInfo(), actual, arrayOf(6, 8)); } @Test void should_pass_if_actual_and_sequence_are_equal() { arrays.assertContainsSequence(someInfo(), actual, arrayOf(6, 8, 10, 12)); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(someInfo(), null, arrayOf(-8))) .withMessage(actualIsNull()); } @Test void should_throw_error_if_sequence_is_null_whatever_custom_comparison_strategy_is() { assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(someInfo(), actual, emptyArray())); } @Test void should_fail_if_sequence_is_bigger_than_actual_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); short[] sequence = { 6, -8, 10, 12, 20, 22 }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainSequence(actual, sequence, absValueComparisonStrategy)); } @Test void should_fail_if_actual_does_not_contain_whole_sequence_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); short[] sequence = { 6, 20 }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainSequence(actual, sequence, absValueComparisonStrategy)); } @Test void should_fail_if_actual_contains_first_elements_of_sequence_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); short[] sequence = { 6, 20, 22 }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertContainsSequence(info, actual, sequence)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldContainSequence(actual, sequence, absValueComparisonStrategy)); } @Test void should_pass_if_actual_contains_sequence_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContainsSequence(someInfo(), actual, arrayOf(6, -8)); } @Test void should_pass_if_actual_and_sequence_are_equal_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContainsSequence(someInfo(), actual, arrayOf(6, -8, 10, 12)); } }
ShortArrays_assertContainsSequence_Test
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/csrf/CsrfTokenRequestAttributeHandler.java
{ "start": 2964, "end": 3695 }
class ____ implements CsrfToken { private final Supplier<CsrfToken> csrfTokenSupplier; private SupplierCsrfToken(Supplier<CsrfToken> csrfTokenSupplier) { this.csrfTokenSupplier = csrfTokenSupplier; } @Override public String getHeaderName() { return getDelegate().getHeaderName(); } @Override public String getParameterName() { return getDelegate().getParameterName(); } @Override public String getToken() { return getDelegate().getToken(); } private CsrfToken getDelegate() { CsrfToken delegate = this.csrfTokenSupplier.get(); if (delegate == null) { throw new IllegalStateException("csrfTokenSupplier returned null delegate"); } return delegate; } } }
SupplierCsrfToken
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-jpa/src/main/java/smoketest/data/jpa/service/ReviewsSummary.java
{ "start": 712, "end": 794 }
interface ____ { long getNumberOfReviewsWithRating(Rating rating); }
ReviewsSummary
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/Db2PartitionedTableTest.java
{ "start": 696, "end": 1304 }
class ____ { @Test void test(EntityManagerFactoryScope scope) { scope.inTransaction( session -> { Partitioned partitioned = new Partitioned(); partitioned.id = 1L; partitioned.pid = 500L; session.persist( partitioned ); } ); scope.inTransaction( session -> { Partitioned partitioned = session.find( Partitioned.class, 1L ); assertNotNull( partitioned ); partitioned.text = "updated"; } ); } @Entity @Table(name = "db2parts", options = """ PARTITION BY RANGE (pid) ( STARTING FROM (0) ENDING AT (1000), ENDING AT (2000) ) """) static
Db2PartitionedTableTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskmanager/TaskExecutionStateTest.java
{ "start": 1478, "end": 3656 }
class ____ { @Test public void testEqualsHashCode() { try { final ExecutionAttemptID executionId = createExecutionAttemptId(); final ExecutionState state = ExecutionState.RUNNING; final Throwable error = new RuntimeException("some test error message"); TaskExecutionState s1 = new TaskExecutionState(executionId, state, error); TaskExecutionState s2 = new TaskExecutionState(executionId, state, error); assertEquals(s1.hashCode(), s2.hashCode()); assertEquals(s1, s2); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testSerialization() { try { final ExecutionAttemptID executionId = createExecutionAttemptId(); final ExecutionState state = ExecutionState.DEPLOYING; final Throwable error = new IOException("fubar"); TaskExecutionState original1 = new TaskExecutionState(executionId, state, error); TaskExecutionState original2 = new TaskExecutionState(executionId, state); TaskExecutionState javaSerCopy1 = CommonTestUtils.createCopySerializable(original1); TaskExecutionState javaSerCopy2 = CommonTestUtils.createCopySerializable(original2); // equalities assertEquals(original1, javaSerCopy1); assertEquals(javaSerCopy1, original1); assertEquals(original2, javaSerCopy2); assertEquals(javaSerCopy2, original2); // hash codes assertEquals(original1.hashCode(), javaSerCopy1.hashCode()); assertEquals(original2.hashCode(), javaSerCopy2.hashCode()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void handleNonSerializableException() { try { @SuppressWarnings({"ThrowableInstanceNeverThrown", "serial"}) Exception hostile = new Exception() { // should be non serializable, because it contains the outer
TaskExecutionStateTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/generic/ManyToManyGenericTest.java
{ "start": 2216, "end": 2907 }
class ____<T> { @Id @GeneratedValue(strategy = GenerationType.UUID) public UUID id; @ManyToOne(optional = false) @JoinColumn(name = "TREE_ID") public NodeTree tree; @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.DETACH}) @JoinTable(name = "NODE_CHILDREN", joinColumns = {@JoinColumn(name = "TREE_ID", referencedColumnName = "TREE_ID"), @JoinColumn(name = "NODE_ID", referencedColumnName = "ID")}, inverseJoinColumns = {@JoinColumn(name = "CHILD_ID", referencedColumnName = "ID")} ) private final Set<GenericNode<?>> children = new HashSet<>(); public Set<GenericNode<?>> getChildren() { return children; } } }
GenericNode
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/RunningQuarkusApplication.java
{ "start": 110, "end": 631 }
interface ____ extends AutoCloseable { ClassLoader getClassLoader(); @Override void close() throws Exception; <T> Optional<T> getConfigValue(String key, Class<T> type); Iterable<String> getConfigKeys(); /** * Looks up an instance from the CDI container of the running application. * * @param clazz The class * @param qualifiers The qualifiers * @return The instance or null */ Object instance(Class<?> clazz, Annotation... qualifiers); }
RunningQuarkusApplication
java
apache__camel
components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/agent/BedrockAgentProducer.java
{ "start": 1548, "end": 12544 }
class ____ extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(BedrockAgentProducer.class); private transient String bedrockAgentProducerToString; public BedrockAgentProducer(Endpoint endpoint) { super(endpoint); } @Override public void process(Exchange exchange) throws Exception { switch (determineOperation(exchange)) { case startIngestionJob: startIngestionJob(getEndpoint().getBedrockAgentClient(), exchange); break; case listIngestionJobs: listIngestionJobs(getEndpoint().getBedrockAgentClient(), exchange); break; case getIngestionJob: getIngestionJob(getEndpoint().getBedrockAgentClient(), exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } private BedrockAgentOperations determineOperation(Exchange exchange) { BedrockAgentOperations operation = exchange.getIn().getHeader(BedrockAgentConstants.OPERATION, BedrockAgentOperations.class); if (operation == null) { operation = getConfiguration().getOperation(); } return operation; } protected BedrockAgentConfiguration getConfiguration() { return getEndpoint().getConfiguration(); } @Override public String toString() { if (bedrockAgentProducerToString == null) { bedrockAgentProducerToString = "BedrockAgentProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } return bedrockAgentProducerToString; } @Override public BedrockAgentEndpoint getEndpoint() { return (BedrockAgentEndpoint) super.getEndpoint(); } private void startIngestionJob(BedrockAgentClient bedrockAgentClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); if (payload instanceof StartIngestionJobRequest) { StartIngestionJobResponse result; try { result = bedrockAgentClient.startIngestionJob((StartIngestionJobRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Start Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); prepareIngestionJobResponse(result, message); } } else { String knowledgeBaseId; String dataSourceId; StartIngestionJobRequest.Builder builder = StartIngestionJobRequest.builder(); if (ObjectHelper.isEmpty(getConfiguration().getKnowledgeBaseId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID))) { knowledgeBaseId = exchange.getIn().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID, String.class); } else { throw new IllegalArgumentException("KnowledgeBaseId must be specified"); } } else { knowledgeBaseId = getConfiguration().getKnowledgeBaseId(); } if (ObjectHelper.isEmpty(getConfiguration().getDataSourceId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.DATASOURCE_ID))) { dataSourceId = exchange.getIn().getHeader(BedrockAgentConstants.DATASOURCE_ID, String.class); } else { throw new IllegalArgumentException("DataSourceId must be specified"); } } else { dataSourceId = getConfiguration().getDataSourceId(); } builder.knowledgeBaseId(knowledgeBaseId); builder.dataSourceId(dataSourceId); StartIngestionJobResponse output = bedrockAgentClient.startIngestionJob(builder.build()); Message message = getMessageForResponse(exchange); prepareIngestionJobResponse(output, message); } } private void listIngestionJobs(BedrockAgentClient bedrockAgentClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); if (payload instanceof ListIngestionJobsRequest) { ListIngestionJobsResponse result; try { result = bedrockAgentClient.listIngestionJobs((ListIngestionJobsRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Start Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); prepareListIngestionJobsResponse(result, message); } } else { String knowledgeBaseId; String dataSourceId; ListIngestionJobsRequest.Builder builder = ListIngestionJobsRequest.builder(); if (ObjectHelper.isEmpty(getConfiguration().getKnowledgeBaseId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID))) { knowledgeBaseId = exchange.getIn().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID, String.class); } else { throw new IllegalArgumentException("KnowledgeBaseId must be specified"); } } else { knowledgeBaseId = getConfiguration().getKnowledgeBaseId(); } if (ObjectHelper.isEmpty(getConfiguration().getDataSourceId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.DATASOURCE_ID))) { dataSourceId = exchange.getIn().getHeader(BedrockAgentConstants.DATASOURCE_ID, String.class); } else { throw new IllegalArgumentException("DataSourceId must be specified"); } } else { dataSourceId = getConfiguration().getDataSourceId(); } builder.knowledgeBaseId(knowledgeBaseId); builder.dataSourceId(dataSourceId); ListIngestionJobsResponse output = bedrockAgentClient.listIngestionJobs(builder.build()); Message message = getMessageForResponse(exchange); prepareListIngestionJobsResponse(output, message); } } private void getIngestionJob(BedrockAgentClient bedrockAgentClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { Object payload = exchange.getMessage().getMandatoryBody(); if (payload instanceof GetIngestionJobRequest) { GetIngestionJobResponse result; try { result = bedrockAgentClient.getIngestionJob((GetIngestionJobRequest) payload); } catch (AwsServiceException ase) { LOG.trace("Get Ingestion Job command returned the error code {}", ase.awsErrorDetails().errorCode()); throw ase; } Message message = getMessageForResponse(exchange); prepareGetIngestionJobResponse(result, message); } } else { String knowledgeBaseId; String dataSourceId; String ingestionJobId; GetIngestionJobRequest.Builder builder = GetIngestionJobRequest.builder(); if (ObjectHelper.isEmpty(getConfiguration().getKnowledgeBaseId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID))) { knowledgeBaseId = exchange.getMessage().getHeader(BedrockAgentConstants.KNOWLEDGE_BASE_ID, String.class); } else { throw new IllegalArgumentException("KnowledgeBaseId must be specified"); } } else { knowledgeBaseId = getConfiguration().getKnowledgeBaseId(); } if (ObjectHelper.isEmpty(getConfiguration().getDataSourceId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.DATASOURCE_ID))) { dataSourceId = exchange.getMessage().getHeader(BedrockAgentConstants.DATASOURCE_ID, String.class); } else { throw new IllegalArgumentException("DataSourceId must be specified"); } } else { dataSourceId = getConfiguration().getDataSourceId(); } if (ObjectHelper.isEmpty(getConfiguration().getIngestionJobId())) { if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(BedrockAgentConstants.INGESTION_JOB_ID))) { ingestionJobId = exchange.getMessage().getHeader(BedrockAgentConstants.INGESTION_JOB_ID, String.class); } else { throw new IllegalArgumentException("IngestionJobId must be specified"); } } else { ingestionJobId = getConfiguration().getIngestionJobId(); } builder.knowledgeBaseId(knowledgeBaseId); builder.dataSourceId(dataSourceId); builder.ingestionJobId(ingestionJobId); GetIngestionJobResponse output = bedrockAgentClient.getIngestionJob(builder.build()); Message message = getMessageForResponse(exchange); prepareGetIngestionJobResponse(output, message); } } private void prepareIngestionJobResponse(StartIngestionJobResponse result, Message message) { message.setBody(result.ingestionJob().ingestionJobId()); } private void prepareListIngestionJobsResponse(ListIngestionJobsResponse result, Message message) { if (result.hasIngestionJobSummaries()) { message.setBody(result.ingestionJobSummaries()); } } private void prepareGetIngestionJobResponse(GetIngestionJobResponse result, Message message) { message.setBody(result.ingestionJob()); message.setHeader(BedrockAgentConstants.INGESTION_JOB_STATUS, result.ingestionJob().status()); if (result.ingestionJob().hasFailureReasons()) { message.setHeader(BedrockAgentConstants.INGESTION_JOB_FAILURE_REASONS, result.ingestionJob().failureReasons()); } } public static Message getMessageForResponse(final Exchange exchange) { return exchange.getMessage(); } }
BedrockAgentProducer
java
apache__camel
components/camel-mllp/src/test/java/org/apache/camel/test/junit/rule/mllp/MllpServerResource.java
{ "start": 1688, "end": 21754 }
class ____ implements BeforeEachCallback, AfterEachCallback { Logger log = LoggerFactory.getLogger(this.getClass()); String listenHost; int listenPort; int backlog = 5; int counter = 1; boolean active = true; int delayBeforeStartOfBlock; int delayBeforeAcknowledgement; int delayDuringAcknowledgement; int delayAfterAcknowledgement; int delayAfterEndOfBlock; int excludeStartOfBlockModulus; int excludeEndOfBlockModulus; int excludeEndOfDataModulus; int excludeAcknowledgementModulus; int sendOutOfBandDataModulus; int closeSocketBeforeAcknowledgementModulus; int closeSocketAfterAcknowledgementModulus; int resetSocketBeforeAcknowledgementModulus; int resetSocketAfterAcknowledgementModulus; int sendApplicationRejectAcknowledgementModulus; int sendApplicationErrorAcknowledgementModulus; Pattern sendApplicationRejectAcknowledgementPattern; Pattern sendApplicationErrorAcknowledgementPattern; String acknowledgementString; AcceptSocketThread acceptSocketThread; public MllpServerResource() { } public MllpServerResource(int listenPort) { this.listenPort = listenPort; } public MllpServerResource(int listenPort, int backlog) { this.listenPort = listenPort; this.backlog = backlog; } public MllpServerResource(String listenHost, int listenPort) { this.listenHost = listenHost; this.listenPort = listenPort; } public MllpServerResource(String listenHost, int listenPort, int backlog) { this.listenHost = listenHost; this.listenPort = listenPort; this.backlog = backlog; } public String getListenHost() { return listenHost; } public void setListenHost(String listenHost) { this.listenHost = listenHost; } public int getListenPort() { return listenPort; } public void setListenPort(int listenPort) { this.listenPort = listenPort; } public int getBacklog() { return backlog; } public void setBacklog(int backlog) { this.backlog = backlog; } public void startup() throws IOException { this.active = true; if (null != listenHost) { acceptSocketThread = new AcceptSocketThread(listenHost, listenPort, backlog); } else { acceptSocketThread = new AcceptSocketThread(listenPort, backlog); listenHost = acceptSocketThread.getListenHost(); } if (0 >= listenPort) { listenPort = acceptSocketThread.listenPort; } acceptSocketThread.setDaemon(true); acceptSocketThread.start(); } public void shutdown() { this.active = false; if (acceptSocketThread != null) { acceptSocketThread.shutdown(); acceptSocketThread = null; } } @Override public void beforeEach(ExtensionContext context) throws Exception { startup(); } @Override public void afterEach(ExtensionContext context) { shutdown(); } public void interrupt() { acceptSocketThread.interrupt(); } public int getDelayBeforeStartOfBlock() { return delayBeforeStartOfBlock; } public void setDelayBeforeStartOfBlock(int delayBeforeStartOfBlock) { this.delayBeforeStartOfBlock = delayBeforeStartOfBlock; } public int getDelayBeforeAcknowledgement() { return delayBeforeAcknowledgement; } public void setDelayBeforeAcknowledgement(int delayBeforeAcknowledgement) { this.delayBeforeAcknowledgement = delayBeforeAcknowledgement; } public int getDelayDuringAcknowledgement() { return delayDuringAcknowledgement; } public void setDelayDuringAcknowledgement(int delayDuringAcknowledgement) { this.delayDuringAcknowledgement = delayDuringAcknowledgement; } public int getDelayAfterAcknowledgement() { return delayAfterAcknowledgement; } public void setDelayAfterAcknowledgement(int delayAfterAcknowledgement) { this.delayAfterAcknowledgement = delayAfterAcknowledgement; } public int getDelayAfterEndOfBlock() { return delayAfterEndOfBlock; } public void setDelayAfterEndOfBlock(int delayAfterEndOfBlock) { this.delayAfterEndOfBlock = delayAfterEndOfBlock; } public boolean sendApplicationRejectAcknowledgement(String hl7Message) { return evaluatePattern(hl7Message, this.sendApplicationErrorAcknowledgementPattern); } public boolean sendApplicationErrorAcknowledgement(String hl7Message) { return evaluatePattern(hl7Message, this.sendApplicationRejectAcknowledgementPattern); } public boolean sendApplicationRejectAcknowledgement(int messageCount) { return evaluateModulus(messageCount, this.sendApplicationRejectAcknowledgementModulus); } public boolean sendApplicationErrorAcknowledgement(int messageCount) { return evaluateModulus(messageCount, this.sendApplicationErrorAcknowledgementModulus); } public boolean excludeStartOfBlock(int messageCount) { return evaluateModulus(messageCount, excludeStartOfBlockModulus); } public boolean excludeAcknowledgement(int messageCount) { return evaluateModulus(messageCount, excludeAcknowledgementModulus); } public boolean excludeEndOfBlock(int messageCount) { return evaluateModulus(messageCount, excludeEndOfBlockModulus); } public boolean excludeEndOfData(int messageCount) { return evaluateModulus(messageCount, excludeEndOfDataModulus); } public boolean closeSocketBeforeAcknowledgement(int messageCount) { return evaluateModulus(messageCount, closeSocketBeforeAcknowledgementModulus); } public boolean closeSocketAfterAcknowledgement(int messageCount) { return evaluateModulus(messageCount, closeSocketAfterAcknowledgementModulus); } public boolean resetSocketBeforeAcknowledgement(int messageCount) { return evaluateModulus(messageCount, resetSocketBeforeAcknowledgementModulus); } public boolean resetSocketAfterAcknowledgement(int messageCount) { return evaluateModulus(messageCount, resetSocketAfterAcknowledgementModulus); } public boolean sendOutOfBandData(int messageCount) { return evaluateModulus(messageCount, sendOutOfBandDataModulus); } private boolean evaluateModulus(int messageCount, int modulus) { switch (modulus) { case 0: return false; case 1: return true; default: return messageCount % modulus == 0; } } private boolean evaluatePattern(String hl7Message, Pattern pattern) { boolean retValue = false; if (null != pattern && pattern.matcher(hl7Message).matches()) { retValue = true; } return retValue; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public int getExcludeStartOfBlockModulus() { return excludeStartOfBlockModulus; } /** * Set the modulus used to determine when to include the START_OF_BLOCK portion of the MLLP Envelope. * <p/> * If this value is less than or equal to 0, the START_OF_BLOCK portion of the MLLP Envelope will always be * included. If the value is 1, the START_OF_BLOCK portion of the MLLP Envelope will never be included. Otherwise, * if the result of evaluating message availableByteCount % value is greater than 0, the START_OF_BLOCK portion of * the MLLP Envelope will not be included. Effectively leaving the START_OF_BLOCK portion of the MLLP Envelope out * of every n-th message. * * @param excludeStartOfBlockModulus exclude on every n-th message 0 => Never excluded 1 => Always excluded */ public void setExcludeStartOfBlockModulus(int excludeStartOfBlockModulus) { if (0 > excludeStartOfBlockModulus) { this.excludeStartOfBlockModulus = 0; } else { this.excludeStartOfBlockModulus = excludeStartOfBlockModulus; } } public void enableMllpEnvelope() { this.setExcludeStartOfBlockModulus(0); this.setExcludeEndOfBlockModulus(0); this.setExcludeEndOfDataModulus(0); } public void disableMllpEnvelopeStart() { this.disableMllpEnvelopeStart(1); } public void disableMllpEnvelopeStart(int mllpEnvelopeModulus) { this.setExcludeStartOfBlockModulus(mllpEnvelopeModulus); } public void disableMllpEnvelopeEnd() { this.disableMllpEnvelope(1); } public void disableMllpEnvelopeEnd(int mllpEnvelopeModulus) { this.setExcludeEndOfBlockModulus(mllpEnvelopeModulus); this.setExcludeEndOfDataModulus(mllpEnvelopeModulus); } public void disableMllpEnvelope() { this.disableMllpEnvelope(1); } public void disableMllpEnvelope(int mllpEnvelopeModulus) { this.setExcludeStartOfBlockModulus(mllpEnvelopeModulus); this.setExcludeEndOfBlockModulus(mllpEnvelopeModulus); this.setExcludeEndOfDataModulus(mllpEnvelopeModulus); } public void enableResponse() { this.setExcludeStartOfBlockModulus(0); this.setExcludeAcknowledgementModulus(0); this.setExcludeEndOfBlockModulus(0); this.setExcludeEndOfDataModulus(0); } public void disableResponse() { this.disableResponse(1); } public void disableResponse(int mllpResponseModulus) { this.setExcludeStartOfBlockModulus(mllpResponseModulus); this.setExcludeAcknowledgementModulus(mllpResponseModulus); this.setExcludeEndOfBlockModulus(mllpResponseModulus); this.setExcludeEndOfDataModulus(mllpResponseModulus); } public int getExcludeEndOfBlockModulus() { return excludeEndOfBlockModulus; } public void setExcludeEndOfBlockModulus(int excludeEndOfBlockModulus) { if (0 > excludeEndOfBlockModulus) { this.excludeEndOfBlockModulus = 0; } else { this.excludeEndOfBlockModulus = excludeEndOfBlockModulus; } } public int getExcludeEndOfDataModulus() { return excludeEndOfDataModulus; } public void setExcludeEndOfDataModulus(int excludeEndOfDataModulus) { if (0 > excludeEndOfDataModulus) { this.excludeEndOfDataModulus = 0; } else { this.excludeEndOfDataModulus = excludeEndOfDataModulus; } } public int getExcludeAcknowledgementModulus() { return excludeAcknowledgementModulus; } public void setExcludeAcknowledgementModulus(int excludeAcknowledgementModulus) { if (0 > excludeAcknowledgementModulus) { this.excludeAcknowledgementModulus = 0; } else { this.excludeAcknowledgementModulus = excludeAcknowledgementModulus; } } public int getSendOutOfBandDataModulus() { return sendOutOfBandDataModulus; } public void setSendOutOfBandDataModulus(int sendOutOfBandDataModulus) { if (0 > sendOutOfBandDataModulus) { this.sendOutOfBandDataModulus = 0; } else { this.sendOutOfBandDataModulus = sendOutOfBandDataModulus; } } public int getCloseSocketBeforeAcknowledgementModulus() { return closeSocketBeforeAcknowledgementModulus; } public void setCloseSocketBeforeAcknowledgementModulus(int closeSocketBeforeAcknowledgementModulus) { if (0 > closeSocketBeforeAcknowledgementModulus) { this.closeSocketBeforeAcknowledgementModulus = 0; } else { this.closeSocketBeforeAcknowledgementModulus = closeSocketBeforeAcknowledgementModulus; } } public int getCloseSocketAfterAcknowledgementModulus() { return closeSocketAfterAcknowledgementModulus; } public void setCloseSocketAfterAcknowledgementModulus(int closeSocketAfterAcknowledgementModulus) { if (0 > closeSocketAfterAcknowledgementModulus) { this.closeSocketAfterAcknowledgementModulus = 0; } else { this.closeSocketAfterAcknowledgementModulus = closeSocketAfterAcknowledgementModulus; } } public int getResetSocketBeforeAcknowledgementModulus() { return resetSocketBeforeAcknowledgementModulus; } public void setResetSocketBeforeAcknowledgementModulus(int resetSocketBeforeAcknowledgementModulus) { if (0 > resetSocketBeforeAcknowledgementModulus) { this.resetSocketBeforeAcknowledgementModulus = 0; } else { this.resetSocketBeforeAcknowledgementModulus = resetSocketBeforeAcknowledgementModulus; } } public int getResetSocketAfterAcknowledgementModulus() { return resetSocketAfterAcknowledgementModulus; } public void setResetSocketAfterAcknowledgementModulus(int resetSocketAfterAcknowledgementModulus) { if (0 > resetSocketAfterAcknowledgementModulus) { this.resetSocketAfterAcknowledgementModulus = 0; } else { this.resetSocketAfterAcknowledgementModulus = resetSocketAfterAcknowledgementModulus; } } public int getSendApplicationRejectAcknowledgementModulus() { return sendApplicationRejectAcknowledgementModulus; } public void setSendApplicationRejectAcknowledgementModulus(int sendApplicationRejectAcknowledgementModulus) { if (0 > sendApplicationRejectAcknowledgementModulus) { this.sendApplicationRejectAcknowledgementModulus = 0; } else { this.sendApplicationRejectAcknowledgementModulus = sendApplicationRejectAcknowledgementModulus; } } public int getSendApplicationErrorAcknowledgementModulus() { return sendApplicationErrorAcknowledgementModulus; } public void setSendApplicationErrorAcknowledgementModulus(int sendApplicationErrorAcknowledgementModulus) { if (0 > sendApplicationErrorAcknowledgementModulus) { this.sendApplicationErrorAcknowledgementModulus = 0; } else { this.sendApplicationErrorAcknowledgementModulus = sendApplicationErrorAcknowledgementModulus; } } public Pattern getSendApplicationRejectAcknowledgementPattern() { return sendApplicationRejectAcknowledgementPattern; } public void setSendApplicationRejectAcknowledgementPattern(Pattern sendApplicationRejectAcknowledgementPattern) { this.sendApplicationRejectAcknowledgementPattern = sendApplicationRejectAcknowledgementPattern; } public Pattern getSendApplicationErrorAcknowledgementPattern() { return sendApplicationErrorAcknowledgementPattern; } public void setSendApplicationErrorAcknowledgementPattern(Pattern sendApplicationErrorAcknowledgementPattern) { this.sendApplicationErrorAcknowledgementPattern = sendApplicationErrorAcknowledgementPattern; } public String getAcknowledgementString() { return acknowledgementString; } public void setAcknowledgementString(String acknowledgementString) { this.acknowledgementString = acknowledgementString; } public AcceptSocketThread getAcceptSocketThread() { return acceptSocketThread; } public void setAcceptSocketThread(AcceptSocketThread acceptSocketThread) { this.acceptSocketThread = acceptSocketThread; } public void checkClientConnections() { if (acceptSocketThread != null) { acceptSocketThread.checkClientConnections(); } } public void closeClientConnections() { if (acceptSocketThread != null) { acceptSocketThread.closeClientConnections(); } } public void resetClientConnections() { if (acceptSocketThread != null) { acceptSocketThread.resetClientConnections(); } } /** * Generates a HL7 Application Acknowledgement * * @param hl7Message HL7 message that is being acknowledged * @param acknowledgementCode AA, AE or AR * * @return a HL7 Application Acknowledgement */ protected String generateAcknowledgement(String hl7Message, String acknowledgementCode) { final String defaulNackMessage = "MSH|^~\\&|||||||NACK||P|2.2" + MllpProtocolConstants.SEGMENT_DELIMITER + "MSA|AR|" + MllpProtocolConstants.SEGMENT_DELIMITER + MllpProtocolConstants.MESSAGE_TERMINATOR; if (hl7Message == null) { log.error("Invalid HL7 message for parsing operation. Please check your inputs"); return defaulNackMessage; } if (!("AA".equals(acknowledgementCode) || "AE".equals(acknowledgementCode) || "AR".equals(acknowledgementCode))) { throw new IllegalArgumentException("Acknowledgemnt Code must be AA, AE or AR: " + acknowledgementCode); } int endOfMshSegment = hl7Message.indexOf(MllpProtocolConstants.SEGMENT_DELIMITER); if (-1 != endOfMshSegment) { String mshSegment = hl7Message.substring(0, endOfMshSegment); char fieldSeparator = mshSegment.charAt(3); String fieldSeparatorPattern = Pattern.quote(String.valueOf(fieldSeparator)); String[] mshFields = mshSegment.split(fieldSeparatorPattern); if (mshFields.length == 0) { log.error("Failed to split MSH Segment into fields"); } else { StringBuilder ackBuilder = new StringBuilder(mshSegment.length() + 25); // Build the MSH Segment ackBuilder .append(mshFields[0]).append(fieldSeparator) .append(mshFields[1]).append(fieldSeparator) .append(mshFields[4]).append(fieldSeparator) .append(mshFields[5]).append(fieldSeparator) .append(mshFields[2]).append(fieldSeparator) .append(mshFields[3]).append(fieldSeparator) .append(mshFields[6]).append(fieldSeparator) .append(mshFields[7]).append(fieldSeparator) .append("ACK") .append(mshFields[8].substring(3)); for (int i = 9; i < mshFields.length; ++i) { ackBuilder.append(fieldSeparator).append(mshFields[i]); } // Empty fields at the end are not preserved by String.split, so preserve them int emptyFieldIndex = mshSegment.length() - 1; if (fieldSeparator == mshSegment.charAt(mshSegment.length() - 1)) { ackBuilder.append(fieldSeparator); while (emptyFieldIndex >= 1 && mshSegment.charAt(emptyFieldIndex) == mshSegment.charAt(emptyFieldIndex - 1)) { ackBuilder.append(fieldSeparator); --emptyFieldIndex; } } ackBuilder.append(MllpProtocolConstants.SEGMENT_DELIMITER); // Build the MSA Segment ackBuilder .append("MSA").append(fieldSeparator) .append(acknowledgementCode).append(fieldSeparator) .append(mshFields[9]).append(fieldSeparator) .append(MllpProtocolConstants.SEGMENT_DELIMITER); // Terminate the message ackBuilder.append(MllpProtocolConstants.MESSAGE_TERMINATOR); return ackBuilder.toString(); } } else { log.error("Failed to find the end of the MSH Segment"); } return null; } /** * Nested
MllpServerResource
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/json/DuplicateJsonObjectContextCustomizerFactoryTests.java
{ "start": 1266, "end": 1759 }
class ____ { private CapturedOutput output; @BeforeEach void setup(CapturedOutput output) { this.output = output; } @Test @SuppressWarnings("NullAway") // Uses null for quick test setup void warningForMultipleVersions() { new DuplicateJsonObjectContextCustomizerFactory().createContextCustomizer(null, null) .customizeContext(null, null); assertThat(this.output).contains("Found multiple occurrences of org.json.JSONObject on the
DuplicateJsonObjectContextCustomizerFactoryTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/startupprogress/Status.java
{ "start": 1010, "end": 1216 }
enum ____ { /** * The phase has not yet started running. */ PENDING, /** * The phase is running right now. */ RUNNING, /** * The phase has already completed. */ COMPLETE }
Status
java
quarkusio__quarkus
independent-projects/tools/analytics-common/src/test/java/io/quarkus/analytics/common/TestRestClient.java
{ "start": 183, "end": 559 }
class ____ implements ConfigClient { private AnalyticsRemoteConfig analyticsRemoteConfig; public TestRestClient(AnalyticsRemoteConfig analyticsRemoteConfig) { this.analyticsRemoteConfig = analyticsRemoteConfig; } @Override public Optional<AnalyticsRemoteConfig> getConfig() { return Optional.of(analyticsRemoteConfig); } }
TestRestClient
java
apache__flink
flink-connectors/flink-file-sink-common/src/main/java/org/apache/flink/streaming/api/functions/sink/filesystem/BucketWriter.java
{ "start": 5078, "end": 5930 }
interface ____ { /** * Commits the pending file, making it visible. The file will contain the exact data as when * the pending file was created. * * @throws IOException Thrown if committing fails. */ void commit() throws IOException; /** * Commits the pending file, making it visible. The file will contain the exact data as when * the pending file was created. * * <p>This method tolerates situations where the file was already committed and will not * raise an exception in that case. This is important for idempotent commit retries as they * need to happen after recovery. * * @throws IOException Thrown if committing fails. */ void commitAfterRecovery() throws IOException; } }
PendingFile
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plan/physical/ShowExecSerializationTests.java
{ "start": 666, "end": 2399 }
class ____ extends AbstractPhysicalPlanSerializationTests<ShowExec> { public static ShowExec randomShowExec() { Source source = randomSource(); List<Attribute> attributes = randomList(1, 10, () -> ReferenceAttributeTests.randomReferenceAttribute(true)); List<List<Object>> values = randomValues(attributes); return new ShowExec(source, attributes, values); } private static List<List<Object>> randomValues(List<Attribute> attributes) { int size = between(0, 1000); List<List<Object>> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { List<Object> row = new ArrayList<>(attributes.size()); for (Attribute a : attributes) { row.add(randomLiteral(a.dataType()).value()); } result.add(row); } return result; } @Override protected ShowExec createTestInstance() { return randomShowExec(); } @Override protected ShowExec mutateInstance(ShowExec instance) throws IOException { List<Attribute> attributes = instance.output(); List<List<Object>> values = instance.values(); if (randomBoolean()) { attributes = randomValueOtherThan( attributes, () -> randomList(1, 10, () -> ReferenceAttributeTests.randomReferenceAttribute(true)) ); } List<Attribute> finalAttributes = attributes; values = randomValueOtherThan(values, () -> randomValues(finalAttributes)); return new ShowExec(instance.source(), attributes, values); } @Override protected boolean alwaysEmptySource() { return true; } }
ShowExecSerializationTests
java
square__javapoet
src/test/java/com/squareup/javapoet/JavaFileTest.java
{ "start": 8777, "end": 9472 }
class ____ {\n" + " public static long minutesToSeconds(long minutes) {\n" + " System.gc();\n" + " return SECONDS.convert(minutes, MINUTES);\n" + " }\n" + "}\n"); } @Test public void importStaticUsingWildcards() { assertThat(JavaFile.builder("readme", importStaticTypeSpec("Util")) .addStaticImport(TimeUnit.class, "*") .addStaticImport(System.class, "*") .build().toString()).isEqualTo("" + "package readme;\n" + "\n" + "import static java.lang.System.*;\n" + "import static java.util.concurrent.TimeUnit.*;\n" + "\n" + "
Util
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeEditorTests.java
{ "start": 1166, "end": 6843 }
class ____ { private final TransactionAttributeEditor pe = new TransactionAttributeEditor(); @Test void nullText() { pe.setAsText(null); assertThat(pe.getValue()).isNull(); } @Test void emptyString() { pe.setAsText(""); assertThat(pe.getValue()).isNull(); } @Test void validPropagationCodeOnly() { pe.setAsText("PROPAGATION_REQUIRED"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(ta).isNotNull(); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); assertThat(ta.isReadOnly()).isFalse(); } @Test void invalidPropagationCodeOnly() { // should have failed with bogus propagation code assertThatIllegalArgumentException().isThrownBy(() -> pe.setAsText("XXPROPAGATION_REQUIRED")); } @Test void validPropagationCodeAndIsolationCode() { pe.setAsText("PROPAGATION_REQUIRED, ISOLATION_READ_UNCOMMITTED"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(ta).isNotNull(); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_READ_UNCOMMITTED); } @Test void validPropagationAndIsolationCodesAndInvalidRollbackRule() { // should fail with bogus rollback rule assertThatIllegalArgumentException() .isThrownBy(() -> pe.setAsText("PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,XXX")); } @Test void validPropagationCodeAndIsolationCodeAndRollbackRules1() { pe.setAsText("PROPAGATION_MANDATORY,ISOLATION_REPEATABLE_READ,timeout_10,-IOException,+MyRuntimeException"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(ta).isNotNull(); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); assertThat(ta.getTimeout()).isEqualTo(10); assertThat(ta.isReadOnly()).isFalse(); assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); assertThat(ta.rollbackOn(new Exception())).isFalse(); // Check for our bizarre customized rollback rules assertThat(ta.rollbackOn(new IOException())).isTrue(); assertThat(ta.rollbackOn(new MyRuntimeException())).isFalse(); } @Test void validPropagationCodeAndIsolationCodeAndRollbackRules2() { pe.setAsText("+IOException,readOnly,ISOLATION_READ_COMMITTED,-MyRuntimeException,PROPAGATION_SUPPORTS"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(ta).isNotNull(); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); assertThat(ta.getTimeout()).isEqualTo(TransactionDefinition.TIMEOUT_DEFAULT); assertThat(ta.isReadOnly()).isTrue(); assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); assertThat(ta.rollbackOn(new Exception())).isFalse(); // Check for our bizarre customized rollback rules assertThat(ta.rollbackOn(new IOException())).isFalse(); assertThat(ta.rollbackOn(new MyRuntimeException())).isTrue(); } @Test void defaultTransactionAttributeToString() { DefaultTransactionAttribute source = new DefaultTransactionAttribute(); source.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); source.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); source.setTimeout(10); source.setReadOnly(true); pe.setAsText(source.toString()); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(source).isEqualTo(ta); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); assertThat(ta.getTimeout()).isEqualTo(10); assertThat(ta.isReadOnly()).isTrue(); assertThat(ta.rollbackOn(new RuntimeException())).isTrue(); assertThat(ta.rollbackOn(new Exception())).isFalse(); source.setTimeout(9); assertThat(source).isNotSameAs(ta); source.setTimeout(10); assertThat(source).isEqualTo(ta); } @Test void ruleBasedTransactionAttributeToString() { RuleBasedTransactionAttribute source = new RuleBasedTransactionAttribute(); source.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); source.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); source.setTimeout(10); source.setReadOnly(true); source.getRollbackRules().add(new RollbackRuleAttribute("IllegalArgumentException")); source.getRollbackRules().add(new NoRollbackRuleAttribute("IllegalStateException")); pe.setAsText(source.toString()); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertThat(source).isEqualTo(ta); assertThat(ta.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_SUPPORTS); assertThat(ta.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); assertThat(ta.getTimeout()).isEqualTo(10); assertThat(ta.isReadOnly()).isTrue(); assertThat(ta.rollbackOn(new IllegalArgumentException())).isTrue(); assertThat(ta.rollbackOn(new IllegalStateException())).isFalse(); source.getRollbackRules().clear(); assertThat(source).isNotSameAs(ta); source.getRollbackRules().add(new RollbackRuleAttribute("IllegalArgumentException")); source.getRollbackRules().add(new NoRollbackRuleAttribute("IllegalStateException")); assertThat(source).isEqualTo(ta); } }
TransactionAttributeEditorTests
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_assertThat_with_primitive_boolean_Test.java
{ "start": 869, "end": 1086 }
class ____ { @Test void should_create_Assert() { AbstractBooleanAssert<?> assertions = Assertions.assertThat(true); assertThat(assertions).isNotNull(); } }
Assertions_assertThat_with_primitive_boolean_Test
java
google__dagger
javatests/dagger/functional/builder/BuilderTest.java
{ "start": 2927, "end": 3377 }
interface ____<B, C, M1, M2> { C build(); // Test resolving return type of build() B setM1(M1 m1); // Test resolving return type & param of setter SharedBuilder<B, C, M1, M2> setM2(M2 m2); // Test being overridden void setM3(DoubleModule doubleModule); // Test being overridden SharedBuilder<B, C, M1, M2> set(FloatModule floatModule); // Test return type is supertype. } @Subcomponent.Builder
SharedBuilder
java
google__guice
core/test/com/google/inject/MaxArityTest.java
{ "start": 879, "end": 8646 }
class ____ { // Regression test for a bug where the methodhandle path would fail for such large methods. @Test public void testMaxArityProvidesMethod() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(int.class).toInstance(1); } @SuppressWarnings("unused") @Provides String provideLimits( int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, int i9, int i10, int i11, int i12, int i13, int i14, int i15, int i16, int i17, int i18, int i19, int i20, int i21, int i22, int i23, int i24, int i25, int i26, int i27, int i28, int i29, int i30, int i31, int i32, int i33, int i34, int i35, int i36, int i37, int i38, int i39, int i40, int i41, int i42, int i43, int i44, int i45, int i46, int i47, int i48, int i49, int i50, int i51, int i52, int i53, int i54, int i55, int i56, int i57, int i58, int i59, int i60, int i61, int i62, int i63, int i64, int i65, int i66, int i67, int i68, int i69, int i70, int i71, int i72, int i73, int i74, int i75, int i76, int i77, int i78, int i79, int i80, int i81, int i82, int i83, int i84, int i85, int i86, int i87, int i88, int i89, int i90, int i91, int i92, int i93, int i94, int i95, int i96, int i97, int i98, int i99, int i100, int i101, int i102, int i103, int i104, int i105, int i106, int i107, int i108, int i109, int i110, int i111, int i112, int i113, int i114, int i115, int i116, int i117, int i118, int i119, int i120, int i121, int i122, int i123, int i124, int i125, int i126, int i127, int i128, int i129, int i130, int i131, int i132, int i133, int i134, int i135, int i136, int i137, int i138, int i139, int i140, int i141, int i142, int i143, int i144, int i145, int i146, int i147, int i148, int i149, int i150, int i151, int i152, int i153, int i154, int i155, int i156, int i157, int i158, int i159, int i160, int i161, int i162, int i163, int i164, int i165, int i166, int i167, int i168, int i169, int i170, int i171, int i172, int i173, int i174, int i175, int i176, int i177, int i178, int i179, int i180, int i181, int i182, int i183, int i184, int i185, int i186, int i187, int i188, int i189, int i190, int i191, int i192, int i193, int i194, int i195, int i196, int i197, int i198, int i199, int i200, int i201, int i202, int i203, int i204, int i205, int i206, int i207, int i208, int i209, int i210, int i211, int i212, int i213, int i214, int i215, int i216, int i217, int i218, int i219, int i220, int i221, int i222, int i223, int i224, int i225, int i226, int i227, int i228, int i229, int i230, int i231, int i232, int i233, int i234, int i235, int i236, int i237, int i238, int i239, int i240, int i241, int i242, int i243, int i244, int i245, int i246, int i247, int i248, int i249, int i250, int i251, int i252, int i253) { // NOTE: the java compiler will reject this method if we add even one more // parameter. return "limits"; } }); assertThat(injector.getInstance(String.class)).isEqualTo("limits"); } static
MaxArityTest
java
resilience4j__resilience4j
resilience4j-framework-common/src/main/java/io/github/resilience4j/common/micrometer/configuration/TimerConfigCustomizer.java
{ "start": 915, "end": 1920 }
interface ____ extends CustomizerWithName { /** * Timer configuration builder. * * @param configBuilder to be customized */ void customize(TimerConfig.Builder configBuilder); /** * A convenient method to create TimerConfigCustomizer using {@link Consumer} * * @param instanceName the name of the instance * @param consumer delegate call to Consumer when {@link TimerConfigCustomizer#customize(TimerConfig.Builder)} * is called * @return Customizer instance */ static TimerConfigCustomizer of(@NonNull String instanceName, @NonNull Consumer<TimerConfig.Builder> consumer) { return new TimerConfigCustomizer() { @Override public void customize(TimerConfig.Builder builder) { consumer.accept(builder); } @Override public String name() { return instanceName; } }; } }
TimerConfigCustomizer
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 106013, "end": 106251 }
class ____<E> { public abstract E bar(); public static <E> Builder<E> builder() { return new AutoValue_AutoValueTest_NonDefaultableInner.Builder<E>(); } @AutoValue.Builder public abstract static
NonDefaultableInner
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/http/WebSocketConnectOptions.java
{ "start": 1189, "end": 10828 }
class ____ extends RequestOptions { /** * The default value for proxy options = {@code null} */ public static final ProxyOptions DEFAULT_PROXY_OPTIONS = null; /** * The default WebSocket version = {@link WebSocketVersion#V13} */ public static final WebSocketVersion DEFAULT_VERSION = WebSocketVersion.V13; /** * The default WebSocket sub protocols = {@code null} */ public static final List<String> DEFAULT_SUB_PROTOCOLS = null; /** * The default WebSocket allow origin header = {@code true} */ public static final boolean DEFAULT_ALLOW_ORIGIN_HEADER = true; /** * Whether write-handlers should be registered by default = false. */ public static final boolean DEFAULT_REGISTER_WRITE_HANDLERS = false; private ProxyOptions proxyOptions; private WebSocketVersion version; private List<String> subProtocols; private boolean allowOriginHeader; private boolean registerWriteHandlers; public WebSocketConnectOptions() { proxyOptions = DEFAULT_PROXY_OPTIONS; version = DEFAULT_VERSION; subProtocols = DEFAULT_SUB_PROTOCOLS; allowOriginHeader = DEFAULT_ALLOW_ORIGIN_HEADER; registerWriteHandlers = DEFAULT_REGISTER_WRITE_HANDLERS; } public WebSocketConnectOptions(WebSocketConnectOptions other) { super(other); this.proxyOptions = other.proxyOptions != null ? new ProxyOptions(other.proxyOptions) : null; this.version = other.version; this.subProtocols = other.subProtocols; this.allowOriginHeader = other.allowOriginHeader; this.registerWriteHandlers = other.registerWriteHandlers; } public WebSocketConnectOptions(JsonObject json) { super(json); WebSocketConnectOptionsConverter.fromJson(json, this); } /** * @return the WebSocket version */ public WebSocketVersion getVersion() { return version; } /** * Set the WebSocket version. * * @return a reference to this, so the API can be used fluently */ public WebSocketConnectOptions setVersion(WebSocketVersion version) { this.version = version; return this; } /** * @return the list of WebSocket sub protocols or {@code null} if there are none */ public List<String> getSubProtocols() { return subProtocols; } /** * Set the WebSocket sub protocols to use. * * @return a reference to this, so the API can be used fluently */ public WebSocketConnectOptions setSubProtocols(List<String> subProtocols) { this.subProtocols = subProtocols; return this; } /** * Add a WebSocket sub protocol to use. * * @return a reference to this, so the API can be used fluently */ public WebSocketConnectOptions addSubProtocol(String subprotocol) { if (subProtocols == null) { subProtocols = new ArrayList<>(); } subProtocols.add(subprotocol); return this; } /** * Get the proxy options override for connections * * @return proxy options override */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Override the {@link HttpClientOptions#setProxyOptions(ProxyOptions)} proxy options * for connections. * * @param proxyOptions proxy options override object * @return a reference to this, so the API can be used fluently */ public RequestOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return whether to add the {@code origin} header to the WebSocket handshake request */ public boolean getAllowOriginHeader() { return allowOriginHeader; } /** * Set whether to add the {@code origin} header to the WebSocket handshake request, enabled by default. * * <p> Set to {@code false} when a server does not accept WebSocket with an origin header. * * @param allowOriginHeader whether to add the {@code origin} header to the WebSocket handshake request * @return a reference to this, so the API can be used fluently */ public WebSocketConnectOptions setAllowOriginHeader(boolean allowOriginHeader) { this.allowOriginHeader = allowOriginHeader; return this; } @Override public WebSocketConnectOptions setHost(String host) { return (WebSocketConnectOptions) super.setHost(host); } @Override public WebSocketConnectOptions setPort(Integer port) { return (WebSocketConnectOptions) super.setPort(port); } @Override public WebSocketConnectOptions setSsl(Boolean ssl) { return (WebSocketConnectOptions) super.setSsl(ssl); } @Override public WebSocketConnectOptions setSslOptions(ClientSSLOptions sslOptions) { return (WebSocketConnectOptions) super.setSslOptions(sslOptions); } @Override public WebSocketConnectOptions setURI(String uri) { return (WebSocketConnectOptions) super.setURI(uri); } /** * Sets the amount of time after which if the WebSocket handshake does not happen within the timeout period an * {@link WebSocketHandshakeException} will be passed to the exception handler and the connection will be closed. * * @param timeout the amount of time in milliseconds. * @return a reference to this, so the API can be used fluently */ @Override public WebSocketConnectOptions setTimeout(long timeout) { return (WebSocketConnectOptions) super.setTimeout(timeout); } @Override public WebSocketConnectOptions setConnectTimeout(long timeout) { return (WebSocketConnectOptions) super.setConnectTimeout(timeout); } @Override public WebSocketConnectOptions setIdleTimeout(long timeout) { return (WebSocketConnectOptions) super.setIdleTimeout(timeout); } @Override public WebSocketConnectOptions addHeader(String key, String value) { return (WebSocketConnectOptions) super.addHeader(key, value); } @Override public WebSocketConnectOptions addHeader(CharSequence key, CharSequence value) { return (WebSocketConnectOptions) super.addHeader(key, value); } @Override public WebSocketConnectOptions addHeader(CharSequence key, Iterable<CharSequence> values) { return (WebSocketConnectOptions) super.addHeader(key, values); } @Override public WebSocketConnectOptions putHeader(String key, String value) { return (WebSocketConnectOptions) super.putHeader(key, value); } @Override public WebSocketConnectOptions putHeader(CharSequence key, CharSequence value) { return (WebSocketConnectOptions) super.putHeader(key, value); } @Override public WebSocketConnectOptions putHeader(CharSequence key, Iterable<CharSequence> values) { return (WebSocketConnectOptions) super.putHeader(key, values); } @GenIgnore @Override public WebSocketConnectOptions setHeaders(MultiMap headers) { return (WebSocketConnectOptions) super.setHeaders(headers); } @Override public WebSocketConnectOptions setServer(Address server) { return (WebSocketConnectOptions) super.setServer(server); } @Override public WebSocketConnectOptions setMethod(HttpMethod method) { return (WebSocketConnectOptions) super.setMethod(method); } @Override public WebSocketConnectOptions setFollowRedirects(Boolean followRedirects) { return (WebSocketConnectOptions) super.setFollowRedirects(followRedirects); } @Override public WebSocketConnectOptions setAbsoluteURI(String absoluteURI) { URI uri; try { uri = new URI(absoluteURI); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } setAbsoluteURI(uri); return this; } @Override public WebSocketConnectOptions setAbsoluteURI(URL url) { URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } setAbsoluteURI(uri); return this; } private void setAbsoluteURI(URI uri) { String scheme = uri.getScheme(); if (!"ws".equals(scheme) && !"wss".equals(scheme)) { throw new IllegalArgumentException("Scheme: " + scheme); } boolean ssl = scheme.length() == 3; int port = uri.getPort(); if (port == -1) { port = ssl ? 443 : 80; }; StringBuilder relativeUri = new StringBuilder(); if (uri.getRawPath() != null) { relativeUri.append(uri.getRawPath()); } if (uri.getRawQuery() != null) { relativeUri.append('?').append(uri.getRawQuery()); } if (uri.getRawFragment() != null) { relativeUri.append('#').append(uri.getRawFragment()); } setHost(uri.getHost()); setPort(port); setSsl(ssl); setURI(relativeUri.toString()); } @Override public WebSocketConnectOptions setTraceOperation(String op) { return (WebSocketConnectOptions) super.setTraceOperation(op); } @Override public JsonObject toJson() { JsonObject json = super.toJson(); WebSocketConnectOptionsConverter.toJson(this, json); return json; } /** * @return {@code true} if write-handlers should be registered on the {@link io.vertx.core.eventbus.EventBus}, otherwise {@code false} */ public boolean isRegisterWriteHandlers() { return registerWriteHandlers; } /** * Whether write-handlers should be registered on the {@link io.vertx.core.eventbus.EventBus}. * <p> * Defaults to {@code false}. * * @param registerWriteHandlers true to register write-handlers * @return a reference to this, so the API can be used fluently * @see WebSocketBase#textHandlerID() * @see WebSocketBase#binaryHandlerID() */ public WebSocketConnectOptions setRegisterWriteHandlers(boolean registerWriteHandlers) { this.registerWriteHandlers = registerWriteHandlers; return this; } }
WebSocketConnectOptions
java
google__guava
android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
{ "start": 10681, "end": 11103 }
class ____ method @Override public int size() { Monitor monitor = this.monitor; monitor.enter(); try { return q.size(); } finally { monitor.leave(); } } /** * Always returns {@code Integer.MAX_VALUE} because a {@code MonitorBasedPriorityBlockingQueue} is * not capacity constrained. * * @return {@code Integer.MAX_VALUE} */ @CanIgnoreReturnValue // pushed down from
to
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableAsObservableTest.java
{ "start": 1092, "end": 2206 }
class ____ extends RxJavaTest { @Test public void hiding() { PublishProcessor<Integer> src = PublishProcessor.create(); Flowable<Integer> dst = src.hide(); assertFalse(dst instanceof PublishProcessor); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); dst.subscribe(subscriber); src.onNext(1); src.onComplete(); verify(subscriber).onNext(1); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void hidingError() { PublishProcessor<Integer> src = PublishProcessor.create(); Flowable<Integer> dst = src.hide(); assertFalse(dst instanceof PublishProcessor); Subscriber<Integer> subscriber = TestHelper.mockSubscriber(); dst.subscribe(subscriber); src.onError(new TestException()); verify(subscriber, never()).onNext(Mockito.<Integer>any()); verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } }
FlowableAsObservableTest
java
quarkusio__quarkus
extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java
{ "start": 7892, "end": 8203 }
class ____ extends AbstractTestSecurityIdentity { @Override public Principal getPrincipal() { return null; } @Override public boolean isAnonymous() { return false; } } static abstract
TestSecurityIdentityPrincipalNullAnonymousFalse