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
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hbm/query/BarPK.java
{ "start": 144, "end": 386 }
class ____ { String id1; String id2; public String getId1() { return id1; } public void setId1(String id1) { this.id1 = id1; } public String getId2() { return id2; } public void setId2(String id2) { this.id2 = id2; } }
BarPK
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupElasticMemoryController.java
{ "start": 1890, "end": 10861 }
class ____ { protected static final Logger LOG = LoggerFactory .getLogger(TestCGroupElasticMemoryController.class); private YarnConfiguration conf = new YarnConfiguration(); private File script = new File("target/" + TestCGroupElasticMemoryController.class.getName()); /** * Test that at least one memory type is requested. * @throws YarnException on exception */ @Test public void testConstructorOff() throws YarnException { assertThrows(YarnException.class, () -> { new CGroupElasticMemoryController( conf, null, null, false, false, 10000 ); }); } /** * Test that the OOM logic is pluggable. * @throws YarnException on exception */ @Test public void testConstructorHandler() throws YarnException { conf.setClass(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_HANDLER, DummyRunnableWithContext.class, Runnable.class); CGroupsHandler handler = mock(CGroupsHandler.class); when(handler.getPathForCGroup(any(), any())).thenReturn(""); new CGroupElasticMemoryController( conf, null, handler, true, false, 10000 ); } /** * Test that the handler is notified about multiple OOM events. * @throws Exception on exception */ @Test @Timeout(value = 20) public void testMultipleOOMEvents() throws Exception { conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH, script.getAbsolutePath()); try { FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;printf oomevent;\n", StandardCharsets.UTF_8, false); assertTrue(script.setExecutable(true), "Could not set executable"); CGroupsHandler cgroups = mock(CGroupsHandler.class); when(cgroups.getPathForCGroup(any(), any())).thenReturn(""); when(cgroups.getCGroupParam(any(), any(), any())) .thenReturn("under_oom 0"); Runnable handler = mock(Runnable.class); doNothing().when(handler).run(); CGroupElasticMemoryController controller = new CGroupElasticMemoryController( conf, null, cgroups, true, false, 10000, handler ); controller.run(); verify(handler, times(2)).run(); } finally { assertTrue(script.delete(), String.format("Could not clean up script %s", script.getAbsolutePath())); } } /** * Test the scenario that the controller is stopped before. * the child process starts * @throws Exception one exception */ @Test @Timeout(value = 20) public void testStopBeforeStart() throws Exception { conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH, script.getAbsolutePath()); try { FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;printf oomevent;\n", StandardCharsets.UTF_8, false); assertTrue(script.setExecutable(true), "Could not set executable"); CGroupsHandler cgroups = mock(CGroupsHandler.class); when(cgroups.getPathForCGroup(any(), any())).thenReturn(""); when(cgroups.getCGroupParam(any(), any(), any())) .thenReturn("under_oom 0"); Runnable handler = mock(Runnable.class); doNothing().when(handler).run(); CGroupElasticMemoryController controller = new CGroupElasticMemoryController( conf, null, cgroups, true, false, 10000, handler ); controller.stopListening(); controller.run(); verify(handler, times(0)).run(); } finally { assertTrue(script.delete(), String.format("Could not clean up script %s", script.getAbsolutePath())); } } /** * Test the edge case that OOM is never resolved. * @throws Exception on exception */ @Test @Timeout(value = 20) public void testInfiniteOOM() throws Exception { assertThrows(YarnRuntimeException.class, () -> { conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH, script.getAbsolutePath()); Runnable handler = mock(Runnable.class); try { FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n", StandardCharsets.UTF_8, false); assertTrue(script.setExecutable(true), "Could not set executable"); CGroupsHandler cgroups = mock(CGroupsHandler.class); when(cgroups.getPathForCGroup(any(), any())).thenReturn(""); when(cgroups.getCGroupParam(any(), any(), any())) .thenReturn("under_oom 1"); doNothing().when(handler).run(); CGroupElasticMemoryController controller = new CGroupElasticMemoryController( conf, null, cgroups, true, false, 10000, handler ); controller.run(); } finally { verify(handler, times(1)).run(); assertTrue(script.delete(), String.format("Could not clean up script %s", script.getAbsolutePath())); } }); } /** * Test the edge case that OOM cannot be resolved due to the lack of * containers. * @throws Exception on exception */ @Test @Timeout(value = 20) public void testNothingToKill() throws Exception { assertThrows(YarnRuntimeException.class, () -> { conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH, script.getAbsolutePath()); Runnable handler = mock(Runnable.class); try { FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n", StandardCharsets.UTF_8, false); assertTrue( script.setExecutable(true), "Could not set executable"); CGroupsHandler cgroups = mock(CGroupsHandler.class); when(cgroups.getPathForCGroup(any(), any())).thenReturn(""); when(cgroups.getCGroupParam(any(), any(), any())) .thenReturn("under_oom 1"); doThrow(new YarnRuntimeException("Expected")).when(handler).run(); CGroupElasticMemoryController controller = new CGroupElasticMemoryController( conf, null, cgroups, true, false, 10000, handler ); controller.run(); } finally { verify(handler, times(1)).run(); assertTrue(script.delete(), String.format("Could not clean up script %s", script.getAbsolutePath())); } }); } /** * Test that node manager can exit listening. * This is done by running a long running listener for 10000 seconds. * Then we wait for 2 seconds and stop listening. * We do not use a script this time to avoid leaking the child process. * @throws Exception exception occurred */ @Test @Timeout(value = 20) public void testNormalExit() throws Exception { conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH, "sleep"); ExecutorService service = Executors.newFixedThreadPool(1); try { CGroupsHandler cgroups = mock(CGroupsHandler.class); // This will be passed to sleep as an argument when(cgroups.getPathForCGroup(any(), any())).thenReturn("10000"); when(cgroups.getCGroupParam(any(), any(), any())) .thenReturn("under_oom 0"); Runnable handler = mock(Runnable.class); doNothing().when(handler).run(); CGroupElasticMemoryController controller = new CGroupElasticMemoryController( conf, null, cgroups, true, false, 10000, handler ); long start = System.currentTimeMillis(); service.submit(() -> { try { Thread.sleep(2000); } catch (InterruptedException ex) { assertTrue(false, "Wait interrupted."); } LOG.info(String.format("Calling process destroy in %d ms", System.currentTimeMillis() - start)); controller.stopListening(); LOG.info("Called process destroy."); }); controller.run(); } finally { service.shutdown(); } } /** * Test that DefaultOOMHandler is instantiated correctly in * the elastic constructor. * @throws YarnException Could not set up elastic memory control. */ @Test public void testDefaultConstructor() throws YarnException{ CGroupsHandler handler = mock(CGroupsHandler.class); when(handler.getPathForCGroup(any(), any())).thenReturn(""); new CGroupElasticMemoryController( conf, null, handler, true, false, 10); } }
TestCGroupElasticMemoryController
java
redisson__redisson
redisson/src/main/java/org/redisson/api/search/index/SVSVamanaVectorIndex.java
{ "start": 770, "end": 1052 }
interface ____ extends VectorTypeParam<SVSVamanaVectorOptionalArgs> { /** * Defines the attribute associated to the field name * * @param as the associated attribute * @return options object */ SVSVamanaVectorIndex as(String as); }
SVSVamanaVectorIndex
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/basicType/FloatTest3_array_random.java
{ "start": 300, "end": 1169 }
class ____ extends TestCase { public void test_ran() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 1; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(new float[]{val})); Model m = JSON.parseObject(str, Model.class); assertEquals(val, m.value[0]); } } public void test_ran_2() throws Exception { Random rand = new Random(); for (int i = 0; i < 1000 * 1000 * 10; ++i) { float val = rand.nextFloat(); String str = JSON.toJSONString(new Model(new float[]{val}), SerializerFeature.BeanToArray); Model m = JSON.parseObject(str, Model.class, Feature.SupportArrayToBean); assertEquals(val, m.value[0]); } } public static
FloatTest3_array_random
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxDeferComposeTest.java
{ "start": 820, "end": 2393 }
class ____ { @Test public void perSubscriberState() { Flux<Integer> source = Flux.just(10).transformDeferred(f -> { AtomicInteger value = new AtomicInteger(); return f.map(v -> v + value.incrementAndGet()); }); for (int i = 0; i < 10; i++) { AssertSubscriber<Integer> ts = AssertSubscriber.create(); source.subscribe(ts); ts.assertValues(11) .assertComplete() .assertNoError(); } } @Test public void composerThrows() { Flux<Integer> source = Flux.just(10).transformDeferred(f -> { throw new RuntimeException("Forced failure"); }); for (int i = 0; i < 10; i++) { AssertSubscriber<Integer> ts = AssertSubscriber.create(); source.subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertError(RuntimeException.class); } } @Test public void composerReturnsNull() { Flux<Integer> source = Flux.just(10).transformDeferred(f -> { return null; }); for (int i = 0; i < 10; i++) { AssertSubscriber<Integer> ts = AssertSubscriber.create(); source.subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertError(NullPointerException.class); } } }
FluxDeferComposeTest
java
apache__hadoop
hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/client/binding/RegistryPathUtils.java
{ "start": 1577, "end": 7369 }
class ____ { /** * Compiled down pattern to validate single entries in the path */ private static final Pattern PATH_ENTRY_VALIDATION_PATTERN = Pattern.compile(RegistryInternalConstants.VALID_PATH_ENTRY_PATTERN); private static final Pattern USER_NAME = Pattern.compile("/users/([a-z][a-z0-9-.]*)"); /** * Validate ZK path with the path itself included in * the exception text * @param path path to validate * @return the path parameter * @throws InvalidPathnameException if the pathname is invalid. */ public static String validateZKPath(String path) throws InvalidPathnameException { try { PathUtils.validatePath(path); } catch (IllegalArgumentException e) { throw new InvalidPathnameException(path, "Invalid Path \"" + path + "\" : " + e, e); } return path; } /** * Validate ZK path as valid for a DNS hostname. * @param path path to validate * @return the path parameter * @throws InvalidPathnameException if the pathname is invalid. */ public static String validateElementsAsDNS(String path) throws InvalidPathnameException { List<String> splitpath = split(path); for (String fragment : splitpath) { if (!PATH_ENTRY_VALIDATION_PATTERN.matcher(fragment).matches()) { throw new InvalidPathnameException(path, "Invalid Path element \"" + fragment + "\""); } } return path; } /** * Create a full path from the registry root and the supplied subdir * @param path path of operation * @return an absolute path * @throws InvalidPathnameException if the path is invalid */ public static String createFullPath(String base, String path) throws InvalidPathnameException { Preconditions.checkArgument(path != null, "null path"); Preconditions.checkArgument(base != null, "null path"); return validateZKPath(join(base, path)); } /** * Join two paths, guaranteeing that there will not be exactly * one separator between the two, and exactly one at the front * of the path. There will be no trailing "/" except for the special * case that this is the root path * @param base base path * @param path second path to add * @return a combined path. */ public static String join(String base, String path) { Preconditions.checkArgument(path != null, "null path"); Preconditions.checkArgument(base != null, "null path"); StringBuilder fullpath = new StringBuilder(); if (!base.startsWith("/")) { fullpath.append('/'); } fullpath.append(base); // guarantee a trailing / if (!fullpath.toString().endsWith("/")) { fullpath.append("/"); } // strip off any at the beginning if (path.startsWith("/")) { // path starts with /, so append all other characters -if present if (path.length() > 1) { fullpath.append(path.substring(1)); } } else { fullpath.append(path); } //here there may be a trailing "/" String finalpath = fullpath.toString(); if (finalpath.endsWith("/") && !"/".equals(finalpath)) { finalpath = finalpath.substring(0, finalpath.length() - 1); } return finalpath; } /** * split a path into elements, stripping empty elements * @param path the path * @return the split path */ public static List<String> split(String path) { // String[] pathelements = path.split("/"); List<String> dirs = new ArrayList<String>(pathelements.length); for (String pathelement : pathelements) { if (!pathelement.isEmpty()) { dirs.add(pathelement); } } return dirs; } /** * Get the last entry in a path; for an empty path * returns "". The split logic is that of * {@link #split(String)} * @param path path of operation * @return the last path entry or "" if none. */ public static String lastPathEntry(String path) { List<String> splits = split(path); if (splits.isEmpty()) { // empty path. Return "" return ""; } else { return splits.get(splits.size() - 1); } } /** * Get the parent of a path * @param path path to look at * @return the parent path * @throws PathNotFoundException if the path was at root. */ public static String parentOf(String path) throws PathNotFoundException { List<String> elements = split(path); int size = elements.size(); if (size == 0) { throw new PathNotFoundException("No parent of " + path); } if (size == 1) { return "/"; } elements.remove(size - 1); StringBuilder parent = new StringBuilder(path.length()); for (String element : elements) { parent.append("/"); parent.append(element); } return parent.toString(); } /** * Perform any formatting for the registry needed to convert * non-simple-DNS elements * @param element element to encode * @return an encoded string */ public static String encodeForRegistry(String element) { return IDN.toASCII(element); } /** * Perform whatever transforms are needed to get a YARN ID into * a DNS-compatible name * @param yarnId ID as string of YARN application, instance or container * @return a string suitable for use in registry paths. */ public static String encodeYarnID(String yarnId) { return yarnId.replace("container", "ctr").replace("_", "-"); } /** * Return the username found in the ZK path. * * @param recPath the ZK recPath. * @return the user name. */ public static String getUsername(String recPath) { String user = "anonymous"; Matcher matcher = USER_NAME.matcher(recPath); if (matcher.find()) { user = matcher.group(1); } return user; } }
RegistryPathUtils
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/RepetitionExtension.java
{ "start": 1548, "end": 2841 }
class ____ implements ParameterResolver, TestWatcher, ExecutionCondition { private final DefaultRepetitionInfo repetitionInfo; RepetitionExtension(DefaultRepetitionInfo repetitionInfo) { this.repetitionInfo = repetitionInfo; } @Override public ExtensionContextScope getTestInstantiationExtensionContextScope(ExtensionContext rootContext) { return ExtensionContextScope.TEST_METHOD; } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return (parameterContext.getParameter().getType() == RepetitionInfo.class); } @Override public RepetitionInfo resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return this.repetitionInfo; } @Override public void testFailed(ExtensionContext context, @Nullable Throwable cause) { this.repetitionInfo.failureCount().incrementAndGet(); } @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { int failureThreshold = this.repetitionInfo.getFailureThreshold(); if (this.repetitionInfo.getFailureCount() >= failureThreshold) { return disabled("Failure threshold [" + failureThreshold + "] exceeded"); } return enabled("Failure threshold not exceeded"); } }
RepetitionExtension
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/PemKeyCertOptions.java
{ "start": 3188, "end": 12703 }
class ____ implements KeyCertOptions { private KeyStoreHelper helper; private List<String> keyPaths; private List<Buffer> keyValues; private List<String> certPaths; private List<Buffer> certValues; /** * Default constructor */ public PemKeyCertOptions() { super(); init(); } private void init() { keyPaths = new ArrayList<>(); keyValues = new ArrayList<>(); certPaths = new ArrayList<>(); certValues = new ArrayList<>(); } /** * Copy constructor * * @param other the options to copy */ public PemKeyCertOptions(PemKeyCertOptions other) { super(); this.keyPaths = other.keyPaths != null ? new ArrayList<>(other.keyPaths) : new ArrayList<>(); this.keyValues = other.keyValues != null ? new ArrayList<>(other.keyValues) : new ArrayList<>(); this.certPaths = other.certPaths != null ? new ArrayList<>(other.certPaths) : new ArrayList<>(); this.certValues = other.certValues != null ? new ArrayList<>(other.certValues) : new ArrayList<>(); } /** * Create options from JSON * * @param json the JSON */ public PemKeyCertOptions(JsonObject json) { super(); init(); PemKeyCertOptionsConverter.fromJson(json, this); } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject json = new JsonObject(); PemKeyCertOptionsConverter.toJson(this, json); return json; } /** * Get the path to the first key file * * @return the path to the key file */ @GenIgnore public String getKeyPath() { return keyPaths.isEmpty() ? null : keyPaths.get(0); } /** * Set the path of the first key file, replacing the keys paths * * @param keyPath the path to the first key file * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setKeyPath(String keyPath) { keyPaths.clear(); if (keyPath != null) { keyPaths.add(keyPath); } return this; } /** * Get all the paths to the key files * * @return the paths to the keys files */ public List<String> getKeyPaths() { return keyPaths; } /** * Set all the paths to the keys files * * @param keyPaths the paths to the keys files * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setKeyPaths(List<String> keyPaths) { this.keyPaths.clear(); this.keyPaths.addAll(keyPaths); return this; } /** * Add a path to a key file * * @param keyPath the path to the key file * @return a reference to this, so the API can be used fluently */ @GenIgnore public PemKeyCertOptions addKeyPath(String keyPath) { Arguments.require(keyPath != null, "Null keyPath"); keyPaths.add(keyPath); return this; } /** * Get the first key as a buffer * * @return the first key as a buffer */ @GenIgnore public Buffer getKeyValue() { return keyValues.isEmpty() ? null : keyValues.get(0); } /** * Set the first key a a buffer, replacing the previous keys buffers * * @param keyValue key as a buffer * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setKeyValue(Buffer keyValue) { keyValues.clear(); if (keyValue != null) { keyValues.add(keyValue); } return this; } /** * Get all the keys as a list of buffer * * @return keys as a list of buffers */ public List<Buffer> getKeyValues() { return keyValues; } /** * Set all the keys as a list of buffer * * @param keyValues the keys as a list of buffer * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setKeyValues(List<Buffer> keyValues) { this.keyValues.clear(); this.keyValues.addAll(keyValues); return this; } /** * Add a key as a buffer * * @param keyValue the key to add * @return a reference to this, so the API can be used fluently */ @GenIgnore public PemKeyCertOptions addKeyValue(Buffer keyValue) { Arguments.require(keyValue != null, "Null keyValue"); keyValues.add(keyValue); return this; } /** * Get the path to the first certificate file * * @return the path to the certificate file */ @GenIgnore public String getCertPath() { return certPaths.isEmpty() ? null : certPaths.get(0); } /** * Set the path of the first certificate, replacing the previous certificates paths * * @param certPath the path to the certificate * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setCertPath(String certPath) { certPaths.clear(); if (certPath != null) { certPaths.add(certPath); } return this; } /** * Get all the paths to the certificates files * * @return the paths to the certificates files */ public List<String> getCertPaths() { return certPaths; } /** * Set all the paths to the certificates files * * @param certPaths the paths to the certificates files * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setCertPaths(List<String> certPaths) { this.certPaths.clear(); this.certPaths.addAll(certPaths); return this; } /** * Add a path to a certificate file * * @param certPath the path to the certificate file * @return a reference to this, so the API can be used fluently */ @GenIgnore public PemKeyCertOptions addCertPath(String certPath) { Arguments.require(certPath != null, "Null certPath"); certPaths.add(certPath); return this; } /** * Get the first certificate as a buffer * * @return the first certificate as a buffer */ @GenIgnore public Buffer getCertValue() { return certValues.isEmpty() ? null : certValues.get(0); } /** * Set the first certificate as a buffer, replacing the previous certificates buffers * * @param certValue the first certificate as a buffer * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setCertValue(Buffer certValue) { certValues.clear(); if (certValue != null) { certValues.add(certValue); } return this; } /** * Get all the certificates as a list of buffer * * @return certificates as a list of buffers */ public List<Buffer> getCertValues() { return certValues; } /** * Set all the certificates as a list of buffer * * @param certValues the certificates as a list of buffer * @return a reference to this, so the API can be used fluently */ public PemKeyCertOptions setCertValues(List<Buffer> certValues) { this.certValues.clear(); this.certValues.addAll(certValues); return this; } /** * Add a certificate as a buffer * * @param certValue the certificate to add * @return a reference to this, so the API can be used fluently */ @GenIgnore public PemKeyCertOptions addCertValue(Buffer certValue) { Arguments.require(certValue != null, "Null certValue"); certValues.add(certValue); return this; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == getClass()) { PemKeyCertOptions that = (PemKeyCertOptions) obj; return Objects.equals(keyPaths, that.keyPaths) && Objects.equals(keyValues, that.keyValues) && Objects.equals(certPaths, that.certPaths) && Objects.equals(certValues, that.certValues); } return false; } @Override public int hashCode() { int hashCode = Objects.hashCode(keyPaths); hashCode = 31 * hashCode + Objects.hashCode(keyValues); hashCode = 31 * hashCode + Objects.hashCode(certPaths); hashCode = 31 * hashCode + Objects.hashCode(certValues); return hashCode; } @Override public PemKeyCertOptions copy() { return new PemKeyCertOptions(this); } public KeyStoreHelper getHelper(Vertx vertx) throws Exception { if (helper == null) { List<Buffer> keys = new ArrayList<>(); for (String keyPath : keyPaths) { keys.add(vertx.fileSystem().readFileBlocking(((VertxInternal)vertx).fileResolver().resolve(keyPath).getAbsolutePath())); } keys.addAll(keyValues); List<Buffer> certs = new ArrayList<>(); for (String certPath : certPaths) { certs.add(vertx.fileSystem().readFileBlocking(((VertxInternal)vertx).fileResolver().resolve(certPath).getAbsolutePath())); } certs.addAll(certValues); helper = new KeyStoreHelper(KeyStoreHelper.loadKeyCert(keys, certs), KeyStoreHelper.DUMMY_PASSWORD, null); } return helper; } /** * Load and return a Java keystore. * * @param vertx the vertx instance * @return the {@code KeyStore} */ public KeyStore loadKeyStore(Vertx vertx) throws Exception { KeyStoreHelper helper = getHelper(vertx); return helper != null ? helper.store() : null; } @Override public KeyManagerFactory getKeyManagerFactory(Vertx vertx) throws Exception { KeyStoreHelper helper = getHelper(vertx); return helper != null ? helper.getKeyMgrFactory() : null; } @Override public Function<String, KeyManagerFactory> keyManagerFactoryMapper(Vertx vertx) throws Exception { KeyStoreHelper helper = getHelper(vertx); return helper != null ? helper::getKeyMgrFactory : null; } }
PemKeyCertOptions
java
micronaut-projects__micronaut-core
jackson-databind/src/main/java/io/micronaut/jackson/annotation/JacksonFeatures.java
{ "start": 1258, "end": 1997 }
interface ____ { /** * @return The enabled serialization features */ SerializationFeature[] enabledSerializationFeatures() default {}; /** * @return The disabled serialization features */ SerializationFeature[] disabledSerializationFeatures() default {}; /** * @return The enabled serialization features */ DeserializationFeature[] enabledDeserializationFeatures() default {}; /** * @return The disabled serialization features */ DeserializationFeature[] disabledDeserializationFeatures() default {}; /** * @return Additional modules to add to the jackson mapper */ Class<? extends JacksonModule>[] additionalModules() default {}; }
JacksonFeatures
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/NamingStrategyViaCreator556Test.java
{ "start": 682, "end": 995 }
class ____ { protected String myName; protected int myAge; @JsonCreator public RenamingCtorBean(int myAge, String myName) { this.myName = myName; this.myAge = myAge; } } // Try the same with factory, too static
RenamingCtorBean
java
apache__camel
test-infra/camel-test-infra-qdrant/src/main/java/org/apache/camel/test/infra/qdrant/services/QdrantInfraService.java
{ "start": 1137, "end": 2219 }
interface ____ extends InfrastructureService { String getHttpHost(); int getHttpPort(); @Deprecated default String getGrpcHost() { return host(); } @Deprecated default int getGrpcPort() { return port(); } String host(); int port(); default HttpResponse<byte[]> put(String path, Map<Object, Object> body) throws Exception { final String reqPath = !path.startsWith("/") ? "/" + path : path; final String reqUrl = String.format("http://%s:%d%s", getHttpHost(), getHttpPort(), reqPath); String requestBody = new ObjectMapper() .writerWithDefaultPrettyPrinter() .writeValueAsString(body); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(reqUrl)) .header("Content-Type", "application/json") .PUT(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray()); } }
QdrantInfraService
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/source/presencecheck/spi/PresenceCheckNestedObjectsTest.java
{ "start": 646, "end": 1512 }
class ____ { @ProcessorTest public void testNestedWithSourcesAbsentOnNestingLevel() { SoccerTeamSource soccerTeamSource = new SoccerTeamSource(); GoalKeeper goalKeeper = new GoalKeeper(); goalKeeper.setHasName( false ); goalKeeper.setName( "shouldNotBeUsed" ); soccerTeamSource.setGoalKeeper( goalKeeper ); soccerTeamSource.setHasRefereeName( false ); soccerTeamSource.setRefereeName( "shouldNotBeUsed" ); SoccerTeamTargetWithPresenceCheck target = SoccerTeamMapperNestedObjects.INSTANCE.mapNested( soccerTeamSource ); assertThat( target.getGoalKeeperName() ).isNull(); assertThat( target.hasGoalKeeperName() ).isFalse(); assertThat( target.getReferee() ).isNotNull(); assertThat( target.getReferee().getName() ).isNull(); } }
PresenceCheckNestedObjectsTest
java
dropwizard__dropwizard
dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/ResourceExtensionMocksTest.java
{ "start": 1176, "end": 1456 }
class ____ { private final Person person; public TestResource(Person person) { this.person = person; } @GET @Path("/name") public String getPersonName() { return person.getName(); } } }
TestResource
java
google__dagger
javatests/dagger/internal/codegen/ExpressionTest.java
{ "start": 1461, "end": 1600 }
class ____ { @Rule public CompilationRule compilationRule = new CompilationRule(); @Inject XProcessingEnv processingEnv;
ExpressionTest
java
apache__camel
components/camel-base64/src/test/java/org/apache/camel/dataformat/base64/Base64DataFormatTestBase.java
{ "start": 1125, "end": 7942 }
class ____ extends CamelTestSupport { static final byte[] DECODED = { 34, -76, 86, -124, -42, 77, -116, 92, 80, -23, 101, -55, 16, -117, 30, -123, -71, -59, 118, -22, -19, -127, -89, 0, -85, -21, 122, 102, 29, -18, 98, 92, -100, -108, 93, -57, 3, 31, 125, -26, 102, -56, -55, -44, 37, -54, 99, 60, 87, 124, -128, -7, -122, -11, -89, 114, 35, -20, 4, -75, 85, 6, -108, 52, 112, 37, -116, -38, 71, 82, -86, -42, 71, -95, 38, 1, 38, 85, -4, 68, 47, 71, -111, -92, -15, 112, -17, 70, -70, -19, -110, -128, -26, -6, 55, 89, -3, 114, -97, 122, -53, 118, 56, -116, -31, -117, 22, 69, -42, 103, 42, -54, 45, 79, 29, -22, 127, -84, 89, -43, 61, -55, 78, -11, 99, -106, -76, 32, -111, -121, 63, -108, -38, -54, 1, -52, -48, 109, -67, 55, 58, -57, 90, 115, -42, 3, -103, 114, -125, -124, 20, -95, -46, 127, 105, 38, -110, -83, 127, -18, 17, -59, -105, -112, -101, -10, 118, -46, 6, 12, -87, -108, 92, -20, 34, 117, 65, 124, 41, 17, -59, 112, 5, -117, 28, 27, 11, 112, 126, 44, 31, 30, -41, -100, -46, 50, -6, 6, -22, -119, 50, 14, -50, -62, -15, 4, -95, 33, -112, -105, 24, 121, 108, -71, 72, -121, -9, -88, -77, 81, -73, -63, -14, -86, 83, 64, -81, 52, 60, -16, 34, -77, 22, 33, 23, -8, 27, -21, -65, 48, -68, -18, 94, -1, 77, -64, -104, 89, -104, 108, 26, -77, -62, -125, 80, -24, -6, 25, 40, 82, 60, 107, -125, -44, -84, -70, 2, 46, -75, 39, 41, 8, 48, 57, 123, -98, 111, 92, -68, 119, -122, -20, 84, 106, -41, 31, -108, 20, 22, 0, 4, -33, 38, 68, -97, 102, 80, -75, 91, -6, 109, -103, -26, -34, 91, -63, 123, -14, -53, 68, 62, 49, 33, 77, -113, 114, 110, 94, -8, 50, 84, 102, 17, -36, -105, -1, 12, 106, 42, 3, 88, 88, 24, 60, -73, -19, 12, -85, -60, 83, 2, -63, -36, -127, 86, 45, 34, -116, 40, 90, 30, 94, 125, -89, -109, 12, 108, 8, 122, -13, -123, -88, -31, 110, 66, -91, -41, -31, -3, 35, -79, -92, 119, 95, 67, -56, 10, 15, 34, -72, -106, 56, -108, -100, -94, 15, -90, 112, -3, 34, -88, 111, 98, 50, -90, 5, -110, -115, -89, -82, 29, -85, -81, -24, -36, -56, -95, 65, -122, -76, 84, -72, -36, 55, 91, -49, -95, -8, 83, -80, 100, 50, -36, 6, 107, -109, -65, 105, 68, 58, -11, 29, 104, -8, 3, -5, 87, -70, 125, 122, 110, -58, 24, -94, -121, -116, 31, -1, 57, 90, -111, -27, 90, -45, 125, 83, -11, -51, 63, 28, -35, 54, -49, 71, 0, -124, -76, -11, -66, -47, 0, -45, 48, -25, -24, -20, -13, -123, -113, -1, 50, 29, -9, -39, -103, -126, -5, 26, -24, -7, -17, 104, -39, -82, -66, 118, 124, 26, -104, 59, 75, -71, 24, 3, 13, -33, -124, 114, -123, 16, -91, -15, 11, 94, -122, -41, -35, -108, -105, -20, -28, 48, -43, -107, -15, 90, 34, 75, -75, 35, -100, -25, 34, -47, -111, -42, -15, 116, -78, -65, 11, -89, -28, 113, -114, 28, -87, -49, -47, -64, 17, -104, -75, 115, 123, 103, 81, 13, 27, -5, 63, 46, 122, -39, -99, 21, 63, 18, -77, 22, 70, -42, -47, -63, -24, 64, -1, 70, -74, 41, 38, -51, 56, -52, 10, -16, 26, 115, 14, -69, -105, -71, -14, -41, 101, -63, -102, 12, -92, 84, 122, 75, 80, 125, -43, -8, 94, 24, 88, 17, 43, 117, 118, -73, -80, -107, 2, -43, 104, 69, -85, 100, 20, 124, 36, -25, 121, -103, -55, 46, -108, -8, 112, 30, -99, -112, -45, 70, 50, -95, 39, 4, -113, -92, 108, -1, -37, 34, -54, -2, 61, -4, 84, -102, 68, 38, -25, 127, 57, 119, 9, 25, -51, -68, 35, -125, -43, -53, -59, -32, -23, -34, 97, -75, 73, 8, -61, -104, -29, -37, -100, 22, 99, 127, -104, 16, -78, -60, -77, -83, 39, -122, 115, -16, 65, -75, 20, 47, 53, 65, 56, 55, 73, -52, 62, 21, -47, 67, -80, 40, 43, -20, 58, -107, -82, 99, -50, 46, 41, 42, -85, -84, 9, 116, -80, 99, -56, 117, -18, 50, 37, 79, -12, 90, -65, 104, 12, 111, 92, 72, 35, 70, -27, 103, 55, 109, 48, -97, 107, 84, 57, 119, -102, 55, -123, -22, -50, 36, 58, -24, -51, -74, -12, 123, 24, -48, 21, -7, -82, 34, 116, -45, 37, -64, -84, 60, 93, -8, -113, 102, 20, 58, 112, -3, 64, -25, 24, 16, 4, -40, -1, -1, -43, -11, 53, -98, -51, 64, -21, 52, 58, -123, 59, -5, 107, 23, 101, -61, 127, -59, -100, -32, 29, -54, 97, 10, -88, 64, -3, 8, -9, -37, -120, 59, -55, -54, 7, 0, 115, 27, -10, 127, 35, -111, 29, 15, -109, -118, -102, -52, 27, 23, 36, 2, 89, -53, 103, 106, 70, -105, -24, 14, -51, -69, 89, -52, -104, 30, 115, 33, 73, 28, 22, -31, -74, 75, -101, 24, 62, 51, -51, 8, 110, 36, -100, 60, -54, -102, -87, -91, 44, 106, 14, -49, 18, 1, 109, -97, -82, 62, 54, 81, 63, 106, 68, -57, -126, 4, 101, -53, 107, 92, 50, 33, 43, 120, 24, -114, -94, 58, 119, -16, 76, 36, 73, -3, 33, 59, 9, 90, -60, 126, 103, 102, 68, -23, 73, -92, 2, 71, 125, 73, 80, 32, -102, -75, 105, 109, -26, 76, 78, 115, 78, 96, 50, -125, 42, 113, 69, 64, -62, -104, 15, -98, 99, -36, 29, 10, 39, 5, -89, -90, 41, -75, -48, -124, 43, 115, -10, -19, 12, -39, -79, 32, 18, 0, 28, -99, -26, 60, 71, 50, 34, 1, -111, -36, 6, -50, 61, 121, -45, 92, 89, -18, 17, 75, 36, 53, -61, 77 }; protected Base64DataFormat format = new Base64DataFormat(); @EndpointInject("mock:result") private MockEndpoint result; protected void runEncoderTest(byte[] raw, byte[] expected) throws Exception { result.setExpectedMessageCount(1); template.sendBody("direct:startEncode", raw); MockEndpoint.assertIsSatisfied(context); byte[] encoded = result.getReceivedExchanges().get(0).getIn().getBody(byte[].class); assertArrayEquals(expected, encoded); } protected void runDecoderTest(byte[] encoded, byte[] expected) throws Exception { result.setExpectedMessageCount(1); template.sendBody("direct:startDecode", encoded); MockEndpoint.assertIsSatisfied(context); byte[] decoded = result.getReceivedExchanges().get(0).getIn().getBody(byte[].class); assertArrayEquals(expected, decoded); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:startEncode").marshal(format).to("mock:result"); from("direct:startDecode").unmarshal(format).to("mock:result"); } }; } }
Base64DataFormatTestBase
java
bumptech__glide
annotation/compiler/test/src/test/resources/GlideExtensionOptionsTest/OverrideExtendMultipleArguments/Extension.java
{ "start": 257, "end": 591 }
class ____ { private Extension() { // Utility class. } @NonNull @GlideOption(override = GlideOption.OVERRIDE_EXTEND) public static BaseRequestOptions<?> override(BaseRequestOptions<?> requestOptions, int width, int height) { return requestOptions .override(width, height) .centerCrop(); } }
Extension
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/MethodOrderer.java
{ "start": 4983, "end": 5098 }
class ____. Otherwise, it has the same effect as not specifying any * {@code MethodOrderer}. * * <p>This
directly
java
apache__camel
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/BindyFactory.java
{ "start": 2363, "end": 2530 }
class ____ to POJO objects * @throws Exception can be thrown */ String unbind(CamelContext camelContext, Map<String, Object> model) throws Exception; }
link
java
apache__flink
flink-core/src/test/java/org/apache/flink/testutils/serialization/types/ByteArrayType.java
{ "start": 1054, "end": 2343 }
class ____ implements SerializationTestType { private static final int MAX_LEN = 512 * 15; private byte[] data; public ByteArrayType() { this.data = new byte[0]; } public ByteArrayType(byte[] data) { this.data = data; } @Override public ByteArrayType getRandom(Random rnd) { final int len = rnd.nextInt(MAX_LEN) + 1; final byte[] data = new byte[len]; rnd.nextBytes(data); return new ByteArrayType(data); } @Override public int length() { return data.length + 4; } @Override public void write(DataOutputView out) throws IOException { out.writeInt(this.data.length); out.write(this.data); } @Override public void read(DataInputView in) throws IOException { final int len = in.readInt(); this.data = new byte[len]; in.readFully(this.data); } @Override public int hashCode() { return Arrays.hashCode(this.data); } @Override public boolean equals(Object obj) { if (obj instanceof ByteArrayType) { ByteArrayType other = (ByteArrayType) obj; return Arrays.equals(this.data, other.data); } else { return false; } } }
ByteArrayType
java
apache__kafka
raft/src/main/java/org/apache/kafka/raft/VoterSet.java
{ "start": 12714, "end": 18235 }
class ____ { private final ReplicaKey voterKey; private final Endpoints listeners; private final SupportedVersionRange supportedKRaftVersion; VoterNode( ReplicaKey voterKey, Endpoints listeners, SupportedVersionRange supportedKRaftVersion ) { this.voterKey = voterKey; this.listeners = listeners; this.supportedKRaftVersion = supportedKRaftVersion; } public ReplicaKey voterKey() { return voterKey; } /** * Returns if the provided replica key matches this voter node. * * If the voter node includes the directory id, the {@code replicaKey} directory id must * match the directory id specified by the voter set. * * If the voter node doesn't include the directory id ({@code Optional.empty()}), a replica * is the voter as long as the node id matches. The directory id is not checked. * * @param replicaKey the replica key * @return true if the replica key is the voter, otherwise false */ public boolean isVoter(ReplicaKey replicaKey) { if (voterKey.id() != replicaKey.id()) return false; if (voterKey.directoryId().isPresent()) { return voterKey.directoryId().equals(replicaKey.directoryId()); } else { // configured voter set doesn't include a directory id so it is a voter as long as // the ids match return true; } } /** * Returns the listeners of the voter node */ public Endpoints listeners() { return listeners; } private SupportedVersionRange supportedKRaftVersion() { return supportedKRaftVersion; } private Optional<InetSocketAddress> address(ListenerName listener) { return listeners.address(listener); } private boolean supportsVersion(KRaftVersion version) { return version.featureLevel() >= supportedKRaftVersion.min() && version.featureLevel() <= supportedKRaftVersion.max(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VoterNode that = (VoterNode) o; if (!Objects.equals(voterKey, that.voterKey)) return false; if (!Objects.equals(supportedKRaftVersion, that.supportedKRaftVersion)) return false; return Objects.equals(listeners, that.listeners); } @Override public int hashCode() { return Objects.hash(voterKey, listeners, supportedKRaftVersion); } @Override public String toString() { return String.format( "VoterNode(voterKey=%s, listeners=%s, supportedKRaftVersion=%s)", voterKey, listeners, supportedKRaftVersion ); } public static VoterNode of( ReplicaKey voterKey, Endpoints listeners, SupportedVersionRange supportedKRaftVersion ) { return new VoterNode(voterKey, listeners, supportedKRaftVersion); } } private static final VoterSet EMPTY = new VoterSet(Map.of()); public static VoterSet empty() { return EMPTY; } /** * Converts a {@code VotersRecord} to a {@code VoterSet}. * * @param voters the set of voters control record * @return the voter set */ public static VoterSet fromVotersRecord(VotersRecord voters) { HashMap<Integer, VoterNode> voterNodes = new HashMap<>(voters.voters().size()); for (VotersRecord.Voter voter: voters.voters()) { voterNodes.put( voter.voterId(), new VoterNode( ReplicaKey.of(voter.voterId(), voter.voterDirectoryId()), Endpoints.fromVotersRecordEndpoints(voter.endpoints()), new SupportedVersionRange( voter.kRaftVersionFeature().minSupportedVersion(), voter.kRaftVersionFeature().maxSupportedVersion() ) ) ); } return new VoterSet(voterNodes); } /** * Creates a voter set from a map of socket addresses. * * @param listener the listener name for all of the endpoints * @param voters the socket addresses by voter id * @return the voter set */ public static VoterSet fromInetSocketAddresses(ListenerName listener, Map<Integer, InetSocketAddress> voters) { Map<Integer, VoterNode> voterNodes = voters .entrySet() .stream() .collect( Collectors.toMap( Map.Entry::getKey, entry -> new VoterNode( ReplicaKey.of(entry.getKey(), Uuid.ZERO_UUID), Endpoints.fromInetSocketAddresses(Map.of(listener, entry.getValue())), new SupportedVersionRange((short) 0, (short) 0) ) ) ); return new VoterSet(voterNodes); } public static VoterSet fromMap(Map<Integer, VoterNode> voters) { return new VoterSet(new HashMap<>(voters)); } }
VoterNode
java
quarkusio__quarkus
extensions/spring-security/deployment/src/test/java/io/quarkus/spring/security/deployment/springapp/PersonChecker.java
{ "start": 65, "end": 189 }
interface ____ { boolean check(Person person, String input); boolean isTrue(); boolean isFalse(); }
PersonChecker
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/ValueConstants.java
{ "start": 784, "end": 1194 }
interface ____ { /** * Constant defining a value for no default - as a replacement for {@code null} which * we cannot use in annotation attributes. * <p>This is an artificial arrangement of 16 unicode characters, with its sole purpose * being to never match user-declared values. * @see Header#defaultValue() */ String DEFAULT_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n"; }
ValueConstants
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/localfs/TestLocalFSContractBulkDelete.java
{ "start": 1111, "end": 1313 }
class ____ extends AbstractContractBulkDeleteTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new LocalFSContract(conf); } }
TestLocalFSContractBulkDelete
java
playframework__playframework
web/play-filters-helpers/src/main/java/play/filters/csrf/RequireCSRFCheckAction.java
{ "start": 643, "end": 5544 }
class ____ extends Action<RequireCSRFCheck> { private final CSRFConfig config; private final SessionConfiguration sessionConfiguration; private final CSRF.TokenProvider tokenProvider; private final CSRFTokenSigner tokenSigner; private Function<RequireCSRFCheck, CSRFErrorHandler> configurator; @Inject public RequireCSRFCheckAction( CSRFConfig config, SessionConfiguration sessionConfiguration, CSRF.TokenProvider tokenProvider, CSRFTokenSigner csrfTokenSigner, Injector injector) { this( config, sessionConfiguration, tokenProvider, csrfTokenSigner, configAnnotation -> injector.instanceOf(configAnnotation.error())); } public RequireCSRFCheckAction( CSRFConfig config, SessionConfiguration sessionConfiguration, CSRF.TokenProvider tokenProvider, CSRFTokenSigner csrfTokenSigner, CSRFErrorHandler errorHandler) { this( config, sessionConfiguration, tokenProvider, csrfTokenSigner, configAnnotation -> errorHandler); } public RequireCSRFCheckAction( CSRFConfig config, SessionConfiguration sessionConfiguration, CSRF.TokenProvider tokenProvider, CSRFTokenSigner csrfTokenSigner, Function<RequireCSRFCheck, CSRFErrorHandler> configurator) { this.config = config; this.sessionConfiguration = sessionConfiguration; this.tokenProvider = tokenProvider; this.tokenSigner = csrfTokenSigner; this.configurator = configurator; } @Override public CompletionStage<Result> call(Http.Request req) { CSRFActionHelper csrfActionHelper = new CSRFActionHelper(sessionConfiguration, config, tokenSigner, tokenProvider); RequestHeader taggedRequest = csrfActionHelper.tagRequestFromHeader(req.asScala()); // Check for bypass if (!csrfActionHelper.requiresCsrfCheck(taggedRequest) || (config.checkContentType().apply(req.asScala().contentType()) != Boolean.TRUE && !csrfActionHelper.hasInvalidContentType(req.asScala()))) { return delegate.call(req); } else { // Get token from cookie/session Option<String> headerToken = csrfActionHelper.getTokenToValidate(taggedRequest); if (headerToken.isDefined()) { String tokenToCheck = null; // Get token from query string Option<String> queryStringToken = csrfActionHelper.getHeaderToken(taggedRequest); if (queryStringToken.isDefined()) { tokenToCheck = queryStringToken.get(); } else { // Get token from body if (req.body().asFormUrlEncoded() != null) { String[] values = req.body().asFormUrlEncoded().get(config.tokenName()); if (values != null && values.length > 0) { tokenToCheck = values[0]; } } else if (req.body().asMultipartFormData() != null) { Map<String, String[]> form = req.body().asMultipartFormData().asFormUrlEncoded(); String[] values = form.get(config.tokenName()); if (values != null && values.length > 0) { tokenToCheck = values[0]; } } } if (tokenToCheck != null) { if (tokenProvider.compareTokens(tokenToCheck, headerToken.get())) { return delegate.call(req); } else { return handleTokenError(req, taggedRequest, "CSRF tokens don't match"); } } else { return handleTokenError( req, taggedRequest, "CSRF token not found in body or query string"); } } else { return handleTokenError(req, taggedRequest, "CSRF token not found in session"); } } } private CompletionStage<Result> handleTokenError( Http.Request req, RequestHeader taggedRequest, String msg) { CSRFErrorHandler handler = configurator.apply(this.configuration); return handler .handle( taggedRequest .addAttr( HttpErrorHandler.Attrs$.MODULE$.HttpErrorInfo(), new HttpErrorInfo("csrf-filter")) .asJava(), msg) .thenApply( result -> { if (CSRF.getToken(taggedRequest).isEmpty()) { if (config.cookieName().isDefined()) { Option<String> domain = sessionConfiguration.domain(); return result.discardingCookie( config.cookieName().get(), sessionConfiguration.path(), domain.isDefined() ? domain.get() : null, config.secureCookie(), config.partitionedCookie()); } return result.removingFromSession(req, config.tokenName()); } return result; }); } }
RequireCSRFCheckAction
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/TestFixed.java
{ "start": 929, "end": 1867 }
class ____ { @Test void fixedDefaultValueDrop() { Schema md5 = SchemaBuilder.builder().fixed("MD5").size(16); Schema frec = SchemaBuilder.builder().record("test").fields().name("hash").type(md5).withDefault(new byte[16]) .endRecord(); Schema.Field field = frec.getField("hash"); assertNotNull(field.defaultVal()); assertArrayEquals(new byte[16], (byte[]) field.defaultVal()); } @Test void fixedLengthOutOfLimit() { Exception ex = assertThrows(UnsupportedOperationException.class, () -> Schema.createFixed("oversize", "doc", "space", Integer.MAX_VALUE)); assertEquals(TestSystemLimitException.ERROR_VM_LIMIT_BYTES, ex.getMessage()); } @Test void fixedNegativeLength() { Exception ex = assertThrows(AvroRuntimeException.class, () -> Schema.createFixed("negative", "doc", "space", -1)); assertEquals(TestSystemLimitException.ERROR_NEGATIVE, ex.getMessage()); } }
TestFixed
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/FetchGraphCollectionOrderByAndCriteriaJoinTest.java
{ "start": 7234, "end": 8211 }
class ____ { @Id Long id; Long ordinal; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") private Level1 parent; @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.PERSIST) @OrderBy("ordinal") private Set<Level3> children = new LinkedHashSet<>(); public Level2() { } public Level2(Level1 parent, Long id, Long ordinal) { this.parent = parent; this.id = id; this.ordinal = ordinal; parent.getChildren().add( this ); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Level1 getParent() { return parent; } public void setParent(Level1 parent) { this.parent = parent; } public Set<Level3> getChildren() { return children; } public Long getOrdinal() { return ordinal; } @Override public String toString() { return "Level1 #" + id + " $" + ordinal; } } @Entity(name = "Level3") static
Level2
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/class_/ClassAssert_isAbstract_Test.java
{ "start": 1069, "end": 1844 }
class ____ { @Test void should_fail_if_actual_is_null() { // GIVEN Class<?> actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).isAbstract()); // THEN then(assertionError).hasMessage(shouldNotBeNull().create()); } @Test void should_fail_if_actual_is_not_abstract() { // GIVEN Class<?> actual = Object.class; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).isAbstract()); // THEN then(assertionError).hasMessage(shouldBeAbstract(actual).create()); } @Test void should_pass_if_actual_is_abstract() { // GIVEN Class<?> actual = AbstractCollection.class; // WHEN/THEN assertThat(actual).isAbstract(); } }
ClassAssert_isAbstract_Test
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/architecture/ArchitectureRules.java
{ "start": 25141, "end": 26317 }
class ____<T extends JavaMember> extends DescribedPredicate<T> { OverridesPublicMethod() { super("overrides public method"); } @Override public boolean test(T member) { if (!(member instanceof JavaMethod javaMethod)) { return false; } Stream<JavaMethod> superClassMethods = member.getOwner() .getAllRawSuperclasses() .stream() .flatMap((superClass) -> superClass.getMethods().stream()); Stream<JavaMethod> interfaceMethods = member.getOwner() .getAllRawInterfaces() .stream() .flatMap((iface) -> iface.getMethods().stream()); return Stream.concat(superClassMethods, interfaceMethods) .anyMatch((superMethod) -> isPublic(superMethod) && isOverridden(superMethod, javaMethod)); } private boolean isPublic(JavaMethod method) { return method.getModifiers().contains(JavaModifier.PUBLIC); } private boolean isOverridden(JavaMethod superMethod, JavaMethod method) { return superMethod.getName().equals(method.getName()) && superMethod.getRawParameterTypes().size() == method.getRawParameterTypes().size() && superMethod.getDescriptor().equals(method.getDescriptor()); } } }
OverridesPublicMethod
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/spi/JdbcSelect.java
{ "start": 506, "end": 2470 }
interface ____ extends PrimaryOperation, CacheableJdbcOperation { JdbcValuesMappingProducer getJdbcValuesMappingProducer(); JdbcLockStrategy getLockStrategy(); boolean usesLimitParameters(); JdbcParameter getLimitParameter(); int getRowsToSkip(); int getMaxRows(); /** * Access to a collector of values loaded to be applied during the * processing of the selection's results. * May be {@code null}. */ @Nullable LoadedValuesCollector getLoadedValuesCollector(); /** * Perform any pre-actions. * <p/> * Generally the pre-actions should use the passed {@code jdbcStatementAccess} to interact with the * database, although the {@code jdbcConnection} can be used to create specialized statements, * access the {@linkplain java.sql.DatabaseMetaData database metadata}, etc. * * @param jdbcStatementAccess Access to a JDBC Statement object which may be used to perform the action. * @param jdbcConnection The JDBC Connection. * @param executionContext Access to contextual information useful while executing. */ void performPreActions(StatementAccess jdbcStatementAccess, Connection jdbcConnection, ExecutionContext executionContext); /** * Perform any post-actions. * <p/> * Generally the post-actions should use the passed {@code jdbcStatementAccess} to interact with the * database, although the {@code jdbcConnection} can be used to create specialized statements, * access the {@linkplain java.sql.DatabaseMetaData database metadata}, etc. * * @param succeeded Whether the primary operation succeeded. * @param jdbcStatementAccess Access to a JDBC Statement object which may be used to perform the action. * @param jdbcConnection The JDBC Connection. * @param executionContext Access to contextual information useful while executing. */ void performPostAction( boolean succeeded, StatementAccess jdbcStatementAccess, Connection jdbcConnection, ExecutionContext executionContext); }
JdbcSelect
java
google__guice
core/test/com/google/inject/ScopesTest.java
{ "start": 41605, "end": 41760 }
class ____ { /** Relies on Guice implementation to inject S first, which provides a barrier . */ @Inject J2(K1 k) {} } @Singleton static
J2
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/WindowPropertiesRules.java
{ "start": 2424, "end": 2796 }
class ____ { public static final WindowPropertiesHavingRule WINDOW_PROPERTIES_HAVING_RULE = WindowPropertiesHavingRule.WindowPropertiesHavingRuleConfig.DEFAULT.toRule(); public static final WindowPropertiesRule WINDOW_PROPERTIES_RULE = WindowPropertiesRule.WindowPropertiesRuleConfig.DEFAULT.toRule(); public static
WindowPropertiesRules
java
spring-projects__spring-boot
module/spring-boot-jackson/src/test/java/org/springframework/boot/jackson/NameAndAgeJacksonKeyComponent.java
{ "start": 1204, "end": 1421 }
class ____ extends ValueSerializer<NameAndAge> { @Override public void serialize(NameAndAge value, JsonGenerator jgen, SerializationContext serializers) { jgen.writeName(value.asKey()); } } static
Serializer
java
apache__camel
components/camel-attachments/src/test/java/org/apache/camel/attachment/SimpleAttachmentTest.java
{ "start": 1037, "end": 6302 }
class ____ extends LanguageTestSupport { @Override protected String getLanguageName() { return "simple"; } @Override protected void populateExchange(Exchange exchange) { super.populateExchange(exchange); DefaultAttachment da = new DefaultAttachment(new DataHandler(new CamelFileDataSource(new File("src/test/data/message1.xml")))); da.addHeader("orderId", "123"); exchange.getIn(AttachmentMessage.class).addAttachmentObject("message1.xml", da); da = new DefaultAttachment(new DataHandler(new CamelFileDataSource(new File("src/test/data/message2.xml")))); da.addHeader("orderId", "456"); exchange.getIn(AttachmentMessage.class).addAttachmentObject("message2.xml", da); da = new DefaultAttachment(new DataHandler(new CamelFileDataSource(new File("src/test/data/123.txt")))); da.addHeader("orderId", "0"); exchange.getIn(AttachmentMessage.class).addAttachmentObject("123.txt", da); } @Test public void testAttachments() throws Exception { var map = exchange.getMessage(AttachmentMessage.class).getAttachments(); assertExpression("${attachments}", map); assertExpression("${attachments.size}", 3); assertExpression("${attachments.length}", 3); exchange.getMessage(AttachmentMessage.class).removeAttachment("message1.xml"); assertExpression("${attachments.size}", 2); assertExpression("${attachments.length}", 2); exchange.getMessage(AttachmentMessage.class).removeAttachment("message2.xml"); assertExpression("${attachments.size}", 1); assertExpression("${attachments.length}", 1); exchange.getMessage(AttachmentMessage.class).removeAttachment("123.txt"); assertExpression("${attachments.size}", 0); assertExpression("${attachments.length}", 0); } @Test public void testAttachmentContent() throws Exception { var map = exchange.getMessage(AttachmentMessage.class).getAttachments(); Object is1 = map.get("message1.xml").getContent(); String xml1 = context.getTypeConverter().convertTo(String.class, is1); Object is2 = map.get("message2.xml").getContent(); String xml2 = context.getTypeConverter().convertTo(String.class, is2); assertExpression("${attachmentContent(message1.xml)}", xml1); assertExpression("${attachmentContentAs(message2.xml,String)}", xml2); assertExpression("${attachmentContentAsText(message2.xml)}", xml2); assertExpression("${attachmentContent(123.txt)}", "456"); assertExpression("${attachmentContentAs(123.txt,String)}", "456"); assertExpression("${attachmentContentAsText(123.txt)}", "456"); } @Test public void testAttachmentContentHeader() throws Exception { assertExpression("${attachmentHeader(message1.xml,orderId)}", "123"); assertExpression("${attachmentHeader(message1.xml,foo)}", null); assertExpression("${attachmentHeaderAs(message2.xml,orderId,int)}", 456); assertExpression("${attachmentHeader(123.txt,orderId)}", 0); assertExpression("${attachmentHeader(123.txt,unknown)}", null); } @Test public void testAttachmentContentType() throws Exception { assertExpression("${attachmentContentType(message1.xml)}", "application/xml"); assertExpression("${attachmentContentType(message2.xml)}", "application/xml"); assertExpression("${attachmentContentType(123.txt)}", "text/plain"); } @Test public void testAttachmentOgnlByName() throws Exception { var map = exchange.getMessage(AttachmentMessage.class).getAttachments(); Object is1 = map.get("message1.xml").getContent(); String xml1 = context.getTypeConverter().convertTo(String.class, is1); Object is2 = map.get("message2.xml").getContent(); String xml2 = context.getTypeConverter().convertTo(String.class, is2); assertExpression("${attachment[message1.xml].name}", "message1.xml"); assertExpression("${attachment[message1.xml].contentType}", "application/xml"); assertExpression("${attachment[message1.xml].content}", xml1); assertExpression("${attachment[message2.xml].name}", "message2.xml"); assertExpression("${attachment[message2.xml].contentType}", "application/xml"); assertExpression("${attachment[message2.xml].content}", xml2); assertExpression("${attachment[123.txt].name}", "123.txt"); assertExpression("${attachment[123.txt].contentType}", "text/plain"); assertExpression("${attachment[123.txt].content}", "456"); } @Test public void testAttachmentOgnlByIndex() throws Exception { assertExpression("${attachment[0].name}", "message1.xml"); assertExpression("${attachment[0].contentType}", "application/xml"); assertExpression("${attachment[1].name}", "message2.xml"); assertExpression("${attachment[1].contentType}", "application/xml"); assertExpression("${attachment[2].name}", "123.txt"); assertExpression("${attachment[2].contentType}", "text/plain"); assertExpression("${attachment[2].content}", "456"); } }
SimpleAttachmentTest
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java
{ "start": 10137, "end": 12034 }
class ____. // I suspect that we could make this exception message nicer. assertThat(e).hasMessage("Unable to create mock instance of type 'UsesTwoBases'"); assertThat(e.getCause()) .hasMessageContaining( "Multiple constructors could be matched to arguments of types " + "[org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase, " + "org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase]") .hasMessageContaining( "If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.\n" + "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.\n" + "See https://github.com/mockito/mockito/issues/685"); } } @Test public void mocking_inner_classes_with_wrong_outer_instance() { try { // when mock( InnerClass.class, withSettings() .useConstructor() .outerInstance(123) .defaultAnswer(CALLS_REAL_METHODS)); // then fail(); } catch (MockitoException e) { assertThat(e).hasMessage("Unable to create mock instance of type 'InnerClass'"); // TODO it would be nice if all useful information was in the top level exception, // instead of in the exception's cause // also applies to other scenarios in this test assertThat(e.getCause()) .hasMessageContaining( "Please ensure that the target
name
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/RewriteMinusAllRule.java
{ "start": 2200, "end": 6232 }
class ____ extends RelRule<RewriteMinusAllRule.RewriteMinusAllRuleConfig> { public static final RewriteMinusAllRule INSTANCE = RewriteMinusAllRuleConfig.DEFAULT.toRule(); protected RewriteMinusAllRule(RewriteMinusAllRuleConfig config) { super(config); } @Override public boolean matches(RelOptRuleCall call) { Minus minus = call.rel(0); return minus.all && minus.getInputs().size() == 2; } @Override public void onMatch(RelOptRuleCall call) { Minus minus = call.rel(0); RelNode left = minus.getInput(0); RelNode right = minus.getInput(1); List<Integer> fields = Util.range(minus.getRowType().getFieldCount()); final FlinkRelBuilder flinkRelBuilder = FlinkRelBuilder.of(call.rel(0).getCluster(), null); // 1. add marker to left rel node RelBuilder leftBuilder = flinkRelBuilder.transform(u -> u.withConvertCorrelateToJoin(false)); RelNode leftWithAddedVirtualCols = leftBuilder .push(left) .project( Stream.concat( leftBuilder.fields(fields).stream(), Stream.of( leftBuilder.alias( leftBuilder.cast( leftBuilder.literal(1L), BIGINT), "vcol_marker"))) .collect(Collectors.toList())) .build(); // 2. add vcol_marker to right rel node RelBuilder rightBuilder = flinkRelBuilder.transform(u -> u.withConvertCorrelateToJoin(false)); RelNode rightWithAddedVirtualCols = rightBuilder .push(right) .project( Stream.concat( rightBuilder.fields(fields).stream(), Stream.of( rightBuilder.alias( leftBuilder.cast( leftBuilder.literal(-1L), BIGINT), "vcol_marker"))) .collect(Collectors.toList())) .build(); // 3. add union all and aggregate RelBuilder builder = flinkRelBuilder.transform(u -> u.withConvertCorrelateToJoin(false)); builder.push(leftWithAddedVirtualCols) .push(rightWithAddedVirtualCols) .union(true) .aggregate( builder.groupKey(builder.fields(fields)), builder.sum(false, "sum_vcol_marker", builder.field("vcol_marker"))) .filter( builder.call( GREATER_THAN, builder.field("sum_vcol_marker"), builder.literal(0))) .project( Stream.concat( Stream.of(builder.field("sum_vcol_marker")), builder.fields(fields).stream()) .collect(Collectors.toList())); // 4. add table function to replicate rows RelNode output = SetOpRewriteUtil.replicateRows(builder, minus.getRowType(), fields); call.transformTo(output); } /** Rule configuration. */ @Value.Immutable(singleton = false) public
RewriteMinusAllRule
java
dropwizard__dropwizard
dropwizard-views-mustache/src/main/java/io/dropwizard/views/mustache/MustacheViewRenderer.java
{ "start": 940, "end": 3136 }
class ____ implements ViewRenderer { private static final Pattern FILE_PATTERN = Pattern.compile("\\.mustache"); private final LoadingCache<Class<? extends View>, MustacheFactory> factories; private boolean useCache = true; private Optional<File> fileRoot = Optional.empty(); public MustacheViewRenderer() { this.factories = Caffeine.newBuilder().build(new CacheLoader<Class<? extends View>, MustacheFactory>() { @Override public MustacheFactory load(Class<? extends View> key) throws Exception { return createNewMustacheFactory(key); } }); } @Override public boolean isRenderable(View view) { return FILE_PATTERN.matcher(view.getTemplateName()).find(); } @Override public void render(View view, Locale locale, OutputStream output) throws IOException { try { final MustacheFactory mustacheFactory = useCache ? factories.get(view.getClass()) : createNewMustacheFactory(view.getClass()); final Mustache template = mustacheFactory.compile(view.getTemplateName()); final Charset charset = view.getCharset().orElse(StandardCharsets.UTF_8); try (OutputStreamWriter writer = new OutputStreamWriter(output, charset)) { template.execute(writer, view); } } catch (Throwable e) { throw new ViewRenderException("Mustache template error: " + view.getTemplateName(), e); } } @Override public void configure(Map<String, String> options) { useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true); fileRoot = Optional.ofNullable(options.get("fileRoot")).map(File::new); } boolean isUseCache() { return useCache; } @Override public String getConfigurationKey() { return "mustache"; } private MustacheFactory createNewMustacheFactory(Class<? extends View> key) { return new DefaultMustacheFactory( fileRoot.isPresent() ? new FileSystemResolver(fileRoot.get()) : new PerClassMustacheResolver(key)); } }
MustacheViewRenderer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/seqno/RetentionLeaseSyncAction.java
{ "start": 3015, "end": 8419 }
class ____ extends TransportWriteAction< RetentionLeaseSyncAction.Request, RetentionLeaseSyncAction.Request, RetentionLeaseSyncAction.Response> { public static final String ACTION_NAME = "indices:admin/seq_no/retention_lease_sync"; private static final Logger LOGGER = LogManager.getLogger(RetentionLeaseSyncAction.class); @Inject public RetentionLeaseSyncAction( final Settings settings, final TransportService transportService, final ClusterService clusterService, final IndicesService indicesService, final ThreadPool threadPool, final ShardStateAction shardStateAction, final ActionFilters actionFilters, final IndexingPressure indexingPressure, final SystemIndices systemIndices, final ProjectResolver projectResolver ) { super( settings, ACTION_NAME, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters, RetentionLeaseSyncAction.Request::new, RetentionLeaseSyncAction.Request::new, new ManagementOnlyExecutorFunction(threadPool), PrimaryActionExecution.Force, indexingPressure, systemIndices, projectResolver, ReplicaActionExecution.BypassCircuitBreaker ); } @Override protected void doExecute(Task parentTask, Request request, ActionListener<Response> listener) { assert false : "use RetentionLeaseSyncAction#sync"; } final void sync( ShardId shardId, String primaryAllocationId, long primaryTerm, RetentionLeases retentionLeases, ActionListener<ReplicationResponse> listener ) { try (var ignore = threadPool.getThreadContext().newEmptySystemContext()) { // we have to execute under the system context so that if security is enabled the sync is authorized final Request request = new Request(shardId, retentionLeases); final ReplicationTask task = (ReplicationTask) taskManager.register("transport", "retention_lease_sync", request); transportService.sendChildRequest( clusterService.localNode(), transportPrimaryAction, new ConcreteShardRequest<>(request, primaryAllocationId, primaryTerm), task, transportOptions, new TransportResponseHandler<ReplicationResponse>() { @Override public ReplicationResponse read(StreamInput in) throws IOException { return newResponseInstance(in); } @Override public Executor executor() { return TransportResponseHandler.TRANSPORT_WORKER; } @Override public void handleResponse(ReplicationResponse response) { task.setPhase("finished"); taskManager.unregister(task); listener.onResponse(response); } @Override public void handleException(TransportException e) { LOGGER.log(getExceptionLogLevel(e), () -> format("%s retention lease sync failed", shardId), e); task.setPhase("finished"); taskManager.unregister(task); listener.onFailure(e); } } ); } } static Level getExceptionLogLevel(Exception e) { return ExceptionsHelper.unwrap( e, NodeClosedException.class, IndexNotFoundException.class, AlreadyClosedException.class, IndexShardClosedException.class, ShardNotInPrimaryModeException.class, ReplicationOperation.RetryOnPrimaryException.class ) == null ? Level.WARN : Level.DEBUG; } @Override protected void dispatchedShardOperationOnPrimary( Request request, IndexShard primary, ActionListener<PrimaryResult<Request, Response>> listener ) { ActionListener.completeWith(listener, () -> { assert request.waitForActiveShards().equals(ActiveShardCount.NONE) : request.waitForActiveShards(); Objects.requireNonNull(request); Objects.requireNonNull(primary); primary.persistRetentionLeases(); return new WritePrimaryResult<>(request, new Response(), null, primary, LOGGER, postWriteRefresh); }); } @Override protected void dispatchedShardOperationOnReplica(Request request, IndexShard replica, ActionListener<ReplicaResult> listener) { ActionListener.completeWith(listener, () -> { Objects.requireNonNull(request); Objects.requireNonNull(replica); replica.updateRetentionLeasesOnReplica(request.getRetentionLeases()); replica.persistRetentionLeases(); return new WriteReplicaResult<>(request, null, null, replica, LOGGER); }); } @Override public ClusterBlockLevel indexBlockLevel() { return null; } public static final
RetentionLeaseSyncAction
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/PropertiesAvailableEverywhereTest.java
{ "start": 1038, "end": 2956 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); final Properties properties = new Properties(); properties.put("foo", "bar"); camelContext.getRegistry().bind("myProp", properties); camelContext.getPropertiesComponent().addLocation("ref:myProp"); return camelContext; } @Test public void testPropertiesInPredicates() throws Exception { getMockEndpoint("mock:header-ok").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:choice-ok").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:direct-ok").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:ko").expectedMessageCount(0); template.sendBody("direct:header-start", "Hello Camel"); template.sendBody("direct:choice-start", "Hello Camel"); template.sendBody("direct:direct-start", "Hello Camel"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // Properties in headers from("direct:header-start").setHeader("foo", simple("{{foo}}")).choice().when(simple("${header.foo} == 'bar'")) .to("mock:header-ok").otherwise().to("mock:ko"); // Properties in choices from("direct:choice-start").choice().when(simple("'{{foo}}' == 'bar'")).to("mock:choice-ok").otherwise() .to("mock:ko"); // Properties in URI from("direct:direct-start").to("direct:direct-{{foo}}"); from("direct:direct-bar").to("mock:direct-ok"); } }; } }
PropertiesAvailableEverywhereTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/metadata/MetadataSerializers.java
{ "start": 1120, "end": 2616 }
class ____ { private static final Map<Integer, MetadataSerializer> SERIALIZERS = CollectionUtil.newHashMapWithExpectedSize(6); static { registerSerializer(MetadataV1Serializer.INSTANCE); registerSerializer(MetadataV2Serializer.INSTANCE); registerSerializer(MetadataV3Serializer.INSTANCE); registerSerializer(MetadataV4Serializer.INSTANCE); registerSerializer(MetadataV5Serializer.INSTANCE); registerSerializer(MetadataV6Serializer.INSTANCE); } private static void registerSerializer(MetadataSerializer serializer) { SERIALIZERS.put(serializer.getVersion(), serializer); } /** * Returns the {@link MetadataSerializer} for the given savepoint version. * * @param version Savepoint version to get serializer for * @return Savepoint for the given version * @throws IllegalArgumentException If unknown savepoint version */ public static MetadataSerializer getSerializer(int version) { MetadataSerializer serializer = SERIALIZERS.get(version); if (serializer != null) { return serializer; } else { throw new IllegalArgumentException( "Unrecognized checkpoint version number: " + version); } } // ------------------------------------------------------------------------ /** Utility method class, not meant to be instantiated. */ private MetadataSerializers() {} }
MetadataSerializers
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/PatternMatchingInstanceofTest.java
{ "start": 5189, "end": 5584 }
class ____ { void test(Object o) { if (!(o instanceof Test test)) { return; } test(test); } } """) .doTest(); } @Test public void negatedIf_butNoDefiniteReturn_noFinding() { helper .addInputLines( "Test.java", """
Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/MapDeserializerTest.java
{ "start": 581, "end": 668 }
class ____ extends HashMap { public MyMap () { } } }
MyMap
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/ColumnReference.java
{ "start": 1323, "end": 4543 }
class ____ implements OrderingExpression, SequencePart { private final String columnExpression; private final boolean isColumnExpressionFormula; public ColumnReference(String columnExpression, boolean isColumnExpressionFormula) { this.columnExpression = columnExpression; this.isColumnExpressionFormula = isColumnExpressionFormula; } public String getColumnExpression() { return columnExpression; } public boolean isColumnExpressionFormula() { return isColumnExpressionFormula; } @Override public Expression resolve( QuerySpec ast, TableGroup tableGroup, String modelPartName, SqlAstCreationState creationState) { final TableReference tableReference = getTableReference( tableGroup ); final SqlExpressionResolver sqlExpressionResolver = creationState.getSqlExpressionResolver(); return sqlExpressionResolver.resolveSqlExpression( createColumnReferenceKey( tableReference, columnExpression, NullType.INSTANCE ), sqlAstProcessingState -> new org.hibernate.sql.ast.tree.expression.ColumnReference( tableReference, columnExpression, isColumnExpressionFormula, // because these ordering fragments are only ever part of the order-by clause, there // is no need for the JdbcMapping null, null ) ); } @Override public SequencePart resolvePathPart( String name, String identifier, boolean isTerminal, TranslationContext translationContext) { throw new UnsupportedMappingException( "ColumnReference cannot be de-referenced" ); } @Override public void apply( QuerySpec ast, TableGroup tableGroup, String collation, String modelPartName, SortDirection sortOrder, Nulls nullPrecedence, SqlAstCreationState creationState) { final Expression expression = resolve( ast, tableGroup, modelPartName, creationState ); // It makes no sense to order by an expression multiple times // SQL Server even reports a query error in this case if ( ast.hasSortSpecifications() ) { for ( SortSpecification sortSpecification : ast.getSortSpecifications() ) { if ( sortSpecification.getSortExpression() == expression ) { return; } } } final Expression sortExpression = OrderingExpression.applyCollation( expression, collation, creationState ); ast.addSortSpecification( new SortSpecification( sortExpression, sortOrder, nullPrecedence ) ); } TableReference getTableReference(TableGroup tableGroup) { ModelPartContainer modelPart = tableGroup.getModelPart(); if ( modelPart instanceof PluralAttributeMapping pluralAttribute ) { if ( !pluralAttribute.getCollectionDescriptor().hasManyToManyOrdering() ) { return tableGroup.getPrimaryTableReference(); } if ( pluralAttribute.getElementDescriptor().getPartMappingType() instanceof EntityPersister entityPersister ) { final String tableName = entityPersister.getTableNameForColumn( columnExpression ); return tableGroup.getTableReference( tableGroup.getNavigablePath(), tableName ); } else { return tableGroup.getPrimaryTableReference(); } } return null; } @Override public String toDescriptiveText() { return "column reference (" + columnExpression + ")"; } }
ColumnReference
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/DateUtils.java
{ "start": 2500, "end": 4097 }
class ____ implements Iterator<Calendar> { private final Calendar endFinal; private final Calendar spot; /** * Constructs a DateIterator that ranges from one date to another. * * @param startFinal start date (inclusive). * @param endFinal end date (inclusive). */ DateIterator(final Calendar startFinal, final Calendar endFinal) { this.endFinal = endFinal; spot = startFinal; spot.add(Calendar.DATE, -1); } /** * Has the iterator not reached the end date yet? * * @return {@code true} if the iterator has yet to reach the end date. */ @Override public boolean hasNext() { return spot.before(endFinal); } /** * Returns the next calendar in the iteration. * * @return Object calendar for the next date. */ @Override public Calendar next() { if (spot.equals(endFinal)) { throw new NoSuchElementException(); } spot.add(Calendar.DATE, 1); return (Calendar) spot.clone(); } /** * Always throws UnsupportedOperationException. * * @throws UnsupportedOperationException Always thrown. * @see java.util.Iterator#remove() */ @Override public void remove() { throw new UnsupportedOperationException(); } } /** * Calendar modification types. */ private
DateIterator
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/GetTransformAction.java
{ "start": 2222, "end": 5149 }
class ____ extends AbstractGetResourcesRequest { // for legacy purposes, this transport action previously had no timeout private static final TimeValue LEGACY_TIMEOUT_VALUE = TimeValue.MAX_VALUE; private static final int MAX_SIZE_RETURN = 1000; private final boolean checkForDanglingTasks; private final TimeValue timeout; public Request(String id) { this(id, false, LEGACY_TIMEOUT_VALUE); } public Request(String id, boolean checkForDanglingTasks, TimeValue timeout) { super(id, PageParams.defaultParams(), true); this.checkForDanglingTasks = checkForDanglingTasks; this.timeout = timeout; } public Request(StreamInput in) throws IOException { super(in); this.checkForDanglingTasks = in.getTransportVersion().onOrAfter(DANGLING_TASKS) ? in.readBoolean() : true; this.timeout = in.getTransportVersion().onOrAfter(DANGLING_TASKS) ? in.readTimeValue() : LEGACY_TIMEOUT_VALUE; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (out.getTransportVersion().onOrAfter(DANGLING_TASKS)) { out.writeBoolean(checkForDanglingTasks); out.writeTimeValue(timeout); } } public String getId() { return getResourceId(); } public boolean checkForDanglingTasks() { return checkForDanglingTasks; } public TimeValue timeout() { return timeout; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException exception = null; if (getPageParams() != null && getPageParams().getSize() > MAX_SIZE_RETURN) { exception = addValidationError( "Param [" + PageParams.SIZE.getPreferredName() + "] has a max acceptable value of [" + MAX_SIZE_RETURN + "]", exception ); } return exception; } @Override public String getCancelableTaskDescription() { return format("get_transforms[%s]", getResourceId()); } @Override public String getResourceIdField() { return TransformField.ID.getPreferredName(); } @Override public boolean equals(Object obj) { return this == obj || (obj instanceof Request other && super.equals(obj) && (checkForDanglingTasks == other.checkForDanglingTasks) && Objects.equals(timeout, other.timeout)); } @Override public int hashCode() { return Objects.hash(super.hashCode(), checkForDanglingTasks, timeout); } } public static
Request
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 4772, "end": 7827 }
interface ____ was found for the key. * @since 6.2 */ private static final Map<Method, Method> publicInterfaceMethodCache = new ConcurrentReferenceHashMap<>(256); /** * Cache for equivalent public methods in a public declaring type within the type hierarchy * of the method's declaring class. * <p>A {@code null} value signals that no publicly accessible method was found for the key. * @since 6.2 */ private static final Map<Method, Method> publiclyAccessibleMethodCache = new ConcurrentReferenceHashMap<>(256); static { primitiveWrapperTypeMap.put(Boolean.class, boolean.class); primitiveWrapperTypeMap.put(Byte.class, byte.class); primitiveWrapperTypeMap.put(Character.class, char.class); primitiveWrapperTypeMap.put(Double.class, double.class); primitiveWrapperTypeMap.put(Float.class, float.class); primitiveWrapperTypeMap.put(Integer.class, int.class); primitiveWrapperTypeMap.put(Long.class, long.class); primitiveWrapperTypeMap.put(Short.class, short.class); primitiveWrapperTypeMap.put(Void.class, void.class); // Map entry iteration is less expensive to initialize than forEach with lambdas for (Map.Entry<Class<?>, Class<?>> entry : primitiveWrapperTypeMap.entrySet()) { primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey()); registerCommonClasses(entry.getKey()); } Set<Class<?>> primitiveTypes = new HashSet<>(32); primitiveTypes.addAll(primitiveWrapperTypeMap.values()); Collections.addAll(primitiveTypes, boolean[].class, byte[].class, char[].class, double[].class, float[].class, int[].class, long[].class, short[].class); for (Class<?> primitiveType : primitiveTypes) { primitiveTypeNameMap.put(primitiveType.getName(), primitiveType); } registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class, Float[].class, Integer[].class, Long[].class, Short[].class); registerCommonClasses(Number.class, Number[].class, String.class, String[].class, Class.class, Class[].class, Object.class, Object[].class); registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class, Error.class, StackTraceElement.class, StackTraceElement[].class); registerCommonClasses(Enum.class, Iterable.class, Iterator.class, Enumeration.class, Collection.class, List.class, Set.class, Map.class, Map.Entry.class, Optional.class); Class<?>[] javaLanguageInterfaceArray = {Serializable.class, Externalizable.class, Closeable.class, AutoCloseable.class, Cloneable.class, Comparable.class}; registerCommonClasses(javaLanguageInterfaceArray); javaLanguageInterfaces = Set.of(javaLanguageInterfaceArray); } /** * Register the given common classes with the ClassUtils cache. */ private static void registerCommonClasses(Class<?>... commonClasses) { for (Class<?> clazz : commonClasses) { commonClassCache.put(clazz.getName(), clazz); } } /** * Return the default ClassLoader to use: typically the thread context * ClassLoader, if available; the ClassLoader that loaded the ClassUtils *
method
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/server/reactive/ListenerWriteProcessorTests.java
{ "start": 1161, "end": 3071 }
class ____ { private final TestListenerWriteProcessor processor = new TestListenerWriteProcessor(); private final TestResultSubscriber resultSubscriber = new TestResultSubscriber(); private final TestSubscription subscription = new TestSubscription(); @BeforeEach void setup() { this.processor.subscribe(this.resultSubscriber); this.processor.onSubscribe(this.subscription); assertThat(subscription.getDemand()).isEqualTo(1); } @Test // SPR-17410 public void writePublisherError() { // Turn off writing so next item will be cached this.processor.setWritePossible(false); DataBuffer buffer = mock(); this.processor.onNext(buffer); // Send error while item cached this.processor.onError(new IllegalStateException()); assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); assertThat(this.processor.getDiscardedBuffers()).containsExactly(buffer); } @Test // SPR-17410 public void ioExceptionDuringWrite() { // Fail on next write this.processor.setWritePossible(true); this.processor.setFailOnWrite(true); // Write DataBuffer buffer = mock(); this.processor.onNext(buffer); assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); assertThat(this.processor.getDiscardedBuffers()).containsExactly(buffer); } @Test // SPR-17410 public void onNextWithoutDemand() { // Disable writing: next item will be cached. this.processor.setWritePossible(false); DataBuffer buffer1 = mock(); this.processor.onNext(buffer1); // Send more data illegally DataBuffer buffer2 = mock(); this.processor.onNext(buffer2); assertThat(this.resultSubscriber.getError()).as("Error should flow to result publisher").isNotNull(); assertThat(this.processor.getDiscardedBuffers()).containsExactly(buffer2, buffer1); } private static final
ListenerWriteProcessorTests
java
apache__rocketmq
namesrv/src/test/java/org/apache/rocketmq/namesrv/routeinfo/RouteInfoManagerBrokerPermTest.java
{ "start": 1304, "end": 4051 }
class ____ extends RouteInfoManagerTestBase { private static RouteInfoManager routeInfoManager; public static String clusterName = "cluster"; public static String brokerPrefix = "broker"; public static String topicPrefix = "topic"; public static RouteInfoManagerTestBase.Cluster cluster; @Before public void setup() { routeInfoManager = new RouteInfoManager(new NamesrvConfig(), null); cluster = registerCluster(routeInfoManager, clusterName, brokerPrefix, 3, 3, topicPrefix, 10); } @After public void terminate() { routeInfoManager.printAllPeriodically(); for (BrokerData bd : cluster.brokerDataMap.values()) { unregisterBrokerAll(routeInfoManager, bd); } } @Test public void testAddWritePermOfBrokerByLock() throws Exception { String brokerName = getBrokerName(brokerPrefix, 0); String topicName = getTopicName(topicPrefix, 0); QueueData qd = new QueueData(); qd.setPerm(PermName.PERM_READ); qd.setBrokerName(brokerName); HashMap<String, Map<String, QueueData>> topicQueueTable = new HashMap<>(); Map<String, QueueData> queueDataMap = new HashMap<>(); queueDataMap.put(brokerName, qd); topicQueueTable.put(topicName, queueDataMap); Field filed = RouteInfoManager.class.getDeclaredField("topicQueueTable"); filed.setAccessible(true); filed.set(routeInfoManager, topicQueueTable); int addTopicCnt = routeInfoManager.addWritePermOfBrokerByLock(brokerName); assertThat(addTopicCnt).isEqualTo(1); assertThat(qd.getPerm()).isEqualTo(PermName.PERM_READ | PermName.PERM_WRITE); } @Test public void testWipeWritePermOfBrokerByLock() throws Exception { String brokerName = getBrokerName(brokerPrefix, 0); String topicName = getTopicName(topicPrefix, 0); QueueData qd = new QueueData(); qd.setPerm(PermName.PERM_READ); qd.setBrokerName(brokerName); HashMap<String, Map<String, QueueData>> topicQueueTable = new HashMap<>(); Map<String, QueueData> queueDataMap = new HashMap<>(); queueDataMap.put(brokerName, qd); topicQueueTable.put(topicName, queueDataMap); Field filed = RouteInfoManager.class.getDeclaredField("topicQueueTable"); filed.setAccessible(true); filed.set(routeInfoManager, topicQueueTable); int addTopicCnt = routeInfoManager.wipeWritePermOfBrokerByLock(brokerName); assertThat(addTopicCnt).isEqualTo(1); assertThat(qd.getPerm()).isEqualTo(PermName.PERM_READ); } }
RouteInfoManagerBrokerPermTest
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/admin/MockAdminClient.java
{ "start": 69788, "end": 73174 }
class ____ { final Uuid topicId; final boolean isInternalTopic; final List<TopicPartitionInfo> partitions; final List<String> partitionLogDirs; Map<String, String> configs; int fetchesRemainingUntilVisible; public boolean markedForDeletion; TopicMetadata(Uuid topicId, boolean isInternalTopic, List<TopicPartitionInfo> partitions, List<String> partitionLogDirs, Map<String, String> configs) { this.topicId = topicId; this.isInternalTopic = isInternalTopic; this.partitions = partitions; this.partitionLogDirs = partitionLogDirs; this.configs = configs != null ? configs : Collections.emptyMap(); this.markedForDeletion = false; this.fetchesRemainingUntilVisible = 0; } } public synchronized void setMockMetrics(MetricName name, Metric metric) { mockMetrics.put(name, metric); } public void disableTelemetry() { telemetryDisabled = true; } /** * @param injectTimeoutExceptionCounter use -1 for infinite */ public void injectTimeoutException(final int injectTimeoutExceptionCounter) { this.injectTimeoutExceptionCounter = injectTimeoutExceptionCounter; } public void advanceTimeOnClientInstanceId(final Time mockTime, final long blockingTimeMs) { this.mockTime = mockTime; this.blockingTimeMs = blockingTimeMs; } public void setClientInstanceId(final Uuid instanceId) { clientInstanceId = instanceId; } @Override public Uuid clientInstanceId(Duration timeout) { if (telemetryDisabled) { throw new IllegalStateException(); } if (clientInstanceId == null) { throw new UnsupportedOperationException("clientInstanceId not set"); } if (injectTimeoutExceptionCounter != 0) { // -1 is used as "infinite" if (injectTimeoutExceptionCounter > 0) { --injectTimeoutExceptionCounter; } throw new TimeoutException(); } if (mockTime != null) { mockTime.sleep(blockingTimeMs); } return clientInstanceId; } @Override public synchronized Map<MetricName, ? extends Metric> metrics() { return mockMetrics; } public synchronized void setFetchesRemainingUntilVisible(String topicName, int fetchesRemainingUntilVisible) { TopicMetadata metadata = allTopics.get(topicName); if (metadata == null) { throw new RuntimeException("No such topic as " + topicName); } metadata.fetchesRemainingUntilVisible = fetchesRemainingUntilVisible; } public synchronized List<Node> brokers() { return new ArrayList<>(brokers); } public synchronized Node broker(int index) { return brokers.get(index); } public List<KafkaMetric> addedMetrics() { return Collections.unmodifiableList(addedMetrics); } @Override public void registerMetricForSubscription(KafkaMetric metric) { addedMetrics.add(metric); } @Override public void unregisterMetricFromSubscription(KafkaMetric metric) { addedMetrics.remove(metric); } }
TopicMetadata
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/functions/RichFlatJoinFunction.java
{ "start": 1426, "end": 1712 }
class ____<IN1, IN2, OUT> extends AbstractRichFunction implements FlatJoinFunction<IN1, IN2, OUT> { private static final long serialVersionUID = 1L; @Override public abstract void join(IN1 first, IN2 second, Collector<OUT> out) throws Exception; }
RichFlatJoinFunction
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyBindingModeJsonWithContractTest.java
{ "start": 1452, "end": 3505 }
class ____ extends BaseJettyTest { @Test public void testBindingModeJsonWithContract() throws Exception { MockEndpoint mock = getMockEndpoint("mock:input"); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(UserPojoEx.class); String body = "{\"id\": 123, \"name\": \"Donald Duck\"}"; Object answer = template.requestBody("http://localhost:" + getPort() + "/users/new", body); assertNotNull(answer); BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) answer)); String line; String answerString = ""; while ((line = reader.readLine()) != null) { answerString += line; } assertTrue(answerString.contains("\"active\":true"), "Unexpected response: " + answerString); MockEndpoint.assertIsSatisfied(context); Object obj = mock.getReceivedExchanges().get(0).getIn().getBody(); assertEquals(UserPojoEx.class, obj.getClass()); UserPojoEx user = (UserPojoEx) obj; assertNotNull(user); assertEquals(123, user.getId()); assertEquals("Donald Duck", user.getName()); assertTrue(user.isActive()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.getTypeConverterRegistry().addTypeConverters(new MyTypeConverters()); restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json); rest("/users/") // REST binding converts from JSON to UserPojo .post("new").type(UserPojo.class).to("direct:new"); from("direct:new") // then contract advice converts from UserPojo to UserPojoEx .inputType(UserPojoEx.class).to("mock:input"); } }; } public static
RestJettyBindingModeJsonWithContractTest
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/internal/instant/InstantPatternThreadLocalCachedFormatterTest.java
{ "start": 2010, "end": 17457 }
class ____ { private static final Locale LOCALE = Locale.getDefault(); private static final TimeZone TIME_ZONE = TimeZone.getDefault(); @ParameterizedTest @MethodSource("getterTestCases") void getters_should_work( final Function<InstantPatternFormatter, InstantPatternThreadLocalCachedFormatter> cachedFormatterSupplier, final String pattern, final Locale locale, final TimeZone timeZone) { final InstantPatternDynamicFormatter dynamicFormatter = new InstantPatternDynamicFormatter(pattern, locale, timeZone); final InstantPatternThreadLocalCachedFormatter cachedFormatter = cachedFormatterSupplier.apply(dynamicFormatter); assertThat(cachedFormatter.getPattern()).isEqualTo(pattern); assertThat(cachedFormatter.getLocale()).isEqualTo(locale); assertThat(cachedFormatter.getTimeZone()).isEqualTo(timeZone); } static Object[][] getterTestCases() { // Choosing two different locale & time zone pairs to ensure having one that doesn't match the system default final Locale locale1 = Locale.forLanguageTag("nl_NL"); final Locale locale2 = Locale.forLanguageTag("tr_TR"); final String[] timeZoneIds = TimeZone.getAvailableIDs(); final int timeZone1IdIndex = new Random(0).nextInt(timeZoneIds.length); final int timeZone2IdIndex = (timeZone1IdIndex + 1) % timeZoneIds.length; final TimeZone timeZone1 = TimeZone.getTimeZone(timeZoneIds[timeZone1IdIndex]); final TimeZone timeZone2 = TimeZone.getTimeZone(timeZoneIds[timeZone2IdIndex]); // Create test cases return new Object[][] { // For `ofMilliPrecision()` { (Function<InstantPatternFormatter, InstantPatternThreadLocalCachedFormatter>) InstantPatternThreadLocalCachedFormatter::ofMilliPrecision, "HH:mm.SSS", locale1, timeZone1 }, { (Function<InstantPatternFormatter, InstantPatternThreadLocalCachedFormatter>) InstantPatternThreadLocalCachedFormatter::ofMilliPrecision, "HH:mm.SSS", locale2, timeZone2 }, // For `ofSecondPrecision()` { (Function<InstantPatternFormatter, InstantPatternThreadLocalCachedFormatter>) InstantPatternThreadLocalCachedFormatter::ofSecondPrecision, "yyyy", locale1, timeZone1 }, { (Function<InstantPatternFormatter, InstantPatternThreadLocalCachedFormatter>) InstantPatternThreadLocalCachedFormatter::ofSecondPrecision, "yyyy", locale2, timeZone2 } }; } @ParameterizedTest @ValueSource(strings = {"SSSS", "SSSSS", "SSSSSS", "SSSSSSS", "SSSSSSSS", "SSSSSSSSS", "n", "N"}) void ofMilliPrecision_should_fail_on_inconsistent_precision(final String subMilliPattern) { final InstantPatternDynamicFormatter dynamicFormatter = new InstantPatternDynamicFormatter(subMilliPattern, LOCALE, TIME_ZONE); assertThatThrownBy(() -> InstantPatternThreadLocalCachedFormatter.ofMilliPrecision(dynamicFormatter)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "instant formatter `%s` is of `%s` precision, whereas the requested cache precision is `%s`", dynamicFormatter, dynamicFormatter.getPrecision(), ChronoUnit.MILLIS); } @ParameterizedTest @ValueSource(strings = {"SSS", "s", "ss", "m", "mm", "H", "HH"}) void ofMilliPrecision_should_truncate_precision_to_milli(final String superMilliPattern) { final InstantPatternDynamicFormatter dynamicFormatter = new InstantPatternDynamicFormatter(superMilliPattern, LOCALE, TIME_ZONE); final InstantPatternThreadLocalCachedFormatter cachedFormatter = InstantPatternThreadLocalCachedFormatter.ofMilliPrecision(dynamicFormatter); assertThat(cachedFormatter.getPrecision()).isEqualTo(ChronoUnit.MILLIS); assertThat(cachedFormatter.getPrecision().compareTo(dynamicFormatter.getPrecision())) .isLessThanOrEqualTo(0); } @ParameterizedTest @ValueSource( strings = {"S", "SS", "SSS", "SSSS", "SSSSS", "SSSSSS", "SSSSSSS", "SSSSSSSS", "SSSSSSSSS", "n", "N", "A"}) void ofSecondPrecision_should_fail_on_inconsistent_precision(final String subSecondPattern) { final InstantPatternDynamicFormatter dynamicFormatter = new InstantPatternDynamicFormatter(subSecondPattern, LOCALE, TIME_ZONE); assertThatThrownBy(() -> InstantPatternThreadLocalCachedFormatter.ofSecondPrecision(dynamicFormatter)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "instant formatter `%s` is of `%s` precision, whereas the requested cache precision is `%s`", dynamicFormatter, dynamicFormatter.getPrecision(), ChronoUnit.SECONDS); } @ParameterizedTest @ValueSource(strings = {"s", "ss", "m", "mm", "H", "HH"}) void ofSecondPrecision_should_truncate_precision_to_second(final String superSecondPattern) { final InstantPatternDynamicFormatter dynamicFormatter = new InstantPatternDynamicFormatter(superSecondPattern, LOCALE, TIME_ZONE); final InstantPatternThreadLocalCachedFormatter cachedFormatter = InstantPatternThreadLocalCachedFormatter.ofSecondPrecision(dynamicFormatter); assertThat(cachedFormatter.getPrecision()).isEqualTo(ChronoUnit.SECONDS); assertThat(cachedFormatter.getPrecision().compareTo(dynamicFormatter.getPrecision())) .isLessThanOrEqualTo(0); } private static final MutableInstant INSTANT0 = createInstant(0, 0); @Test void ofMilliPrecision_should_cache() { // Mock a pattern formatter final InstantPatternFormatter patternFormatter = mock(InstantPatternFormatter.class); when(patternFormatter.getPrecision()).thenReturn(ChronoUnit.MILLIS); // Configure the pattern formatter for the 1st instant final Instant instant1 = INSTANT0; final String output1 = "instant1"; doAnswer(invocation -> { final StringBuilder buffer = invocation.getArgument(0); buffer.append(output1); return null; }) .when(patternFormatter) .formatTo(any(StringBuilder.class), eq(instant1)); // Create a 2nd distinct instant that shares the same milliseconds with the 1st instant. // That is, the 2nd instant should trigger a cache hit. final MutableInstant instant2 = offsetInstant(instant1, 0, 1); assertThat(instant1.getEpochMillisecond()).isEqualTo(instant2.getEpochMillisecond()); assertThat(instant1).isNotEqualTo(instant2); // Configure the pattern for a 3rd distinct instant. // The 3rd instant should be of different milliseconds with the 1st (and 2nd) instants to trigger a cache miss. final MutableInstant instant3 = offsetInstant(instant2, 1, 0); assertThat(instant2.getEpochMillisecond()).isNotEqualTo(instant3.getEpochMillisecond()); final String output3 = "instant3"; doAnswer(invocation -> { final StringBuilder buffer = invocation.getArgument(0); buffer.append(output3); return null; }) .when(patternFormatter) .formatTo(any(StringBuilder.class), eq(instant3)); // Create a 4th distinct instant that shares the same milliseconds with the 3rd instant. // That is, the 4th instant should trigger a cache hit. final MutableInstant instant4 = offsetInstant(instant3, 0, 1); assertThat(instant3.getEpochMillisecond()).isEqualTo(instant4.getEpochMillisecond()); assertThat(instant3).isNotEqualTo(instant4); // Create the cached formatter and verify its output final InstantFormatter cachedFormatter = InstantPatternThreadLocalCachedFormatter.ofMilliPrecision(patternFormatter); assertThat(cachedFormatter.format(instant1)).isEqualTo(output1); // Cache miss assertThat(cachedFormatter.format(instant2)).isEqualTo(output1); // Cache hit assertThat(cachedFormatter.format(instant2)).isEqualTo(output1); // Repeated cache hit assertThat(cachedFormatter.format(instant3)).isEqualTo(output3); // Cache miss assertThat(cachedFormatter.format(instant4)).isEqualTo(output3); // Cache hit assertThat(cachedFormatter.format(instant4)).isEqualTo(output3); // Repeated cache hit // Verify the pattern formatter interaction verify(patternFormatter).getPrecision(); verify(patternFormatter).formatTo(any(StringBuilder.class), eq(instant1)); verify(patternFormatter).formatTo(any(StringBuilder.class), eq(instant3)); verifyNoMoreInteractions(patternFormatter); } @Test void ofSecondPrecision_should_cache() { // Mock a pattern formatter final InstantPatternFormatter patternFormatter = mock(InstantPatternFormatter.class); when(patternFormatter.getPrecision()).thenReturn(ChronoUnit.SECONDS); // Configure the pattern formatter for the 1st instant final Instant instant1 = INSTANT0; final String output1 = "instant1"; doAnswer(invocation -> { final StringBuilder buffer = invocation.getArgument(0); buffer.append(output1); return null; }) .when(patternFormatter) .formatTo(any(StringBuilder.class), eq(instant1)); // Create a 2nd distinct instant that shares the same seconds with the 1st instant. // That is, the 2nd instant should trigger a cache hit. final MutableInstant instant2 = offsetInstant(instant1, 1, 0); assertThat(instant1.getEpochSecond()).isEqualTo(instant2.getEpochSecond()); assertThat(instant1).isNotEqualTo(instant2); // Configure the pattern for a 3rd distinct instant. // The 3rd instant should be of different seconds with the 1st (and 2nd) instants to trigger a cache miss. final MutableInstant instant3 = offsetInstant(instant2, 1_000, 0); assertThat(instant2.getEpochSecond()).isNotEqualTo(instant3.getEpochSecond()); final String output3 = "instant3"; doAnswer(invocation -> { final StringBuilder buffer = invocation.getArgument(0); buffer.append(output3); return null; }) .when(patternFormatter) .formatTo(any(StringBuilder.class), eq(instant3)); // Create a 4th distinct instant that shares the same seconds with the 3rd instant. // That is, the 4th instant should trigger a cache hit. final MutableInstant instant4 = offsetInstant(instant3, 1, 0); assertThat(instant3.getEpochSecond()).isEqualTo(instant4.getEpochSecond()); assertThat(instant3).isNotEqualTo(instant4); // Create the cached formatter and verify its output final InstantFormatter cachedFormatter = InstantPatternThreadLocalCachedFormatter.ofSecondPrecision(patternFormatter); assertThat(cachedFormatter.format(instant1)).isEqualTo(output1); // Cache miss assertThat(cachedFormatter.format(instant2)).isEqualTo(output1); // Cache hit assertThat(cachedFormatter.format(instant2)).isEqualTo(output1); // Repeated cache hit assertThat(cachedFormatter.format(instant3)).isEqualTo(output3); // Cache miss assertThat(cachedFormatter.format(instant4)).isEqualTo(output3); // Cache hit assertThat(cachedFormatter.format(instant4)).isEqualTo(output3); // Repeated cache hit // Verify the pattern formatter interaction verify(patternFormatter).getPrecision(); verify(patternFormatter).formatTo(any(StringBuilder.class), eq(instant1)); verify(patternFormatter).formatTo(any(StringBuilder.class), eq(instant3)); verifyNoMoreInteractions(patternFormatter); } private static MutableInstant offsetInstant( final Instant instant, final long epochMillisOffset, final int epochMillisNanosOffset) { final long epochMillis = Math.addExact(instant.getEpochMillisecond(), epochMillisOffset); final int epochMillisNanos = Math.addExact(instant.getNanoOfMillisecond(), epochMillisNanosOffset); return createInstant(epochMillis, epochMillisNanos); } private static MutableInstant createInstant(final long epochMillis, final int epochMillisNanos) { final MutableInstant instant = new MutableInstant(); instant.initFromEpochMilli(epochMillis, epochMillisNanos); return instant; } @Test @Issue("https://github.com/apache/logging-log4j2/issues/3792") void should_be_thread_safe() throws Exception { // Instead of randomly testing the thread safety, we test that the current implementation does not // cache results across threads. // // Modify this test if the implementation changes in the future. final InstantPatternFormatter patternFormatter = mock(InstantPatternFormatter.class); when(patternFormatter.getPrecision()).thenReturn(ChronoUnit.MILLIS); final Instant instant = INSTANT0; final String output = "thread-output"; doAnswer(invocation -> { StringBuilder buffer = invocation.getArgument(0); buffer.append(output) .append('-') .append(Thread.currentThread().getName()); return null; }) .when(patternFormatter) .formatTo(any(StringBuilder.class), eq(instant)); final InstantFormatter cachedFormatter = InstantPatternThreadLocalCachedFormatter.ofMilliPrecision(patternFormatter); final int threadCount = 2; for (int i = 0; i < threadCount; i++) { formatOnNewThread(cachedFormatter, instant, output); } verify(patternFormatter, times(threadCount)).formatTo(any(StringBuilder.class), eq(instant)); } private static void formatOnNewThread( final InstantFormatter formatter, final Instant instant, final String expectedOutput) throws ExecutionException, InterruptedException { ExecutorService executor = newSingleThreadExecutor(); try { executor.submit(() -> { String formatted = formatter.format(instant); assertThat(formatted) .isEqualTo(expectedOutput + "-" + Thread.currentThread().getName()); }) .get(); } finally { executor.shutdown(); } } }
InstantPatternThreadLocalCachedFormatterTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/component/StructComponentOneToManyMappedByTest.java
{ "start": 1604, "end": 3058 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope){ scope.inTransaction( session -> { Book book1 = new Book(); book1.id = 1L; book1.title = "Main book"; book1.author = new Author( "Abc" ); session.persist( book1 ); Book book2 = new Book(); book2.id = 2L; book2.title = "Second book"; book2.mainBook = book1; book2.author = new Author( "Abc" ); session.persist( book2 ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope){ scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testGet(SessionFactoryScope scope){ scope.inTransaction( session -> { Book book = session.createQuery( "from Book b where b.id = 1", Book.class ).getSingleResult(); assertFalse( Hibernate.isInitialized( book.author.getBooks() ) ); assertEquals( "Second book", book.author.getBooks().iterator().next().getTitle() ); } ); } @Test public void testJoin(SessionFactoryScope scope){ scope.inTransaction( session -> { Book book = session.createQuery( "from Book b join fetch b.author.books where b.id = 1", Book.class ).getSingleResult(); assertTrue( Hibernate.isInitialized( book.author.getBooks() ) ); assertEquals( "Second book", book.author.getBooks().iterator().next().getTitle() ); } ); } @Entity(name = "Book") public static
StructComponentOneToManyMappedByTest
java
junit-team__junit5
junit-vintage-engine/src/test/java/org/junit/vintage/engine/discovery/IsPotentialJUnit4TestClassTests.java
{ "start": 1028, "end": 1182 }
class ____ { } @Test void anonymousClass() { var foo = new Foo() { }; assertFalse(isPotentialJUnit4TestClass.test(foo.getClass())); } public
Baz
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/LanguageComponentBuilderFactory.java
{ "start": 5330, "end": 6362 }
class ____ extends AbstractComponentBuilder<LanguageComponent> implements LanguageComponentBuilder { @Override protected LanguageComponent buildConcreteComponent() { return new LanguageComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "allowTemplateFromHeader": ((LanguageComponent) component).setAllowTemplateFromHeader((boolean) value); return true; case "contentCache": ((LanguageComponent) component).setContentCache((boolean) value); return true; case "lazyStartProducer": ((LanguageComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((LanguageComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
LanguageComponentBuilderImpl
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/annotations/SchedulerSupport.java
{ "start": 1902, "end": 2083 }
class ____ on RxJava's {@linkplain Schedulers#io() I/O scheduler} or takes * timing information from it. */ String IO = "io.reactivex:io"; /** * The operator/
runs
java
elastic__elasticsearch
x-pack/plugin/enrich/src/test/java/org/elasticsearch/xpack/enrich/action/CoordinatorTests.java
{ "start": 2085, "end": 19401 }
class ____ extends ESTestCase { public void testCoordinateLookups() { MockLookupFunction lookupFunction = new MockLookupFunction(); Coordinator coordinator = new Coordinator(lookupFunction, 5, 1, 100); List<ActionListener<SearchResponse>> searchActionListeners = new ArrayList<>(); for (int i = 0; i < 9; i++) { SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(i))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.queue.add(new Coordinator.Slot(searchRequest, actionListener)); } SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(10))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.schedule(searchRequest, actionListener); // First batch of search requests have been sent off: // (However still 5 should remain in the queue) assertThat(coordinator.queue.size(), equalTo(5)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(1)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); assertThat(lookupFunction.capturedRequests.getFirst().requests().size(), equalTo(5)); // Nothing should happen now, because there is an outstanding request and max number of requests has been set to 1: coordinator.coordinateLookups(); assertThat(coordinator.queue.size(), equalTo(5)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(1)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); SearchResponse emptyResponse = emptySearchResponse(); // Replying a response and that should trigger another coordination round MultiSearchResponse.Item[] responseItems = new MultiSearchResponse.Item[5]; for (int i = 0; i < 5; i++) { emptyResponse.incRef(); responseItems[i] = new MultiSearchResponse.Item(emptyResponse, null); } emptyResponse.decRef(); final MultiSearchResponse res1 = new MultiSearchResponse(responseItems, 1L); try { lookupFunction.capturedConsumers.getFirst().accept(res1, null); assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(1)); assertThat(lookupFunction.capturedRequests.size(), equalTo(2)); // Replying last response, resulting in an empty queue and no outstanding requests. responseItems = new MultiSearchResponse.Item[5]; for (int i = 0; i < 5; i++) { emptyResponse.incRef(); responseItems[i] = new MultiSearchResponse.Item(emptyResponse, null); } var res2 = new MultiSearchResponse(responseItems, 1L); try { lookupFunction.capturedConsumers.get(1).accept(res2, null); assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(0)); assertThat(lookupFunction.capturedRequests.size(), equalTo(2)); // All individual action listeners for the search requests should have been invoked: for (ActionListener<SearchResponse> searchActionListener : searchActionListeners) { Mockito.verify(searchActionListener).onResponse(Mockito.eq(emptyResponse)); } } finally { res2.decRef(); } } finally { res1.decRef(); } } public void testCoordinateLookupsMultiSearchError() { MockLookupFunction lookupFunction = new MockLookupFunction(); Coordinator coordinator = new Coordinator(lookupFunction, 5, 1, 100); List<ActionListener<SearchResponse>> searchActionListeners = new ArrayList<>(); for (int i = 0; i < 4; i++) { SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(i))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.queue.add(new Coordinator.Slot(searchRequest, actionListener)); } SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(5))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.schedule(searchRequest, actionListener); // First batch of search requests have been sent off: // (However still 5 should remain in the queue) assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(1)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); assertThat(lookupFunction.capturedRequests.getFirst().requests().size(), equalTo(5)); RuntimeException e = new RuntimeException(); lookupFunction.capturedConsumers.getFirst().accept(null, e); assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(0)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); // All individual action listeners for the search requests should have been invoked: for (ActionListener<SearchResponse> searchActionListener : searchActionListeners) { Mockito.verify(searchActionListener).onFailure(Mockito.eq(e)); } } public void testCoordinateLookupsMultiSearchItemError() { MockLookupFunction lookupFunction = new MockLookupFunction(); Coordinator coordinator = new Coordinator(lookupFunction, 5, 1, 100); List<ActionListener<SearchResponse>> searchActionListeners = new ArrayList<>(); for (int i = 0; i < 4; i++) { SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(i))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.queue.add(new Coordinator.Slot(searchRequest, actionListener)); } SearchRequest searchRequest = new SearchRequest("my-index"); searchRequest.source().query(new MatchQueryBuilder("my_field", String.valueOf(5))); @SuppressWarnings("unchecked") ActionListener<SearchResponse> actionListener = Mockito.mock(ActionListener.class); searchActionListeners.add(actionListener); coordinator.schedule(searchRequest, actionListener); // First batch of search requests have been sent off: // (However still 5 should remain in the queue) assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(1)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); assertThat(lookupFunction.capturedRequests.getFirst().requests().size(), equalTo(5)); RuntimeException e = new RuntimeException(); // Replying a response and that should trigger another coordination round MultiSearchResponse.Item[] responseItems = new MultiSearchResponse.Item[5]; for (int i = 0; i < 5; i++) { responseItems[i] = new MultiSearchResponse.Item(null, e); } var res = new MultiSearchResponse(responseItems, 1L); try { lookupFunction.capturedConsumers.getFirst().accept(res, null); assertThat(coordinator.queue.size(), equalTo(0)); assertThat(coordinator.getRemoteRequestsCurrent(), equalTo(0)); assertThat(lookupFunction.capturedRequests.size(), equalTo(1)); // All individual action listeners for the search requests should have been invoked: for (ActionListener<SearchResponse> searchActionListener : searchActionListeners) { Mockito.verify(searchActionListener).onFailure(Mockito.eq(e)); } } finally { res.decRef(); } } public void testNoBlockingWhenQueueing() { MockLookupFunction lookupFunction = new MockLookupFunction(); // Only one request allowed in flight. Queue size maxed at 1. Coordinator coordinator = new Coordinator(lookupFunction, 1, 1, 1); // Pre-load the queue to be at capacity and spoof the coordinator state to seem like max requests in flight. coordinator.queue.add(new Coordinator.Slot(new SearchRequest(), ActionListener.noop())); assertTrue(coordinator.remoteRequestPermits.tryAcquire()); // Try to schedule an item into the coordinator, should emit an exception SearchRequest searchRequest = new SearchRequest(); final AtomicReference<Exception> capturedException = new AtomicReference<>(); coordinator.schedule(searchRequest, ActionListener.wrap(response -> {}, capturedException::set)); // Ensure rejection since queue is full Exception rejectionException = capturedException.get(); assertThat(rejectionException.getMessage(), containsString("Could not perform enrichment, enrich coordination queue at capacity")); // Ensure that nothing was scheduled because max requests is already in flight assertThat(lookupFunction.capturedConsumers, is(empty())); // Try to schedule again while max requests is not full. Ensure that despite the rejection, the queued request is sent. coordinator.remoteRequestPermits.release(); capturedException.set(null); coordinator.schedule(searchRequest, ActionListener.wrap(response -> {}, capturedException::set)); rejectionException = capturedException.get(); assertThat(rejectionException.getMessage(), containsString("Could not perform enrichment, enrich coordination queue at capacity")); assertThat(lookupFunction.capturedRequests.size(), is(1)); assertThat(lookupFunction.capturedConsumers.size(), is(1)); // Schedule once more now, the queue should be able to accept the item, but will not schedule it yet capturedException.set(null); coordinator.schedule(searchRequest, ActionListener.wrap(response -> {}, capturedException::set)); rejectionException = capturedException.get(); assertThat(rejectionException, is(nullValue())); assertThat(coordinator.queue.size(), is(1)); assertThat(coordinator.getRemoteRequestsCurrent(), is(1)); assertThat(lookupFunction.capturedRequests.size(), is(1)); assertThat(lookupFunction.capturedConsumers.size(), is(1)); // Fulfill the captured consumer which will schedule the next item in the queue. var res = new MultiSearchResponse(new MultiSearchResponse.Item[] { new MultiSearchResponse.Item(emptySearchResponse(), null) }, 1L); try { lookupFunction.capturedConsumers.getFirst().accept(res, null); // Ensure queue was drained and that the item in it was scheduled assertThat(coordinator.queue.size(), equalTo(0)); assertThat(lookupFunction.capturedRequests.size(), equalTo(2)); assertThat(lookupFunction.capturedRequests.get(1).requests().getFirst(), sameInstance(searchRequest)); } finally { res.decRef(); } } public void testLookupFunction() { MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); List<String> indices = List.of("index1", "index2", "index3"); for (String index : indices) { multiSearchRequest.add(new SearchRequest(index)); multiSearchRequest.add(new SearchRequest(index)); } List<EnrichShardMultiSearchAction.Request> requests = new ArrayList<>(); ElasticsearchClient client = new ElasticsearchClient() { @Override public <Request extends ActionRequest, Response extends ActionResponse> ActionFuture<Response> execute( ActionType<Response> action, Request request ) { throw new UnsupportedOperationException(); } @Override public <Request extends ActionRequest, Response extends ActionResponse> void execute( ActionType<Response> action, Request request, ActionListener<Response> listener ) { requests.add((EnrichShardMultiSearchAction.Request) request); } @Override public ThreadPool threadPool() { throw new UnsupportedOperationException(); } }; BiConsumer<MultiSearchRequest, BiConsumer<MultiSearchResponse, Exception>> consumer = Coordinator.lookupFunction(client); consumer.accept(multiSearchRequest, null); assertThat(requests.size(), equalTo(indices.size())); requests.sort(Comparator.comparing(SingleShardRequest::index)); for (int i = 0; i < indices.size(); i++) { String index = indices.get(i); assertThat(requests.get(i).index(), equalTo(index)); assertThat(requests.get(i).getMultiSearchRequest().requests().size(), equalTo(2)); assertThat(requests.get(i).getMultiSearchRequest().requests().getFirst().indices().length, equalTo(1)); assertThat(requests.get(i).getMultiSearchRequest().requests().getFirst().indices()[0], equalTo(index)); } } public void testReduce() { Map<String, List<Tuple<Integer, SearchRequest>>> itemsPerIndex = new HashMap<>(); Map<String, Tuple<MultiSearchResponse, Exception>> shardResponses = new HashMap<>(); try { var empty = emptySearchResponse(); // use empty response 3 times below and we start out with ref-count 1 empty.incRef(); empty.incRef(); MultiSearchResponse.Item item1 = new MultiSearchResponse.Item(empty, null); itemsPerIndex.put("index1", List.of(new Tuple<>(0, null), new Tuple<>(1, null), new Tuple<>(2, null))); shardResponses.put( "index1", new Tuple<>(new MultiSearchResponse(new MultiSearchResponse.Item[] { item1, item1, item1 }, 1), null) ); Exception failure = new RuntimeException(); itemsPerIndex.put("index2", List.of(new Tuple<>(3, null), new Tuple<>(4, null), new Tuple<>(5, null))); shardResponses.put("index2", new Tuple<>(null, failure)); // use empty response 3 times below empty.incRef(); empty.incRef(); empty.incRef(); MultiSearchResponse.Item item2 = new MultiSearchResponse.Item(empty, null); itemsPerIndex.put("index3", List.of(new Tuple<>(6, null), new Tuple<>(7, null), new Tuple<>(8, null))); shardResponses.put( "index3", new Tuple<>(new MultiSearchResponse(new MultiSearchResponse.Item[] { item2, item2, item2 }, 1), null) ); MultiSearchResponse result = Coordinator.reduce(9, itemsPerIndex, shardResponses); try { assertThat(result.getResponses().length, equalTo(9)); assertThat(result.getResponses()[0], sameInstance(item1)); assertThat(result.getResponses()[1], sameInstance(item1)); assertThat(result.getResponses()[2], sameInstance(item1)); assertThat(result.getResponses()[3].getFailure(), sameInstance(failure)); assertThat(result.getResponses()[4].getFailure(), sameInstance(failure)); assertThat(result.getResponses()[5].getFailure(), sameInstance(failure)); assertThat(result.getResponses()[6], sameInstance(item2)); assertThat(result.getResponses()[7], sameInstance(item2)); assertThat(result.getResponses()[8], sameInstance(item2)); } finally { result.decRef(); } } finally { for (Tuple<MultiSearchResponse, Exception> value : shardResponses.values()) { var res = value.v1(); if (res != null) { res.decRef(); } } } } private static SearchResponse emptySearchResponse() { return SearchResponseUtils.successfulResponse(SearchHits.empty(Lucene.TOTAL_HITS_EQUAL_TO_ZERO, Float.NaN)); } private
CoordinatorTests
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/test/java/org/apache/camel/component/aws2/ddb/Ddb2ClientFactoryTest.java
{ "start": 1336, "end": 2750 }
class ____ { @Test public void getStandardDdb2ClientDefault() { Ddb2Configuration ddb2Configuration = new Ddb2Configuration(); Ddb2InternalClient ddb2Client = Ddb2ClientFactory.getDynamoDBClient(ddb2Configuration); assertTrue(ddb2Client instanceof Ddb2ClientStandardImpl); } @Test public void getStandardDdb2Client() { Ddb2Configuration ddb2Configuration = new Ddb2Configuration(); ddb2Configuration.setUseDefaultCredentialsProvider(false); Ddb2InternalClient ddb2Client = Ddb2ClientFactory.getDynamoDBClient(ddb2Configuration); assertTrue(ddb2Client instanceof Ddb2ClientStandardImpl); } @Test public void getIAMOptimizedDdb2Client() { Ddb2Configuration ddb2Configuration = new Ddb2Configuration(); ddb2Configuration.setUseDefaultCredentialsProvider(true); Ddb2InternalClient ddb2Client = Ddb2ClientFactory.getDynamoDBClient(ddb2Configuration); assertTrue(ddb2Client instanceof Ddb2ClientIAMOptimizedImpl); } @Test public void getSessionTokenDdb2Client() { Ddb2Configuration ddb2Configuration = new Ddb2Configuration(); ddb2Configuration.setUseSessionCredentials(true); Ddb2InternalClient ddb2Client = Ddb2ClientFactory.getDynamoDBClient(ddb2Configuration); assertTrue(ddb2Client instanceof Ddb2ClientSessionTokenImpl); } }
Ddb2ClientFactoryTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/coordination/MasterHistoryTests.java
{ "start": 1587, "end": 22303 }
class ____ extends ESTestCase { private DiscoveryNode node1; private DiscoveryNode node2; private DiscoveryNode node3; private ClusterState nullMasterClusterState; private ClusterState node1MasterClusterState; private ClusterState node2MasterClusterState; private ClusterState node3MasterClusterState; private static final String TEST_SOURCE = "test"; @Before public void setup() throws Exception { node1 = DiscoveryNodeUtils.create("node1", randomNodeId()); node2 = DiscoveryNodeUtils.create("node2", randomNodeId()); node3 = DiscoveryNodeUtils.create("node3", randomNodeId()); nullMasterClusterState = createClusterState(null, node1, node2, node3); node1MasterClusterState = createClusterState(node1, node2, node3); node2MasterClusterState = createClusterState(node2, node1, node3); node3MasterClusterState = createClusterState(node3, node1, node2); } public void testGetBasicUse() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(System::currentTimeMillis); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); assertNull(masterHistory.getMostRecentMaster()); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertNull(masterHistory.getMostRecentMaster()); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertThat(masterHistory.getMostRecentMaster(), equalTo(node1MasterClusterState.nodes().getMasterNode())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, node1MasterClusterState)); assertThat(masterHistory.getMostRecentMaster(), equalTo(node2MasterClusterState.nodes().getMasterNode())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node3MasterClusterState, node2MasterClusterState)); assertThat(masterHistory.getMostRecentMaster(), equalTo(node3MasterClusterState.nodes().getMasterNode())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, node3MasterClusterState)); assertThat(masterHistory.getMostRecentMaster(), equalTo(node1MasterClusterState.nodes().getMasterNode())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertNull(masterHistory.getMostRecentMaster()); assertThat(masterHistory.getMostRecentNonNullMaster(), equalTo(node1MasterClusterState.nodes().getMasterNode())); } public void testHasMasterGoneNull() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); AtomicReference<ClusterState> clusterStateReference = new AtomicReference<>(nullMasterClusterState); when(clusterService.state()).thenAnswer((Answer<ClusterState>) invocation -> clusterStateReference.get()); AtomicLong currentTimeMillis = new AtomicLong(System.currentTimeMillis()); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(currentTimeMillis::get); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); currentTimeMillis.set(System.currentTimeMillis() - (60 * 60 * 1000)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node2MasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertTrue(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); // Now make sure that nodes that have left the cluster don't count against us: clusterStateReference.set(createClusterState(null, node2)); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); clusterStateReference.set(nullMasterClusterState); assertTrue(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); currentTimeMillis.set(System.currentTimeMillis()); assertFalse(masterHistory.hasMasterGoneNullAtLeastNTimes(3)); } public void testTime() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); AtomicLong currentTimeMillis = new AtomicLong(System.currentTimeMillis()); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(currentTimeMillis::get); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); currentTimeMillis.set(System.currentTimeMillis() - (60 * 60 * 1000)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, node1MasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node3MasterClusterState, node2MasterClusterState)); assertThat(masterHistory.getMostRecentMaster(), equalTo(node3MasterClusterState.nodes().getMasterNode())); currentTimeMillis.set(System.currentTimeMillis()); assertThat(masterHistory.getMostRecentMaster(), equalTo(node3MasterClusterState.nodes().getMasterNode())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node3MasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); } public void testHasSeenMasterInLastNSeconds() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); AtomicLong currentTimeMillis = new AtomicLong(System.currentTimeMillis()); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(currentTimeMillis::get); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); /* * 60 minutes ago we get these master changes: * null -> node1 -> node2 -> node3 * Except for when only null had been master, there has been a non-null master node in the last 5 seconds all along */ currentTimeMillis.set(System.currentTimeMillis() - new TimeValue(60, TimeUnit.MINUTES).getMillis()); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, node1MasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node3MasterClusterState, node2MasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); /* * 40 minutes ago we get these master changes (the master was node3 when this section began): * null -> node1 -> null -> null -> node1 * There has been a non-null master for the last 5 seconds every step at this time */ currentTimeMillis.set(System.currentTimeMillis() - new TimeValue(40, TimeUnit.MINUTES).getMillis()); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node3MasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); /* * 6 seconds ago we get these master changes (it had been set to node1 previously): * null -> null * Even though the last non-null master was more * than 5 seconds ago (and more than the age of history we keep, 30 minutes), the transition from it to null was just now, so we * still say that there has been a master recently. */ currentTimeMillis.set(System.currentTimeMillis() - new TimeValue(6, TimeUnit.SECONDS).getMillis()); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); /* * Right now we get these master changes (the master was null when this section began): * null -> node1 * Even before the first transition to null, we have no longer seen a non-null master within the last 5 seconds (because we last * transitioned from a non-null master 6 seconds ago). After the transition to node1, we again have seen a non-null master in the * last 5 seconds. */ currentTimeMillis.set(System.currentTimeMillis()); assertFalse(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, nullMasterClusterState)); assertFalse(masterHistory.hasSeenMasterInLastNSeconds(5)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertTrue(masterHistory.hasSeenMasterInLastNSeconds(5)); } public void testGetNumberOfMasterChanges() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); AtomicReference<ClusterState> clusterStateReference = new AtomicReference<>(nullMasterClusterState); when(clusterService.state()).thenAnswer((Answer<ClusterState>) invocation -> clusterStateReference.get()); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(() -> 0L); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); // The first master // doesn't count as a // change masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); // Nulls don't count masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); // Still no change in the // last non-null master masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); // Nulls don't count masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, node1MasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(1)); // Finally a new non-null // master masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node2MasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(1)); // Nulls don't count masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(2)); // Back to node1, but it's // a change from node2 // Make sure that nodes that are no longer in the cluster don't count towards master changes: clusterStateReference.set(createClusterState(node1)); assertThat(MasterHistory.getNumberOfMasterIdentityChanges(masterHistory.getNodes()), equalTo(0)); } public void testMaxSize() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); when(clusterService.state()).thenReturn(nullMasterClusterState); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(() -> 0L); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); for (int i = 0; i < MasterHistory.MAX_HISTORY_SIZE; i++) { masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, nullMasterClusterState, node1MasterClusterState)); } assertThat(masterHistory.getNodes().size(), lessThanOrEqualTo(MasterHistory.MAX_HISTORY_SIZE)); } public void testGetNodesAndGetRawNodes() { var clusterService = mock(ClusterService.class); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); AtomicReference<ClusterState> clusterStateReference = new AtomicReference<>(createClusterState((DiscoveryNode) null)); when(clusterService.state()).thenAnswer((Answer<ClusterState>) invocation -> clusterStateReference.get()); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.relativeTimeInMillisSupplier()).thenReturn(() -> 0L); MasterHistory masterHistory = new MasterHistory(threadPool, clusterService); assertThat(masterHistory.getRawNodes().size(), equalTo(0)); assertThat(masterHistory.getNodes().size(), equalTo(0)); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node1MasterClusterState, nullMasterClusterState)); assertThat(masterHistory.getRawNodes().size(), equalTo(1)); assertThat(masterHistory.getRawNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getNodes().size(), equalTo(0)); clusterStateReference.set(createClusterState(node1)); assertThat(masterHistory.getRawNodes().size(), equalTo(1)); assertThat(masterHistory.getRawNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getNodes().size(), equalTo(1)); assertThat(masterHistory.getNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); masterHistory.clusterChanged(new ClusterChangedEvent(TEST_SOURCE, node2MasterClusterState, nullMasterClusterState)); assertThat(masterHistory.getRawNodes().size(), equalTo(2)); assertThat(masterHistory.getRawNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getRawNodes().get(1).getEphemeralId(), equalTo(node2.getEphemeralId())); assertThat(masterHistory.getNodes().size(), equalTo(1)); assertThat(masterHistory.getNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); clusterStateReference.set(createClusterState(node2)); assertThat(masterHistory.getRawNodes().size(), equalTo(2)); assertThat(masterHistory.getRawNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getRawNodes().get(1).getEphemeralId(), equalTo(node2.getEphemeralId())); assertThat(masterHistory.getNodes().size(), equalTo(1)); assertThat(masterHistory.getNodes().get(0).getEphemeralId(), equalTo(node2.getEphemeralId())); clusterStateReference.set(createClusterState(node1, node2, node3)); assertThat(masterHistory.getRawNodes().size(), equalTo(2)); assertThat(masterHistory.getRawNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getRawNodes().get(1).getEphemeralId(), equalTo(node2.getEphemeralId())); assertThat(masterHistory.getNodes().size(), equalTo(2)); assertThat(masterHistory.getNodes().get(0).getEphemeralId(), equalTo(node1.getEphemeralId())); assertThat(masterHistory.getNodes().get(1).getEphemeralId(), equalTo(node2.getEphemeralId())); } private static String randomNodeId() { return UUID.randomUUID().toString(); } /* * If not null, the first node given will be the elected master. If the first entry is null, there will be no elected master. */ private static ClusterState createClusterState(DiscoveryNode... nodes) { var routingTableBuilder = RoutingTable.builder(); Metadata.Builder metadataBuilder = Metadata.builder(); DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(); for (int i = 0; i < nodes.length; i++) { DiscoveryNode node = nodes[i]; if (node != null) { if (i == 0) { nodesBuilder.masterNodeId(node.getId()); } nodesBuilder.add(node); } } return ClusterState.builder(new ClusterName("test-cluster")) .routingTable(routingTableBuilder.build()) .metadata(metadataBuilder.build()) .nodes(nodesBuilder) .build(); } }
MasterHistoryTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/util/DdlTransactionIsolatorTestingImpl.java
{ "start": 932, "end": 2863 }
class ____ extends DdlTransactionIsolatorNonJtaImpl { public DdlTransactionIsolatorTestingImpl(ServiceRegistry serviceRegistry, Connection jdbConnection) { this( serviceRegistry, createJdbcConnectionAccess( jdbConnection ) ); } public static JdbcConnectionAccess createJdbcConnectionAccess(Connection jdbcConnection) { return new JdbcConnectionAccessProvidedConnectionImpl( jdbcConnection ); } public DdlTransactionIsolatorTestingImpl(ServiceRegistry serviceRegistry, JdbcConnectionAccess jdbcConnectionAccess) { super( createJdbcContext( jdbcConnectionAccess, serviceRegistry ) ); } public DdlTransactionIsolatorTestingImpl(JdbcContext jdbcContext) { super( jdbcContext ); } public static JdbcContext createJdbcContext( JdbcConnectionAccess jdbcConnectionAccess, ServiceRegistry serviceRegistry) { return new JdbcContext() { final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class ); @Override public JdbcConnectionAccess getJdbcConnectionAccess() { return jdbcConnectionAccess; } @Override public Dialect getDialect() { return jdbcServices.getJdbcEnvironment().getDialect(); } @Override public SqlStatementLogger getSqlStatementLogger() { return jdbcServices.getSqlStatementLogger(); } @Override public SqlExceptionHelper getSqlExceptionHelper() { return jdbcServices.getSqlExceptionHelper(); } @Override public ServiceRegistry getServiceRegistry() { return serviceRegistry; } }; } public DdlTransactionIsolatorTestingImpl(ServiceRegistry serviceRegistry, ConnectionProvider connectionProvider) { this( serviceRegistry, createJdbcConnectionAccess( connectionProvider ) ); } private static JdbcConnectionAccess createJdbcConnectionAccess(ConnectionProvider connectionProvider) { return new JdbcConnectionAccessConnectionProviderImpl( connectionProvider ); } }
DdlTransactionIsolatorTestingImpl
java
elastic__elasticsearch
libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/CaseSensitiveComparison.java
{ "start": 524, "end": 969 }
class ____ extends FileAccessTreeComparison { CaseSensitiveComparison(char separatorChar) { super(Character::compare, separatorChar); } @Override protected boolean pathStartsWith(String pathString, String pathPrefix) { return pathString.startsWith(pathPrefix); } @Override protected boolean pathsAreEqual(String path1, String path2) { return path1.equals(path2); } }
CaseSensitiveComparison
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNNStorageRetentionManager.java
{ "start": 14923, "end": 15255 }
class ____ { private final Map<File, FakeRoot> dirRoots = Maps.newLinkedHashMap(); private final Set<File> expectedPurgedLogs = new LinkedHashSet<>(); private final Set<File> expectedPurgedImages = new LinkedHashSet<>(); private final Set<File> expectedStaleLogs = new LinkedHashSet<>(); private
TestCaseDescription
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TruthContainsExactlyElementsInUsageTest.java
{ "start": 3969, "end": 4473 }
class ____ { void test() { assertThat(ImmutableList.of(1, 2, 3)).containsExactlyElementsIn(Sets.newHashSet(1, 2, 3)); } } """) .doTest(); } @Test public void negativeTruthContainsExactlyElementsInUsageWithImmutableSet() { compilationHelper .addSourceLines( "ExampleClassTest.java", """ import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; public
ExampleClassTest
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/TopHitsAgg.java
{ "start": 1073, "end": 4163 }
class ____ extends LeafAgg { private final AggSource sortSource; private final SortOrder sortOrder; private final DataType fieldDataType; private final DataType sortFieldDataType; public TopHitsAgg( String id, AggSource source, DataType fieldDataType, AggSource sortSource, DataType sortFieldDataType, SortOrder sortOrder ) { super(id, source); this.fieldDataType = fieldDataType; this.sortSource = sortSource; this.sortOrder = sortOrder; this.sortFieldDataType = sortFieldDataType; } @Override AggregationBuilder toBuilder() { // Sort missing values (NULLs) as last to get the first/last non-null value List<SortBuilder<?>> sortBuilderList = new ArrayList<>(2); if (sortSource != null) { if (sortSource.fieldName() != null) { sortBuilderList.add( new FieldSortBuilder(sortSource.fieldName()).order(sortOrder) .missing(LAST.searchOrder()) .unmappedType(sortFieldDataType.esType()) ); } else if (sortSource.script() != null) { sortBuilderList.add( new ScriptSortBuilder( Scripts.nullSafeSort(sortSource.script()).toPainless(), source().script().outputType().scriptSortType() ).order(sortOrder) ); } } if (source().fieldName() != null) { sortBuilderList.add( new FieldSortBuilder(source().fieldName()).order(sortOrder).missing(LAST.searchOrder()).unmappedType(fieldDataType.esType()) ); } else { sortBuilderList.add( new ScriptSortBuilder(Scripts.nullSafeSort(source().script()).toPainless(), source().script().outputType().scriptSortType()) .order(sortOrder) ); } TopHitsAggregationBuilder builder = topHits(id()); if (source().fieldName() != null) { builder.docValueField(source().fieldName(), SqlDataTypes.format(fieldDataType)); } else { builder.scriptField(id(), source().script().toPainless()); } return builder.sorts(sortBuilderList).size(1); } @Override public int hashCode() { return Objects.hash(super.hashCode(), sortSource, sortOrder, fieldDataType, sortFieldDataType); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (super.equals(o) == false) { return false; } TopHitsAgg that = (TopHitsAgg) o; return Objects.equals(sortSource, that.sortSource) && sortOrder == that.sortOrder && Objects.equals(fieldDataType, that.fieldDataType) && Objects.equals(sortFieldDataType, that.sortFieldDataType); } }
TopHitsAgg
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java
{ "start": 1235, "end": 1825 }
class ____ implements FactoryBean<JtaTransactionManager>, InitializingBean { private final JtaTransactionManager transactionManager = new JtaTransactionManager(); @Override public void afterPropertiesSet() throws TransactionSystemException { this.transactionManager.afterPropertiesSet(); } @Override public @Nullable JtaTransactionManager getObject() { return this.transactionManager; } @Override public Class<?> getObjectType() { return this.transactionManager.getClass(); } @Override public boolean isSingleton() { return true; } }
JtaTransactionManagerFactoryBean
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/access/annotation/Secured.java
{ "start": 1691, "end": 1891 }
interface ____ { /** * Returns the list of security configuration attributes (e.g.&nbsp;ROLE_USER, * ROLE_ADMIN). * @return String[] The secure method attributes */ String[] value(); }
Secured
java
apache__camel
components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/CxfPayloadProducerNamespaceOnEnvelopeTest.java
{ "start": 2671, "end": 4519 }
class ____ { CXFTestSupport.getPort1(); // Works without streaming... // System.setProperty("org.apache.camel.component.cxf.streaming", "false"); } @Override public void doPostTearDown() { IOHelper.close(applicationContext); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:router") // // call an external Web service in payload mode .to("cxf:bean:serviceEndpoint?dataFormat=PAYLOAD") // Convert the CxfPayload to a String to trigger the // issue .convertBodyTo(String.class) // Parse to DOM to make sure it's still valid XML .convertBodyTo(Document.class) // Convert back to String to make testing the result // easier .convertBodyTo(String.class); // This route just returns the test message from("cxf:bean:serviceEndpoint?dataFormat=RAW").setBody().constant(RESPONSE_MESSAGE); } }; } @Test public void testInvokeRouter() { Object returnValue = template.requestBody("direct:router", REQUEST_PAYLOAD); assertNotNull(returnValue); assertTrue(returnValue instanceof String); assertTrue(((String) returnValue).contains("Return Value")); assertTrue(((String) returnValue).contains("http://www.w3.org/2001/XMLSchema-instance")); } @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/GetTokenBeans.xml"); } }
static
java
apache__camel
components/camel-cassandraql/src/main/java/org/apache/camel/processor/aggregate/cassandra/CassandraAggregationException.java
{ "start": 1013, "end": 1301 }
class ____ extends CamelExecutionException { private static final long serialVersionUID = 3847101273513627461L; public CassandraAggregationException(String message, Exchange exchange, Throwable cause) { super(message, exchange, cause); } }
CassandraAggregationException
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/env/ConstantPropertySources.java
{ "start": 1063, "end": 1322 }
class ____ { private final List<PropertySource> sources; public ConstantPropertySources(List<PropertySource> sources) { this.sources = sources; } List<PropertySource> getSources() { return sources; } }
ConstantPropertySources
java
apache__camel
components/camel-ignite/src/test/java/org/apache/camel/component/ignite/IgniteSetTest.java
{ "start": 1466, "end": 8275 }
class ____ extends AbstractIgniteTest { @Override protected String getScheme() { return "ignite-set"; } @Override protected AbstractIgniteComponent createComponent() { return IgniteSetComponent.fromConfiguration(createConfiguration()); } @Test public void testOperations() { boolean result = template.requestBody("ignite-set:" + resourceUid + "?operation=ADD", "hello", boolean.class); Assertions.assertThat(result).isTrue(); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).contains("hello")).isTrue(); result = template.requestBody("ignite-set:" + resourceUid + "?operation=CONTAINS", "hello", boolean.class); Assertions.assertThat(result).isTrue(); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).contains("hello")).isTrue(); result = template.requestBody("ignite-set:" + resourceUid + "?operation=REMOVE", "hello", boolean.class); Assertions.assertThat(result).isTrue(); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).contains("hello")).isFalse(); result = template.requestBody("ignite-set:" + resourceUid + "?operation=CONTAINS", "hello", boolean.class); Assertions.assertThat(result).isFalse(); } @Test @SuppressWarnings("unchecked") public void testOperations2() { for (int i = 0; i < 100; i++) { template.requestBody("ignite-set:" + resourceUid + "?operation=ADD", "hello" + i); } // SIZE int size = template.requestBody("ignite-set:" + resourceUid + "?operation=SIZE", "hello", int.class); Assertions.assertThat(size).isEqualTo(100); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(100); List<String> toRetain = Lists.newArrayList(); for (int i = 0; i < 50; i++) { toRetain.add("hello" + i); } // RETAIN_ALL boolean retained = template.requestBodyAndHeader("ignite-set:" + resourceUid + "?operation=CLEAR", toRetain, IgniteConstants.IGNITE_SETS_OPERATION, IgniteSetOperation.RETAIN_ALL, boolean.class); Assertions.assertThat(retained).isTrue(); // SIZE size = template.requestBody("ignite-set:" + resourceUid + "?operation=SIZE", "hello", int.class); Assertions.assertThat(size).isEqualTo(50); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(50); // ITERATOR Iterator<String> iterator = template.requestBody("ignite-set:" + resourceUid + "?operation=ITERATOR", "hello", Iterator.class); Assertions.assertThat(Iterators.toArray(iterator, String.class)).containsAll(toRetain); // ARRAY String[] array = template.requestBody("ignite-set:" + resourceUid + "?operation=ARRAY", "hello", String[].class); Assertions.assertThat(array).containsAll(toRetain); // CLEAR Object result = template.requestBody("ignite-set:" + resourceUid + "?operation=CLEAR", "hello", String.class); Assertions.assertThat(result).isEqualTo("hello"); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(0); // SIZE size = template.requestBody("ignite-set:" + resourceUid + "?operation=SIZE", "hello", int.class); Assertions.assertThat(size).isEqualTo(0); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(0); } @Test public void testRetainSingle() { // Fill data. for (int i = 0; i < 100; i++) { template.requestBody("ignite-set:" + resourceUid + "?operation=ADD", "hello" + i); } boolean retained = template.requestBody("ignite-set:" + resourceUid + "?operation=RETAIN_ALL", "hello10", boolean.class); Assertions.assertThat(retained).isTrue(); // ARRAY String[] array = template.requestBody("ignite-set:" + resourceUid + "?operation=ARRAY", "hello", String[].class); Assertions.assertThat(array).containsExactly("hello10"); } @Test public void testCollectionsAsCacheObject() { // Fill data. for (int i = 0; i < 100; i++) { template.requestBody("ignite-set:" + resourceUid + "?operation=ADD", "hello" + i); } // Add the set. Set<String> toAdd = Sets.newHashSet("hello101", "hello102", "hello103"); template.requestBody("ignite-set:" + resourceUid + "?operation=ADD&treatCollectionsAsCacheObjects=true", toAdd); // Size must be 101, not 103. int size = template.requestBody("ignite-set:" + resourceUid + "?operation=SIZE", "hello", int.class); Assertions.assertThat(size).isEqualTo(101); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(101); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).contains(toAdd)).isTrue(); // Check whether the Set contains the Set. boolean contains = template.requestBody( "ignite-set:" + resourceUid + "?operation=CONTAINS&treatCollectionsAsCacheObjects=true", toAdd, boolean.class); Assertions.assertThat(contains).isTrue(); // Delete the Set. template.requestBody("ignite-set:" + resourceUid + "?operation=REMOVE&treatCollectionsAsCacheObjects=true", toAdd); // Size must be 100 again. size = template.requestBody("ignite-set:" + resourceUid + "?operation=SIZE", "hello", int.class); Assertions.assertThat(size).isEqualTo(100); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).size()).isEqualTo(100); Assertions.assertThat(ignite().set(resourceUid, new CollectionConfiguration()).contains(toAdd)).isFalse(); } @Test public void testWithConfiguration() { CollectionConfiguration configuration = new CollectionConfiguration(); configuration.setCacheMode(CacheMode.PARTITIONED); context.getRegistry().bind("config", configuration); IgniteSetEndpoint igniteEndpoint = context.getEndpoint( "ignite-" + "set:" + resourceUid + "?operation=ADD&configuration=#config", IgniteSetEndpoint.class); template.requestBody(igniteEndpoint, "hello"); Assertions.assertThat(ignite().set(resourceUid, configuration).size()).isEqualTo(1); Assertions.assertThat(igniteEndpoint.getConfiguration()).isEqualTo(configuration); } @AfterEach public void deleteSet() { ignite().set(resourceUid, null).close(); } }
IgniteSetTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithCompositeTypeAssociation.java
{ "start": 1294, "end": 2483 }
class ____ { @Test public void testOrderedInsertSupport(EntityManagerFactoryScope scope) { // Without the fix, this transaction would eventually fail with a foreign-key constraint violation. // // The bookNoComment entity would be persisted just fine; however the bookWithComment would fail // because it would lead to inserting the Book entities first rather than making sure that the // Comment would be inserted first. // // The associated ActionQueue fix makes sure that regardless of the order of operations, the Comment // entity associated in the embeddable takes insert priority over the parent Book entity. scope.inTransaction( entityManager -> { Book bookNoComment = new Book(); bookNoComment.setId( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); Book bookWithComment = new Book(); bookWithComment.setId( SafeRandomUUIDGenerator.safeRandomUUIDAsString() ); bookWithComment.setIntermediateObject( new IntermediateObject( new Comment( "This is a comment" ) ) ); entityManager.persist( bookNoComment ); entityManager.persist( bookWithComment ); } ); } @Entity(name = "Book") public static
InsertOrderingWithCompositeTypeAssociation
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java
{ "start": 22566, "end": 23038 }
class ____ extends TopHitsAggTranslator<Last> { @Override protected LeafAgg toAgg(String id, Last l) { return new TopHitsAgg( id, asFieldOrLiteralOrScript(l, l.field()), l.dataType(), asFieldOrLiteralOrScript(l, l.orderField()), l.orderField() == null ? null : l.orderField().dataType(), SortOrder.DESC ); } } static
Lasts
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/NumberDeserializerTest.java
{ "start": 146, "end": 1408 }
class ____ extends TestCase { public void test_byte() throws Exception { Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("\"123\"", byte.class)); Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("\"123\"", Byte.class)); } public void test_byte1() throws Exception { Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("123.", byte.class)); Assert.assertEquals(Byte.valueOf((byte) 123), JSON.parseObject("123.", Byte.class)); } public void test_short() throws Exception { Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("\"123\"", short.class)); Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("\"123\"", Short.class)); } public void test_short1() throws Exception { Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("123.", short.class)); Assert.assertEquals(Short.valueOf((short) 123), JSON.parseObject("123.", Short.class)); } public void test_double() throws Exception { Assert.assertTrue(123.0D == JSON.parseObject("123.", double.class)); Assert.assertTrue(123.0D == JSON.parseObject("123.", Double.class).doubleValue()); } }
NumberDeserializerTest
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/DirectorySnapshotTests.java
{ "start": 1204, "end": 5769 }
class ____ { @TempDir @SuppressWarnings("NullAway.Init") File tempDir; private File directory; private DirectorySnapshot initialSnapshot; @BeforeEach void setup() throws Exception { this.directory = createTestDirectoryStructure(); this.initialSnapshot = new DirectorySnapshot(this.directory); } @Test @SuppressWarnings("NullAway") // Test null check void directoryMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(null)) .withMessageContaining("'directory' must not be null"); } @Test void directoryMustNotBeFile() throws Exception { File file = new File(this.tempDir, "file"); file.createNewFile(); assertThatIllegalArgumentException().isThrownBy(() -> new DirectorySnapshot(file)) .withMessageContaining("'directory' [" + file + "] must not be a file"); } @Test void directoryDoesNotHaveToExist() { File file = new File(this.tempDir, "does/not/exist"); DirectorySnapshot snapshot = new DirectorySnapshot(file); assertThat(snapshot).isEqualTo(new DirectorySnapshot(file)); } @Test void equalsWhenNothingHasChanged() { DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); assertThat(this.initialSnapshot).isEqualTo(updatedSnapshot); assertThat(this.initialSnapshot).hasSameHashCodeAs(updatedSnapshot); } @Test void notEqualsWhenAFileIsAdded() throws Exception { new File(new File(this.directory, "directory1"), "newfile").createNewFile(); DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test void notEqualsWhenAFileIsDeleted() { new File(new File(this.directory, "directory1"), "file1").delete(); DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test void notEqualsWhenAFileIsModified() throws Exception { File file1 = new File(new File(this.directory, "directory1"), "file1"); FileCopyUtils.copy("updatedcontent".getBytes(), file1); DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); assertThat(this.initialSnapshot).isNotEqualTo(updatedSnapshot); } @Test @SuppressWarnings("NullAway") // Test null check void getChangedFilesSnapshotMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) .withMessageContaining("'snapshot' must not be null"); } @Test void getChangedFilesSnapshotMustBeTheSameSourceDirectory() { assertThatIllegalArgumentException().isThrownBy( () -> this.initialSnapshot.getChangedFiles(new DirectorySnapshot(createTestDirectoryStructure()), null)) .withMessageContaining("'snapshot' source directory must be '" + this.directory + "'"); } @Test void getChangedFilesWhenNothingHasChanged() { DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); this.initialSnapshot.getChangedFiles(updatedSnapshot, null); } @Test void getChangedFilesWhenAFileIsAddedAndDeletedAndChanged() throws Exception { File directory1 = new File(this.directory, "directory1"); File file1 = new File(directory1, "file1"); File file2 = new File(directory1, "file2"); File newFile = new File(directory1, "newfile"); FileCopyUtils.copy("updatedcontent".getBytes(), file1); file2.delete(); newFile.createNewFile(); DirectorySnapshot updatedSnapshot = new DirectorySnapshot(this.directory); ChangedFiles changedFiles = this.initialSnapshot.getChangedFiles(updatedSnapshot, null); assertThat(changedFiles.getSourceDirectory()).isEqualTo(this.directory); assertThat(getChangedFile(changedFiles, file1).getType()).isEqualTo(Type.MODIFY); assertThat(getChangedFile(changedFiles, file2).getType()).isEqualTo(Type.DELETE); assertThat(getChangedFile(changedFiles, newFile).getType()).isEqualTo(Type.ADD); } private ChangedFile getChangedFile(ChangedFiles changedFiles, File file) { for (ChangedFile changedFile : changedFiles) { if (changedFile.getFile().equals(file)) { return changedFile; } } throw new AssertionError("File '%s' not found".formatted(file)); } private File createTestDirectoryStructure() throws IOException { File root = new File(this.tempDir, UUID.randomUUID().toString()); File directory1 = new File(root, "directory1"); directory1.mkdirs(); FileCopyUtils.copy("abc".getBytes(), new File(directory1, "file1")); FileCopyUtils.copy("abc".getBytes(), new File(directory1, "file2")); return root; } }
DirectorySnapshotTests
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/annotation/TypeHint.java
{ "start": 1173, "end": 1570 }
interface ____ { /** * @return The types to provide a hint */ Class<?>[] value() default {}; /** * Describes the access. * @return The access type */ AccessType[] accessType() default AccessType.ALL_DECLARED_CONSTRUCTORS; /** * @return The type names */ String[] typeNames() default {}; /** * The access type. */
TypeHint
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2318/Issue2318Test.java
{ "start": 551, "end": 1232 }
class ____ { @ProcessorTest @WithClasses( Issue2318Mapper.class ) public void shouldMap() { SourceChild source = new SourceChild(); source.setValue( "From child" ); source.setHolder( new Issue2318Mapper.SourceParent.Holder() ); source.getHolder().setParentValue1( "From parent" ); source.getHolder().setParentValue2( 12 ); TargetChild target = Issue2318Mapper.INSTANCE.mapChild( source ); assertThat( target.getParentValue1() ).isEqualTo( "From parent" ); assertThat( target.getParentValue2() ).isEqualTo( 12 ); assertThat( target.getChildValue() ).isEqualTo( "From child" ); } }
Issue2318Test
java
apache__camel
test-infra/camel-test-infra-openai-mock/src/test/java/org/apache/camel/test/infra/openai/mock/OpenAIMockTest.java
{ "start": 1333, "end": 10021 }
class ____ { @RegisterExtension public OpenAIMock openAIMock = new OpenAIMock().builder() .when("any sentence") .invokeTool("toolName") .withParam("param1", "value1") .end() .when("another sentence") .replyWith("hello World") .end() .when("multiple tools") .invokeTool("tool1") .withParam("p1", "v1") .andInvokeTool("tool2") .withParam("p2", "v2") .withParam("p3", "v3") .end() .when("custom response") .thenRespondWith( (request, input) -> "Custom response for: " + input) .end() .when("assert request") .assertRequest(request -> { Assertions.assertEquals("test", request); }) .replyWith("Request asserted successfully") .build(); @Test public void testToolResponse() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers .ofString("{\"messages\": [{\"role\": \"user\", \"content\": \"any sentence\"}]}")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); String responseBody = response.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson = objectMapper.readTree(responseBody); JsonNode choice = responseJson.path("choices").get(0); JsonNode message = choice.path("message"); assertEquals("assistant", message.path("role").asText()); assertEquals(true, message.path("content").isNull()); assertEquals(true, message.path("refusal").isNull()); JsonNode toolCalls = message.path("tool_calls"); assertEquals(1, toolCalls.size()); JsonNode toolCall = toolCalls.get(0); assertEquals("function", toolCall.path("type").asText()); assertEquals("toolName", toolCall.path("function").path("name").asText()); assertEquals("{\"param1\":\"value1\"}", toolCall.path("function").path("arguments").asText()); } @Test public void testChatResponse() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers .ofString("{\"messages\": [{\"role\": \"user\", \"content\": \"another sentence\"}]}")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); String responseBody = response.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson = objectMapper.readTree(responseBody); JsonNode choice = responseJson.path("choices").get(0); JsonNode message = choice.path("message"); assertEquals("assistant", message.path("role").asText()); assertEquals("hello World", message.path("content").asText()); assertEquals(true, message.path("refusal").isNull()); assertEquals(true, message.path("tool_calls").isMissingNode()); } @Test public void testMultipleToolCallsResponse() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers .ofString("{\"messages\": [{\"role\": \"user\", \"content\": \"multiple tools\"}]}")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); String responseBody = response.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson = objectMapper.readTree(responseBody); JsonNode choice = responseJson.path("choices").get(0); JsonNode message = choice.path("message"); assertEquals("assistant", message.path("role").asText()); assertEquals(true, message.path("content").isNull()); assertEquals(true, message.path("refusal").isNull()); JsonNode toolCalls = message.path("tool_calls"); assertEquals(2, toolCalls.size()); JsonNode toolCall1 = toolCalls.get(0); assertEquals("function", toolCall1.path("type").asText()); assertEquals("tool1", toolCall1.path("function").path("name").asText()); assertEquals("{\"p1\":\"v1\"}", toolCall1.path("function").path("arguments").asText()); JsonNode toolCall2 = toolCalls.get(1); assertEquals("function", toolCall2.path("type").asText()); assertEquals("tool2", toolCall2.path("function").path("name").asText()); assertEquals("{\"p2\":\"v2\",\"p3\":\"v3\"}", toolCall2.path("function").path("arguments").asText()); } @Test public void testCustomResponse() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers .ofString("{\"messages\": [{\"role\": \"user\", \"content\": \"custom response\"}]}")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); String responseBody = response.body(); assertEquals("Custom response for: custom response", responseBody); } @Test public void testToolResponseAndStop() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request1 = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers .ofString("{\"messages\": [{\"role\": \"user\", \"content\": \"any sentence\"}]}")) .build(); HttpResponse<String> response1 = client.send(request1, HttpResponse.BodyHandlers.ofString()); String responseBody1 = response1.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson1 = objectMapper.readTree(responseBody1); JsonNode choice1 = responseJson1.path("choices").get(0); JsonNode message1 = choice1.path("message"); assertEquals("assistant", message1.path("role").asText()); assertEquals(true, message1.path("content").isNull()); assertEquals(true, message1.path("refusal").isNull()); JsonNode toolCalls = message1.path("tool_calls"); assertEquals(1, toolCalls.size()); JsonNode toolCall = toolCalls.get(0); String toolCallId = toolCall.path("id").asText(); assertEquals("function", toolCall.path("type").asText()); assertEquals("toolName", toolCall.path("function").path("name").asText()); assertEquals("{\"param1\":\"value1\"}", toolCall.path("function").path("arguments").asText()); // Second request with tool result String secondRequestBody = String.format( "{\"messages\": [{\"role\": \"user\", \"content\": \"any sentence\"}, {\"role\":\"tool\", \"tool_call_id\":\"%s\", \"content\":\"{\\\"name\\\": \\\"pippo\\\"}\"}]}", toolCallId); HttpRequest request2 = HttpRequest.newBuilder() .uri(URI.create(openAIMock.getBaseUrl() + "/v1/chat/completions")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(secondRequestBody)) .build(); HttpResponse<String> response2 = client.send(request2, HttpResponse.BodyHandlers.ofString()); String responseBody2 = response2.body(); JsonNode responseJson2 = objectMapper.readTree(responseBody2); JsonNode choice2 = responseJson2.path("choices").get(0); assertEquals("stop", choice2.path("finish_reason").asText()); } }
OpenAIMockTest
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/EpochEntry.java
{ "start": 885, "end": 2744 }
class ____ extends RemotingSerializable { public static final long LAST_EPOCH_END_OFFSET = Long.MAX_VALUE; private int epoch; private long startOffset; private long endOffset = LAST_EPOCH_END_OFFSET; public EpochEntry(EpochEntry entry) { this.epoch = entry.getEpoch(); this.startOffset = entry.getStartOffset(); this.endOffset = entry.getEndOffset(); } public EpochEntry(int epoch, long startOffset) { this.epoch = epoch; this.startOffset = startOffset; } public EpochEntry(int epoch, long startOffset, long endOffset) { this.epoch = epoch; this.startOffset = startOffset; this.endOffset = endOffset; } public int getEpoch() { return epoch; } public void setEpoch(int epoch) { this.epoch = epoch; } public long getStartOffset() { return startOffset; } public void setStartOffset(long startOffset) { this.startOffset = startOffset; } public long getEndOffset() { return endOffset; } public void setEndOffset(long endOffset) { this.endOffset = endOffset; } @Override public String toString() { return "EpochEntry{" + "epoch=" + epoch + ", startOffset=" + startOffset + ", endOffset=" + endOffset + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EpochEntry entry = (EpochEntry) o; return epoch == entry.epoch && startOffset == entry.startOffset && endOffset == entry.endOffset; } @Override public int hashCode() { return Objects.hash(epoch, startOffset, endOffset); } }
EpochEntry
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/allocation/SearchableSnapshotDiskThresholdIntegTests.java
{ "start": 19843, "end": 21263 }
class ____ extends MockRepository { private static final CountDownLatch RESTORE_SHARD_LATCH = new CountDownLatch(1); public CustomMockRepository( ProjectId projectId, RepositoryMetadata metadata, Environment environment, NamedXContentRegistry namedXContentRegistry, ClusterService clusterService, BigArrays bigArrays, RecoverySettings recoverySettings, SnapshotMetrics snapshotMetrics ) { super(projectId, metadata, environment, namedXContentRegistry, clusterService, bigArrays, recoverySettings, snapshotMetrics); } private void unlockRestore() { RESTORE_SHARD_LATCH.countDown(); } @Override public void restoreShard( Store store, SnapshotId snapshotId, IndexId indexId, ShardId snapshotShardId, RecoveryState recoveryState, ActionListener<Void> listener ) { try { assertTrue(RESTORE_SHARD_LATCH.await(30, TimeUnit.SECONDS)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } super.restoreShard(store, snapshotId, indexId, snapshotShardId, recoveryState, listener); } } }
CustomMockRepository
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/DefaultClasspathScannerTests.java
{ "start": 25299, "end": 25487 }
class ____ extends ClassLoader { @Override public Enumeration<URL> getResources(String name) throws IOException { throw new IOException("Demo I/O error"); } } }
ThrowingClassLoader
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/collection/EnumMapType.java
{ "start": 360, "end": 730 }
class ____ { @Id @GeneratedValue private Integer id; private String type; EnumMapType() { } public EnumMapType(String type) { this.type = type; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
EnumMapType
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectParserTest.java
{ "start": 925, "end": 2033 }
class ____ extends TestCase { public void test_select() throws Exception { String sql = "SELECT last_name, department_id FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE last_name = 'Lorentz') ORDER BY last_name, department_id;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); output(statementList); } public void test_hinits() throws Exception { String sql = "SELECT /*+FIRST_ROWS*/ * FROM T"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); output(statementList); } private void output(List<SQLStatement> stmtList) { StringBuilder out = new StringBuilder(); OracleOutputVisitor visitor = new OracleOutputVisitor(out); for (SQLStatement stmt : stmtList) { stmt.accept(visitor); visitor.println(); } System.out.println(out.toString()); } }
OracleSelectParserTest
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/basic/InterceptedMethodInvokerTest.java
{ "start": 2281, "end": 2490 }
class ____ { @AroundInvoke Object aroundInvoke(InvocationContext ctx) throws Exception { return "intercepted: " + ctx.proceed(); } } @Singleton static
MyInterceptor
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/Suppliers.java
{ "start": 952, "end": 2073 }
class ____ { /** * Returns the singleton supplier that always returns null. * <p> * This supplier never throws an exception. * </p> */ @SuppressWarnings("rawtypes") private static Supplier NUL = () -> null; /** * Null-safe call to {@link Supplier#get()}. * * @param <T> the type of results supplied by this supplier. * @param supplier the supplier or null. * @return Result of {@link Supplier#get()} or null. */ public static <T> T get(final Supplier<T> supplier) { return supplier == null ? null : supplier.get(); } /** * Gets the singleton supplier that always returns null. * <p> * This supplier never throws an exception. * </p> * * @param <T> Supplied type. * @return The NUL singleton. * @since 3.14.0 */ @SuppressWarnings("unchecked") public static <T> Supplier<T> nul() { return NUL; } /** * Make private in 4.0. * * @deprecated TODO Make private in 4.0. */ @Deprecated public Suppliers() { // empty } }
Suppliers
java
quarkusio__quarkus
integration-tests/devtools/src/test/java/io/quarkus/devtools/codestarts/quarkus/RESTClientCodestartTest.java
{ "start": 470, "end": 1034 }
class ____ { @RegisterExtension public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder() .codestarts("rest-client") .languages(JAVA, KOTLIN) .build(); @Test void testContent() throws Throwable { codestartTest.checkGeneratedSource("org.acme.MyRemoteService"); } @Test @EnabledIfSystemProperty(named = "build-projects", matches = "true") void buildAllProjectsForLocalUse() throws Throwable { codestartTest.buildAllProjects(); } }
RESTClientCodestartTest
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/devmode/DevModeTestResource.java
{ "start": 351, "end": 811 }
class ____ { @Inject DependentTestBean bean; @POST @Path("/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String validateBean(@Valid TestBean testBean) { return "ok"; } @GET @Path("/{message}") @Produces(MediaType.TEXT_PLAIN) public String validateCDIBean(@PathParam("message") String message) { return bean.testMethod(message); } }
DevModeTestResource
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client-jackson/deployment/src/test/java/io/quarkus/restclient/jackson/deployment/ZonedDateTimeObjectMapperCustomizer.java
{ "start": 759, "end": 1505 }
class ____ implements ObjectMapperCustomizer { @Override public int priority() { return MINIMUM_PRIORITY; } @Override public void customize(ObjectMapper objectMapper) { SimpleModule customDateModule = new SimpleModule(); customDateModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer( new DateTimeFormatterBuilder().appendInstant(0).toFormatter().withZone(ZoneId.of("Z")))); customDateModule.addDeserializer(ZonedDateTime.class, new ZonedDateTimeEuropeLondonDeserializer()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .registerModule(customDateModule); } public static
ZonedDateTimeObjectMapperCustomizer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/EmbeddableElementCollectionMemberOfTest.java
{ "start": 948, "end": 1386 }
class ____ { @Test public void testMemberOfQuery(SessionFactoryScope scope) { scope.inTransaction( session -> { Address a = new Address(); a.setStreet( "Lollard Street" ); Query query = session.createQuery( "from Person p where :address member of p.addresses" ); query.setParameter( "address", a ); query.list(); } ); } @Entity(name = "Person") public static
EmbeddableElementCollectionMemberOfTest
java
elastic__elasticsearch
x-pack/plugin/ql/test-fixtures/src/main/java/org/elasticsearch/xpack/ql/SpecReader.java
{ "start": 685, "end": 3696 }
class ____ { private SpecReader() {} public static List<Object[]> readScriptSpec(URL source, String url, Parser parser) throws Exception { Objects.requireNonNull(source, "Cannot find resource " + url); return readURLSpec(source, parser); } public static List<Object[]> readScriptSpec(List<URL> urls, Parser parser) throws Exception { List<Object[]> results = emptyList(); for (URL url : urls) { List<Object[]> specs = readURLSpec(url, parser); if (results.isEmpty()) { results = specs; } else { results.addAll(specs); } } return results; } public static List<Object[]> readURLSpec(URL source, Parser parser) throws Exception { String fileName = pathAndName(source.getFile()).v2(); String groupName = fileName.substring(0, fileName.lastIndexOf('.')); Map<String, Integer> testNames = new LinkedHashMap<>(); List<Object[]> testCases = new ArrayList<>(); String testName = null; try (BufferedReader reader = TestUtils.reader(source)) { String line; int lineNumber = 1; while ((line = reader.readLine()) != null) { line = line.trim(); // ignore comments if (shouldSkipLine(line) == false) { // parse test name if (testName == null) { if (testNames.keySet().contains(line)) { throw new IllegalStateException( "Duplicate test name '" + line + "' at line " + lineNumber + " (previously seen at line " + testNames.get(line) + ")" ); } else { testName = Strings.capitalize(line); testNames.put(testName, Integer.valueOf(lineNumber)); } } else { Object result = parser.parse(line); // only if the parser is ready, add the object - otherwise keep on serving it lines if (result != null) { testCases.add(new Object[] { fileName, groupName, testName, Integer.valueOf(lineNumber), result }); testName = null; } } } lineNumber++; } if (testName != null) { throw new IllegalStateException("Read a test without a body at the end of [" + fileName + "]."); } } assertNull("Cannot find spec for test " + testName, testName); return testCases; } public
SpecReader
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/exceptions/Exceptions.java
{ "start": 771, "end": 878 }
class ____ help propagate checked exceptions and rethrow exceptions * designated as fatal. */ public final
to
java
alibaba__nacos
client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java
{ "start": 1181, "end": 2747 }
class ____ { private ConfigEncryptionFilter configEncryptionFilter; @Mock private ConfigRequest configRequest; @Mock private ConfigResponse configResponse; @Mock private IConfigFilterChain iConfigFilterChain; @BeforeEach void setUp() throws Exception { configEncryptionFilter = new ConfigEncryptionFilter(); } @Test void doFilter() throws NacosException { Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); Mockito.when(configRequest.getContent()).thenReturn("nacos"); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); Mockito.verify(configRequest, Mockito.atLeast(1)).getDataId(); Mockito.verify(configRequest, Mockito.atLeast(1)).getContent(); Mockito.when(configResponse.getDataId()).thenReturn("test-dataid"); Mockito.when(configResponse.getContent()).thenReturn("nacos"); Mockito.when(configResponse.getEncryptedDataKey()).thenReturn("1234567890"); configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); Mockito.verify(configResponse, Mockito.atLeast(1)).getDataId(); Mockito.verify(configResponse, Mockito.atLeast(1)).getContent(); Mockito.verify(configResponse, Mockito.atLeast(1)).getEncryptedDataKey(); } @Test void testGetOrder() { int order = configEncryptionFilter.getOrder(); assertEquals(0, order); } }
ConfigEncryptionFilterTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/SequenceFileAsTextInputFormat.java
{ "start": 1038, "end": 1303 }
class ____ similar to SequenceFileInputFormat, * except it generates SequenceFileAsTextRecordReader * which converts the input keys and values to their * String forms by calling toString() method. */ @InterfaceAudience.Public @InterfaceStability.Stable public
is
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorConcurrentAttemptsTest.java
{ "start": 9349, "end": 10196 }
class ____<T, SplitT extends SourceSplit> extends TestingSplitEnumerator.FactorySource<T, SplitT> { public TestSource( SimpleVersionedSerializer<SplitT> splitSerializer, SimpleVersionedSerializer<Set<SplitT>> checkpointSerializer) { super(splitSerializer, checkpointSerializer); } @Override public TestingSplitEnumerator<SplitT> createEnumerator( SplitEnumeratorContext<SplitT> enumContext) { return new TestEnumerator<>(enumContext); } @Override public SplitEnumerator<SplitT, Set<SplitT>> restoreEnumerator( SplitEnumeratorContext<SplitT> enumContext, Set<SplitT> checkpoint) { return new TestEnumerator<>(enumContext, checkpoint); } } private static
TestSource
java
netty__netty
codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
{ "start": 1369, "end": 6386 }
class ____ { private static final byte[][] packets = { { 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 1, 0, 1, -64, 12, 0, 1, 0, 1, 0, 0, 16, -113, 0, 4, -64, 0, 43, 10 }, { 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 28, 0, 1, -64, 12, 0, 28, 0, 1, 0, 0, 69, -8, 0, 16, 32, 1, 5, 0, 0, -120, 2, 0, 0, 0, 0, 0, 0, 0, 0, 16 }, { 0, 2, -127, -128, 0, 1, 0, 0, 0, 1, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 15, 0, 1, -64, 16, 0, 6, 0, 1, 0, 0, 3, -43, 0, 45, 3, 115, 110, 115, 3, 100, 110, 115, 5, 105, 99, 97, 110, 110, 3, 111, 114, 103, 0, 3, 110, 111, 99, -64, 49, 119, -4, 39, 112, 0, 0, 28, 32, 0, 0, 14, 16, 0, 18, 117, 0, 0, 0, 14, 16 }, { 0, 3, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3, 99, 111, 109, 0, 0, 16, 0, 1, -64, 12, 0, 16, 0, 1, 0, 0, 84, 75, 0, 12, 11, 118, 61, 115, 112, 102, 49, 32, 45, 97, 108, 108 }, { -105, 19, -127, 0, 0, 1, 0, 0, 0, 13, 0, 0, 2, 104, 112, 11, 116, 105, 109, 98, 111, 117, 100, 114, 101, 97, 117, 3, 111, 114, 103, 0, 0, 1, 0, 1, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 20, 1, 68, 12, 82, 79, 79, 84, 45, 83, 69, 82, 86, 69, 82, 83, 3, 78, 69, 84, 0, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 70, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 69, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 75, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 67, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 76, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 71, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 73, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 66, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 77, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 65, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 72, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 74, -64, 49 } }; private static final byte[] malformedLoopPacket = { 0, 4, -127, -128, 0, 1, 0, 0, 0, 0, 0, 0, -64, 12, 0, 1, 0, 1 }; @Test public void readResponseTest() { EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder()); for (byte[] p: packets) { ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p); embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))); AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = embedder.readInbound(); assertInstanceOf(DatagramDnsResponse.class, envelope); DnsResponse response = envelope.content(); assertSame(envelope, response); ByteBuf raw = Unpooled.wrappedBuffer(p); assertEquals(raw.getUnsignedShort(0), response.id()); assertEquals(raw.getUnsignedShort(4), response.count(DnsSection.QUESTION)); assertEquals(raw.getUnsignedShort(6), response.count(DnsSection.ANSWER)); assertEquals(raw.getUnsignedShort(8), response.count(DnsSection.AUTHORITY)); assertEquals(raw.getUnsignedShort(10), response.count(DnsSection.ADDITIONAL)); envelope.release(); } assertFalse(embedder.finish()); } @Test public void readMalformedResponseTest() { final EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder()); final ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket); try { assertThrows(CorruptedFrameException.class, new Executable() { @Override public void execute() { embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))); } }); } finally { assertFalse(embedder.finish()); } } @Test public void readIncompleteResponseTest() { final EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder()); final ByteBuf packet = embedder.alloc().buffer(512); try { assertThrows(CorruptedFrameException.class, new Executable() { @Override public void execute() { embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0))); } }); } finally { assertFalse(embedder.finish()); } } }
DnsResponseTest
java
alibaba__nacos
maintainer-client/src/main/java/com/alibaba/nacos/maintainer/client/model/HttpRequest.java
{ "start": 2508, "end": 3833 }
class ____ { private String httpMethod; private String path; private final Map<String, String> headers = new HashMap<>(); private final Map<String, String> paramValues = new HashMap<>(); private String body; private RequestResource resource; public Builder setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; return this; } public Builder setPath(String path) { this.path = path; return this; } public Builder addHeader(Map<String, String> header) { headers.putAll(header); return this; } public Builder setParamValue(Map<String, String> params) { paramValues.putAll(params); return this; } public Builder setBody(String body) { this.body = body; return this; } public Builder setResource(RequestResource resource) { this.resource = resource; return this; } public HttpRequest build() { return new HttpRequest(httpMethod, path, headers, paramValues, body, resource); } } }
Builder
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/RollbackCustomMessageTest.java
{ "start": 1186, "end": 1934 }
class ____ extends ContextTestSupport { @Test public void testRollbackCustomMessage() { try { template.sendBody("direct:start", "Hello World"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(RollbackExchangeException.class, e.getCause()); assertTrue(e.getCause().getMessage().startsWith("boo")); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.setTracing(true); from("direct:start").rollback("boo"); } }; } }
RollbackCustomMessageTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/RollingFileSystemSinkTestBase.java
{ "start": 18802, "end": 19824 }
class ____ extends RollingFileSystemSink { public static volatile boolean errored = false; public static volatile boolean initialized = false; @Override public void init(SubsetConfiguration conf) { try { super.init(conf); } catch (MetricsException ex) { errored = true; throw new MetricsException(ex); } initialized = true; } @Override public void putMetrics(MetricsRecord record) { try { super.putMetrics(record); } catch (MetricsException ex) { errored = true; throw new MetricsException(ex); } } @Override public void close() { try { super.close(); } catch (MetricsException ex) { errored = true; throw new MetricsException(ex); } } @Override public void flush() { try { super.flush(); } catch (MetricsException ex) { errored = true; throw new MetricsException(ex); } } } }
MockSink
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
{ "start": 6527, "end": 6994 }
class ____ { @javax.annotation.CheckReturnValue public static int check() { return 1; } public static void ignoresCheck() { // BUG: Diagnostic contains: check(); } } }\ """) .doTest(); } @Test public void customCheckReturnValueAnnotation() { compilationHelper .addSourceLines( "foo/bar/CheckReturnValue.java", """ package foo.bar; public @
JavaxAnnotation
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/relational/ColumnOrderingStrategyLegacy.java
{ "start": 470, "end": 1126 }
class ____ implements ColumnOrderingStrategy { public static final ColumnOrderingStrategyLegacy INSTANCE = new ColumnOrderingStrategyLegacy(); @Override public List<Column> orderTableColumns(Table table, Metadata metadata) { return null; } @Override public List<Column> orderConstraintColumns(Constraint constraint, Metadata metadata) { return null; } @Override public List<Column> orderUserDefinedTypeColumns(UserDefinedObjectType userDefinedType, Metadata metadata) { return null; } @Override public void orderTemporaryTableColumns(List<TemporaryTableColumn> temporaryTableColumns, Metadata metadata) { } }
ColumnOrderingStrategyLegacy
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/PropertyAliasTest.java
{ "start": 4475, "end": 5429 }
class ____ { @JsonAlias({"a", "b", "c"}) public String value; } @Test public void testAliasDeserializedToLastMatchingKey_ascendingKeys() throws Exception { String ascendingOrderInput = a2q( "{\"a\": \"a-value\", " + "\"b\": \"b-value\", " + "\"c\": \"c-value\"}"); FixedOrderAliasBean ascObj = MAPPER.readValue(ascendingOrderInput, FixedOrderAliasBean.class); assertEquals("c-value", ascObj.value); } @Test public void testAliasDeserializedToLastMatchingKey_descendingKeys() throws Exception { String descendingOrderInput = a2q( "{\"c\": \"c-value\", " + "\"b\": \"b-value\", " + "\"a\": \"a-value\"}"); FixedOrderAliasBean descObj = MAPPER.readValue(descendingOrderInput, FixedOrderAliasBean.class); assertEquals("a-value", descObj.value); } static
FixedOrderAliasBean
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java
{ "start": 1634, "end": 2496 }
interface ____ { /** * Alias for {@link #name}. */ @AliasFor("name") String value() default ""; /** * The name of the request header to bind to. * @since 4.2 */ @AliasFor("value") String name() default ""; /** * Whether the header is required. * <p>Defaults to {@code true}, leading to an exception being thrown * if the header is missing in the request. Switch this to * {@code false} if you prefer a {@code null} value if the header is * not present in the request. * <p>Alternatively, provide a {@link #defaultValue}, which implicitly * sets this flag to {@code false}. */ boolean required() default true; /** * The default value to use as a fallback. * <p>Supplying a default value implicitly sets {@link #required} to * {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; }
RequestHeader