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
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsRouteWithCustomKeyFormatStrategyTest.java
{ "start": 1488, "end": 2135 }
class ____ implements JmsKeyFormatStrategy { @Override public String encodeKey(String key) { key = key.replace("-", "_HYPHEN_") .replace(".", "_DOT_"); return "FOO" + key + "BAR"; } @Override public String decodeKey(String key) { if (key.startsWith("FOO") && key.endsWith("BAR")) { key = key.replace("_HYPHEN_", "-") .replace("_DOT_", "."); return StringHelper.between(key, "FOO", "BAR"); } else { return key; } } } }
MyCustomKeyFormatStrategy
java
grpc__grpc-java
api/src/main/java/io/grpc/ClientInterceptor.java
{ "start": 1602, "end": 2675 }
interface ____ { /** * Intercept {@link ClientCall} creation by the {@code next} {@link Channel}. * * <p>Many variations of interception are possible. Complex implementations may return a wrapper * around the result of {@code next.newCall()}, whereas a simpler implementation may just modify * the header metadata prior to returning the result of {@code next.newCall()}. * * <p>{@code next.newCall()} <strong>must not</strong> be called under a different {@link Context} * other than the current {@code Context}. The outcome of such usage is undefined and may cause * memory leak due to unbounded chain of {@code Context}s. * * @param method the remote method to be called. * @param callOptions the runtime options to be applied to this call. * @param next the channel which is being intercepted. * @return the call object for the remote operation, never {@code null}. */ <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next); }
ClientInterceptor
java
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/EngineFilter.java
{ "start": 1415, "end": 5347 }
class ____ implements Filter<TestEngine> { /** * Create a new <em>include</em> {@code EngineFilter} based on the * supplied engine IDs. * * <p>Only {@code TestEngines} with matching engine IDs will be * <em>included</em> within the test discovery and execution. * * @param engineIds the list of engine IDs to match against; never {@code null} * or empty; individual IDs must also not be null or blank * @see #includeEngines(String...) */ public static EngineFilter includeEngines(String... engineIds) { return includeEngines(Arrays.asList(engineIds)); } /** * Create a new <em>include</em> {@code EngineFilter} based on the * supplied engine IDs. * * <p>Only {@code TestEngines} with matching engine IDs will be * <em>included</em> within the test discovery and execution. * * @param engineIds the list of engine IDs to match against; never {@code null} * or empty; individual IDs must also not be null or blank * @see #includeEngines(String...) */ public static EngineFilter includeEngines(List<String> engineIds) { return new EngineFilter(engineIds, Type.INCLUDE); } /** * Create a new <em>exclude</em> {@code EngineFilter} based on the * supplied engine IDs. * * <p>{@code TestEngines} with matching engine IDs will be * <em>excluded</em> from test discovery and execution. * * @param engineIds the list of engine IDs to match against; never {@code null} * or empty; individual IDs must also not be null or blank * @see #excludeEngines(List) */ public static EngineFilter excludeEngines(String... engineIds) { return excludeEngines(Arrays.asList(engineIds)); } /** * Create a new <em>exclude</em> {@code EngineFilter} based on the * supplied engine IDs. * * <p>{@code TestEngines} with matching engine IDs will be * <em>excluded</em> from test discovery and execution. * * @param engineIds the list of engine IDs to match against; never {@code null} * or empty; individual IDs must also not be null or blank * @see #includeEngines(String...) */ public static EngineFilter excludeEngines(List<String> engineIds) { return new EngineFilter(engineIds, Type.EXCLUDE); } private final List<String> engineIds; private final Type type; private EngineFilter(List<String> engineIds, Type type) { this.engineIds = validateAndTrim(engineIds); this.type = type; } @API(status = INTERNAL, since = "1.9") public List<String> getEngineIds() { return engineIds; } @API(status = INTERNAL, since = "1.9") public boolean isIncludeFilter() { return type == Type.INCLUDE; } @Override public FilterResult apply(TestEngine testEngine) { Preconditions.notNull(testEngine, "TestEngine must not be null"); String engineId = testEngine.getId(); Preconditions.notBlank(engineId, "TestEngine ID must not be null or blank"); if (this.type == Type.INCLUDE) { return includedIf(this.engineIds.stream().anyMatch(engineId::equals), // () -> "Engine ID [%s] is in included list [%s]".formatted(engineId, this.engineIds), // () -> "Engine ID [%s] is not in included list [%s]".formatted(engineId, this.engineIds)); } else { return includedIf(this.engineIds.stream().noneMatch(engineId::equals), // () -> "Engine ID [%s] is not in excluded list [%s]".formatted(engineId, this.engineIds), // () -> "Engine ID [%s] is in excluded list [%s]".formatted(engineId, this.engineIds)); } } @Override public String toString() { return "%s that %s engines with IDs %s".formatted(getClass().getSimpleName(), this.type.verb, this.engineIds); } private static List<String> validateAndTrim(List<String> engineIds) { Preconditions.notEmpty(engineIds, "engine ID list must not be null or empty"); // @formatter:off return engineIds.stream() .map(id -> Preconditions.notBlank(id, "engine ID must not be null or blank").strip()) .distinct() .toList(); // @formatter:on } private
EngineFilter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/merge/CompositeIdWithAssociationsAndGeneratedValuesMergeTest.java
{ "start": 3715, "end": 4604 }
class ____ { private Long id; private String name; private List<Middle> middles; public Top() { } public Top(String name) { this.name = name; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy = "top", cascade = { CascadeType.MERGE, CascadeType.PERSIST }) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public List<Middle> getMiddles() { return middles; } public void setMiddles(List<Middle> middles) { this.middles = middles; } public void addMiddle(Middle middle) { if ( middles == null ) { middles = new ArrayList<>(); } middles.add( middle ); } } @Entity(name = "Middle") @Table(name = "middle_table") public static
Top
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/loadGenerator/LoadGenerator.java
{ "start": 10062, "end": 27863 }
class ____ extends SubjectInheritingThread { private int id; private long [] executionTime = new long[TOTAL_OP_TYPES]; private long [] totalNumOfOps = new long[TOTAL_OP_TYPES]; private byte[] buffer = new byte[1024]; private boolean failed; private DFSClientThread(int id) { this.id = id; } /** Main loop for each thread * Each iteration decides what's the next operation and then pauses. */ @Override public void work() { try { while (shouldRun) { nextOp(); delay(); } } catch (Exception ioe) { System.err.println(ioe.getLocalizedMessage()); ioe.printStackTrace(); failed = true; } } /** Let the thread pause for a random amount of time in the range of * [0, maxDelayBetweenOps] if the delay is not zero. Otherwise, no pause. */ private void delay() throws InterruptedException { if (maxDelayBetweenOps>0) { int delay = r.nextInt(maxDelayBetweenOps); Thread.sleep(delay); } } /** Perform the next operation. * * Depending on the read and write probabilities, the next * operation could be either read, write, or list. */ private void nextOp() throws IOException { double rn = r.nextDouble(); int i = currentIndex; if(LOG.isDebugEnabled()) LOG.debug("Thread " + this.id + " moving to index " + i); if (rn < readProbs[i]) { read(); } else if (rn < readProbs[i] + writeProbs[i]) { write(); } else { list(); } } /** Read operation randomly picks a file in the test space and reads * the entire file */ private void read() throws IOException { String fileName = files.get(r.nextInt(files.size())); long startTimestamp = Time.monotonicNow(); InputStream in = fc.open(new Path(fileName)); executionTime[OPEN] += (Time.monotonicNow() - startTimestamp); totalNumOfOps[OPEN]++; while (in.read(buffer) != -1) {} in.close(); } /** The write operation randomly picks a directory in the * test space and creates a file whose name consists of the current * machine's host name and the thread id. The length of the file * follows Gaussian distribution with an average size of 2 blocks and * the standard deviation of 1 block. The new file is filled with 'a'. * Immediately after the file creation completes, the file is deleted * from the test space. */ private void write() throws IOException { String dirName = dirs.get(r.nextInt(dirs.size())); Path file = new Path(dirName, hostname + id + UUID.randomUUID().toString()); double fileSize = 0; while ((fileSize = r.nextGaussian()+2)<=0) {} genFile(file, (long)(fileSize*BLOCK_SIZE)); long startTimestamp = Time.monotonicNow(); fc.delete(file, true); executionTime[DELETE] += (Time.monotonicNow() - startTimestamp); totalNumOfOps[DELETE]++; } /** The list operation randomly picks a directory in the test space and * list the directory content. */ private void list() throws IOException { String dirName = dirs.get(r.nextInt(dirs.size())); long startTimestamp = Time.monotonicNow(); fc.listStatus(new Path(dirName)); executionTime[LIST] += (Time.monotonicNow() - startTimestamp); totalNumOfOps[LIST]++; } /** Create a file with a length of <code>fileSize</code>. * The file is filled with 'a'. */ private void genFile(Path file, long fileSize) throws IOException { long startTimestamp = Time.monotonicNow(); FSDataOutputStream out = null; boolean isOutClosed = false; try { out = fc.create(file, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), CreateOpts.createParent(), CreateOpts.bufferSize(4096), CreateOpts.repFac((short) 3)); executionTime[CREATE] += (Time.monotonicNow() - startTimestamp); numOfOps[CREATE]++; long i = fileSize; while (i > 0) { long s = Math.min(fileSize, WRITE_CONTENTS.length); out.write(WRITE_CONTENTS, 0, (int) s); i -= s; } startTime = Time.monotonicNow(); out.close(); executionTime[WRITE_CLOSE] += (Time.monotonicNow() - startTime); numOfOps[WRITE_CLOSE]++; isOutClosed = true; } finally { if (!isOutClosed && out != null) { out.close(); } } } } /** Main function called by tool runner. * It first initializes data by parsing the command line arguments. * It then calls the loadGenerator */ @Override public int run(String[] args) throws Exception { int exitCode = parseArgs(false, args); if (exitCode != 0) { return exitCode; } System.out.println("Running LoadGenerator against fileSystem: " + FileContext.getFileContext().getDefaultFileSystem().getUri()); exitCode = generateLoadOnNN(); printResults(System.out); return exitCode; } boolean stopFileCreated() { try { fc.getFileStatus(flagFile); } catch (FileNotFoundException e) { return false; } catch (IOException e) { LOG.error("Got error when checking if file exists:" + flagFile, e); } LOG.info("Flag file was created. Stopping the test."); return true; } /** * This is the main function - run threads to generate load on NN * It starts the number of DFSClient threads as specified by * the user. * It stops all the threads when the specified elapsed time is passed. */ protected int generateLoadOnNN() throws InterruptedException { int hostHashCode = hostname.hashCode(); if (seed == 0) { r = new Random(System.currentTimeMillis()+hostHashCode); } else { r = new Random(seed+hostHashCode); } try { fc = FileContext.getFileContext(getConf()); } catch (IOException ioe) { System.err.println("Can not initialize the file system: " + ioe.getLocalizedMessage()); return -1; } int status = initFileDirTables(); if (status != 0) { return status; } barrier(); DFSClientThread[] threads = new DFSClientThread[numOfThreads]; for (int i=0; i<numOfThreads; i++) { threads[i] = new DFSClientThread(i); threads[i].start(); } if (durations[0] > 0) { if (durations.length == 1) {// There is a fixed run time while (shouldRun) { Thread.sleep(2000); totalTime += 2; if (totalTime >= durations[0] || stopFileCreated()) { shouldRun = false; } } } else { // script run while (shouldRun) { Thread.sleep(durations[currentIndex] * 1000); totalTime += durations[currentIndex]; // Are we on the final line of the script? if ((currentIndex + 1) == durations.length || stopFileCreated()) { shouldRun = false; } else { if (LOG.isDebugEnabled()) { LOG.debug("Moving to index " + currentIndex + ": r = " + readProbs[currentIndex] + ", w = " + writeProbs + " for duration " + durations[currentIndex]); } currentIndex++; } } } } if(LOG.isDebugEnabled()) { LOG.debug("Done with testing. Waiting for threads to finish."); } boolean failed = false; for (DFSClientThread thread : threads) { thread.join(); for (int i=0; i<TOTAL_OP_TYPES; i++) { executionTime[i] += thread.executionTime[i]; numOfOps[i] += thread.totalNumOfOps[i]; } failed = failed || thread.failed; } int exitCode = 0; if (failed) { exitCode = -ERR_TEST_FAILED; } totalOps = 0; for (int i=0; i<TOTAL_OP_TYPES; i++) { totalOps += numOfOps[i]; } return exitCode; } protected static void printResults(PrintStream out) throws UnsupportedFileSystemException { out.println("Result of running LoadGenerator against fileSystem: " + FileContext.getFileContext().getDefaultFileSystem().getUri()); if (numOfOps[OPEN] != 0) { out.println("Average open execution time: " + (double)executionTime[OPEN]/numOfOps[OPEN] + "ms"); } if (numOfOps[LIST] != 0) { out.println("Average list execution time: " + (double)executionTime[LIST]/numOfOps[LIST] + "ms"); } if (numOfOps[DELETE] != 0) { out.println("Average deletion execution time: " + (double)executionTime[DELETE]/numOfOps[DELETE] + "ms"); out.println("Average create execution time: " + (double)executionTime[CREATE]/numOfOps[CREATE] + "ms"); out.println("Average write_close execution time: " + (double)executionTime[WRITE_CLOSE]/numOfOps[WRITE_CLOSE] + "ms"); } if (totalTime != 0) { out.println("Average operations per second: " + (double)totalOps/totalTime +"ops/s"); } out.println(); } /** Parse the command line arguments and initialize the data */ protected int parseArgs(boolean runAsMapReduce, String[] args) throws IOException { try { for (int i = 0; i < args.length; i++) { // parse command line if (args[i].equals("-scriptFile")) { scriptFile = args[++i]; if (durations[0] > 0) { System.err.println("Can't specify elapsedTime and use script."); return -1; } } else if (args[i].equals("-readProbability")) { if (scriptFile != null) { System.err.println("Can't specify probabilities and use script."); return -1; } readProbs[0] = Double.parseDouble(args[++i]); if (readProbs[0] < 0 || readProbs[0] > 1) { System.err.println( "The read probability must be [0, 1]: " + readProbs[0]); return -1; } } else if (args[i].equals("-writeProbability")) { if (scriptFile != null) { System.err.println("Can't specify probabilities and use script."); return -1; } writeProbs[0] = Double.parseDouble(args[++i]); if (writeProbs[0] < 0 || writeProbs[0] > 1) { System.err.println( "The write probability must be [0, 1]: " + writeProbs[0]); return -1; } } else if (args[i].equals("-root")) { root = new Path(args[++i]); } else if (args[i].equals("-maxDelayBetweenOps")) { maxDelayBetweenOps = Integer.parseInt(args[++i]); // in milliseconds } else if (args[i].equals("-numOfThreads")) { numOfThreads = Integer.parseInt(args[++i]); if (numOfThreads <= 0) { System.err.println( "Number of threads must be positive: " + numOfThreads); return -1; } } else if (args[i].equals("-startTime")) { startTime = Long.parseLong(args[++i]); } else if (args[i].equals("-elapsedTime")) { if (scriptFile != null) { System.err.println("Can't specify elapsedTime and use script."); return -1; } durations[0] = Long.parseLong(args[++i]); } else if (args[i].equals("-seed")) { seed = Long.parseLong(args[++i]); r = new Random(seed); } else if (args[i].equals("-flagFile")) { LOG.info("got flagFile:" + flagFile); flagFile = new Path(args[++i]); }else { System.err.println(USAGE); ToolRunner.printGenericCommandUsage(System.err); return -1; } } } catch (NumberFormatException e) { System.err.println("Illegal parameter: " + e.getLocalizedMessage()); System.err.println(USAGE); return -1; } // Load Script File if not MR; for MR scriptFile is loaded by Mapper if (!runAsMapReduce && scriptFile != null) { if(loadScriptFile(scriptFile, true) == -1) return -1; } for(int i = 0; i < readProbs.length; i++) { if (readProbs[i] + writeProbs[i] <0 || readProbs[i]+ writeProbs[i] > 1) { System.err.println( "The sum of read probability and write probability must be [0, 1]: " + readProbs[i] + " " + writeProbs[i]); return -1; } } return 0; } private static void parseScriptLine(String line, ArrayList<Long> duration, ArrayList<Double> readProb, ArrayList<Double> writeProb) { String[] a = line.split("\\s"); if (a.length != 3) { throw new IllegalArgumentException("Incorrect number of parameters: " + line); } try { long d = Long.parseLong(a[0]); double r = Double.parseDouble(a[1]); double w = Double.parseDouble(a[2]); Preconditions.checkArgument(d >= 0, "Invalid duration: " + d); Preconditions.checkArgument(0 <= r && r <= 1.0, "The read probability must be [0, 1]: " + r); Preconditions.checkArgument(0 <= w && w <= 1.0, "The read probability must be [0, 1]: " + w); readProb.add(r); duration.add(d); writeProb.add(w); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Cannot parse: " + line); } } /** * Read a script file of the form: lines of text with duration in seconds, * read probability and write probability, separated by white space. * * @param filename Script file * @return 0 if successful, -1 if not * @throws IOException if errors with file IO */ protected static int loadScriptFile(String filename, boolean readLocally) throws IOException { FileContext fc; if (readLocally) { // read locally - program is run without MR fc = FileContext.getLocalFSFileContext(); } else { fc = FileContext.getFileContext(); // use default file system } DataInputStream in = null; try { in = fc.open(new Path(filename)); } catch (IOException e) { System.err.println("Unable to open scriptFile: " + filename); System.exit(-1); } InputStreamReader inr = new InputStreamReader(in); BufferedReader br = new BufferedReader(inr); ArrayList<Long> duration = new ArrayList<Long>(); ArrayList<Double> readProb = new ArrayList<Double>(); ArrayList<Double> writeProb = new ArrayList<Double>(); int lineNum = 0; String line; // Read script, parse values, build array of duration, read and write probs try { while ((line = br.readLine()) != null) { lineNum++; if (line.startsWith("#") || line.isEmpty()) // skip comments and blanks continue; parseScriptLine(line, duration, readProb, writeProb); } } catch (IllegalArgumentException e) { System.err.println("Line: " + lineNum + ", " + e.getMessage()); return -1; } finally { IOUtils.cleanupWithLogger(LOG, br); } // Copy vectors to arrays of values, to avoid autoboxing overhead later durations = new long[duration.size()]; readProbs = new double[readProb.size()]; writeProbs = new double[writeProb.size()]; for(int i = 0; i < durations.length; i++) { durations[i] = duration.get(i); readProbs[i] = readProb.get(i); writeProbs[i] = writeProb.get(i); } if(durations[0] == 0) System.err.println("Initial duration set to 0. " + "Will loop until stopped manually."); return 0; } /** Create a table that contains all directories under root and * another table that contains all files under root. */ private int initFileDirTables() { try { initFileDirTables(root); } catch (IOException e) { System.err.println(e.getLocalizedMessage()); e.printStackTrace(); return -1; } if (dirs.isEmpty()) { System.err.println("The test space " + root + " is empty"); return -1; } if (files.isEmpty()) { System.err.println("The test space " + root + " does not have any file"); return -1; } return 0; } /** Create a table that contains all directories under the specified path and * another table that contains all files under the specified path and * whose name starts with "_file_". */ private void initFileDirTables(Path path) throws IOException { FileStatus[] stats = fc.util().listStatus(path); for (FileStatus stat : stats) { if (stat.isDirectory()) { dirs.add(stat.getPath().toString()); initFileDirTables(stat.getPath()); } else { Path filePath = stat.getPath(); if (filePath.getName().startsWith(StructureGenerator.FILE_NAME_PREFIX)) { files.add(filePath.toString()); } } } } /** Returns when the current number of seconds from the epoch equals * the command line argument given by <code>-startTime</code>. * This allows multiple instances of this program, running on clock * synchronized nodes, to start at roughly the same time. */ private static void barrier() { long sleepTime; while ((sleepTime = startTime - Time.now()) > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException ex) { } } } /** Main program * * @param args command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new LoadGenerator(), args); System.exit(res); } }
DFSClientThread
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/ReplaceTests.java
{ "start": 5363, "end": 5647 }
class ____ index 0\n[\n^".replaceAll( "\n", System.lineSeparator() ) ) .withFoldingException( PatternSyntaxException.class, "Unclosed character
near
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/reporting/legacy/xml/LegacyXmlReportGeneratingListenerTests.java
{ "start": 2635, "end": 17809 }
class ____ { @TempDir Path tempDirectory; @Test void writesFileForSingleSucceedingTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("succeedingTest", "display<-->Name 😎", () -> { }); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("name")).isEqualTo("dummy"); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(0); assertThat(testsuite.attr("failures", int.class)).isEqualTo(0); assertThat(testsuite.attr("errors", int.class)).isEqualTo(0); assertThat(testsuite.child("system-out").text()) // .containsSubsequence("unique-id: [engine:dummy]", "display-name: dummy"); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("display<-->Name 😎"); assertThat(testcase.attr("classname")).isEqualTo("dummy"); assertThat(testcase.child("system-out").text()) // .containsSubsequence("unique-id: [engine:dummy]/[test:succeedingTest]", "display-name: display<-->Name 😎"); assertThat(testsuite.find("skipped")).isEmpty(); assertThat(testsuite.find("failure")).isEmpty(); assertThat(testsuite.find("error")).isEmpty(); } @Test void writesFileForSingleFailingTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("failingTest", () -> fail("expected to <b>fail</b>")); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(0); assertThat(testsuite.attr("failures", int.class)).isEqualTo(1); assertThat(testsuite.attr("errors", int.class)).isEqualTo(0); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("failingTest"); var failure = testcase.child("failure"); assertThat(failure.attr("message")).isEqualTo("expected to <b>fail</b>"); assertThat(failure.attr("type")).isEqualTo(AssertionFailedError.class.getName()); assertThat(failure.text()).containsSubsequence("AssertionFailedError: expected to <b>fail</b>", "\tat"); assertThat(testsuite.find("skipped")).isEmpty(); assertThat(testsuite.find("error")).isEmpty(); } @Test void writesFileForSingleErroneousTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("failingTest", () -> { throw new RuntimeException("error occurred"); }); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(0); assertThat(testsuite.attr("failures", int.class)).isEqualTo(0); assertThat(testsuite.attr("errors", int.class)).isEqualTo(1); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("failingTest"); var error = testcase.child("error"); assertThat(error.attr("message")).isEqualTo("error occurred"); assertThat(error.attr("type")).isEqualTo(RuntimeException.class.getName()); assertThat(error.text()).containsSubsequence("RuntimeException: error occurred", "\tat"); assertThat(testsuite.find("skipped")).isEmpty(); assertThat(testsuite.find("failure")).isEmpty(); } @Test void writesFileForSingleSkippedTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); var testDescriptor = engine.addTest("skippedTest", () -> fail("never called")); testDescriptor.markSkipped("should be skipped"); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(1); assertThat(testsuite.attr("failures", int.class)).isEqualTo(0); assertThat(testsuite.attr("errors", int.class)).isEqualTo(0); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("skippedTest"); assertThat(testcase.child("skipped").text()).isEqualTo("should be skipped"); assertThat(testsuite.find("failure")).isEmpty(); assertThat(testsuite.find("error")).isEmpty(); } @SuppressWarnings("ConstantConditions") @Test void writesFileForSingleAbortedTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("abortedTest", () -> assumeFalse(true, "deliberately aborted")); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(1); assertThat(testsuite.attr("failures", int.class)).isEqualTo(0); assertThat(testsuite.attr("errors", int.class)).isEqualTo(0); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("abortedTest"); assertThat(testcase.child("skipped").text()) // .containsSubsequence("TestAbortedException: ", "deliberately aborted", "at "); assertThat(testsuite.find("failure")).isEmpty(); assertThat(testsuite.find("error")).isEmpty(); } @Test void measuresTimesInSeconds() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("firstTest", () -> { }); engine.addTest("secondTest", () -> { }); executeTests(engine, new IncrementingClock(0, Duration.ofMillis(333))); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); // start end // ----------- ---------- ----------- // engine 0 (1) 1,665 (6) // firstTest 333 (2) 666 (3) // secondTest 999 (4) 1,332 (5) assertThat(testsuite.attr("time", double.class)) // .isEqualTo(1.665); assertThat(testsuite.children("testcase").matchAttr("name", "firstTest").attr("time", double.class)) // .isEqualTo(0.333); assertThat(testsuite.children("testcase").matchAttr("name", "secondTest").attr("time", double.class)) // .isEqualTo(0.333); } @Test void testWithImmeasurableTimeIsOutputCorrectly() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("test", () -> { }); executeTests(engine, Clock.fixed(Instant.EPOCH, ZoneId.systemDefault())); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.child("testcase").attr("time")).isEqualTo("0"); } @Test void writesFileForSkippedContainer() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("test", () -> fail("never called")); engine.getEngineDescriptor().markSkipped("should be skipped"); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("skipped", int.class)).isEqualTo(1); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("test"); assertThat(testcase.child("skipped").text()).isEqualTo("parent was skipped: should be skipped"); } @Test void writesFileForFailingContainer() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("test", () -> fail("never called")); engine.getEngineDescriptor().setBeforeAllBehavior(() -> fail("failure before all tests")); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("failures", int.class)).isEqualTo(1); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("test"); var failure = testcase.child("failure"); assertThat(failure.attr("message")).isEqualTo("failure before all tests"); assertThat(failure.attr("type")).isEqualTo(AssertionFailedError.class.getName()); assertThat(failure.text()).containsSubsequence("AssertionFailedError: failure before all tests", "\tat"); } @Test void writesFileForFailingContainerWithoutTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addContainer("failingContainer", () -> { throw new RuntimeException("boom"); }); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("errors", int.class)).isEqualTo(1); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("failingContainer"); assertThat(testcase.attr("classname")).isEqualTo("dummy"); var error = testcase.child("error"); assertThat(error.attr("message")).isEqualTo("boom"); assertThat(error.attr("type")).isEqualTo(RuntimeException.class.getName()); assertThat(error.text()).containsSubsequence("RuntimeException: boom", "\tat"); } @Test void writesFileForContainerFailingAfterTest() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); var container = engine.addChild("failingContainer", uniqueId -> new DemoHierarchicalContainerDescriptor(uniqueId, "failingContainer", null, null) { @Override public void after(DemoEngineExecutionContext context) { throw new RuntimeException("boom"); } }, "child"); container.addChild(new DemoHierarchicalTestDescriptor(container.getUniqueId().append("test", "someTest"), "someTest", (c, t) -> { })); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("tests", int.class)).isEqualTo(1); assertThat(testsuite.attr("errors", int.class)).isEqualTo(1); var testcase = testsuite.child("testcase"); assertThat(testcase.attr("name")).isEqualTo("someTest"); assertThat(testcase.attr("classname")).isEqualTo("failingContainer"); var error = testcase.child("error"); assertThat(error.attr("message")).isEqualTo("boom"); assertThat(error.attr("type")).isEqualTo(RuntimeException.class.getName()); assertThat(error.text()).containsSubsequence("RuntimeException: boom", "\tat"); } @Test void writesSystemProperties() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("test", () -> { }); executeTests(engine); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); var properties = testsuite.child("properties").children("property"); assertThat(properties.matchAttr("name", "file\\.separator").attr("value")).isEqualTo(File.separator); assertThat(properties.matchAttr("name", "path\\.separator").attr("value")).isEqualTo(File.pathSeparator); } @Test void writesHostNameAndTimestamp() throws Exception { var engine = new DemoHierarchicalTestEngine("dummy"); engine.addTest("test", () -> { }); var now = LocalDateTime.parse("2016-01-28T14:02:59.123"); var zone = ZoneId.systemDefault(); executeTests(engine, Clock.fixed(ZonedDateTime.of(now, zone).toInstant(), zone)); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-dummy.xml")); assertThat(testsuite.attr("hostname")).isEqualTo(InetAddress.getLocalHost().getHostName()); assertThat(testsuite.attr("timestamp")).isEqualTo("2016-01-28T14:02:59"); } @Test void printsExceptionWhenReportsDirCannotBeCreated() throws Exception { var reportsDir = tempDirectory.resolve("dummy.txt"); Files.write(reportsDir, Set.of("content")); var out = new StringWriter(); var listener = new LegacyXmlReportGeneratingListener(reportsDir, new PrintWriter(out)); listener.testPlanExecutionStarted(TestPlan.from(true, Set.of(), mock(), dummyOutputDirectoryCreator())); assertThat(out.toString()).containsSubsequence("Could not create reports directory", "FileAlreadyExistsException", "at "); } @Test void printsExceptionWhenReportCouldNotBeWritten() throws Exception { var engineDescriptor = new EngineDescriptor(UniqueId.forEngine("engine"), "Engine"); var xmlFile = tempDirectory.resolve("TEST-engine.xml"); Files.createDirectories(xmlFile); var out = new StringWriter(); var listener = new LegacyXmlReportGeneratingListener(tempDirectory, new PrintWriter(out)); listener.testPlanExecutionStarted( TestPlan.from(true, Set.of(engineDescriptor), mock(), dummyOutputDirectoryCreator())); listener.executionFinished(TestIdentifier.from(engineDescriptor), successful()); assertThat(out.toString()).containsSubsequence("Could not write XML report", "Exception", "at "); } @Test void writesReportEntriesToSystemOutElement() throws Exception { var engineDescriptor = new EngineDescriptor(UniqueId.forEngine("engine"), "Engine"); var childUniqueId = UniqueId.root("child", "test"); engineDescriptor.addChild(new TestDescriptorStub(childUniqueId, "test")); var testPlan = TestPlan.from(true, Set.of(engineDescriptor), mock(), dummyOutputDirectoryCreator()); var out = new StringWriter(); var listener = new LegacyXmlReportGeneratingListener(tempDirectory, new PrintWriter(out)); listener.testPlanExecutionStarted(testPlan); var testIdentifier = testPlan.getTestIdentifier(childUniqueId); listener.executionStarted(testIdentifier); listener.reportingEntryPublished(testIdentifier, ReportEntry.from("foo", "bar")); Map<String, String> map = new LinkedHashMap<>(); map.put("bar", "baz"); map.put("qux", "foo"); listener.reportingEntryPublished(testIdentifier, ReportEntry.from(map)); listener.executionFinished(testIdentifier, successful()); listener.executionFinished(testPlan.getTestIdentifier(engineDescriptor.getUniqueId()), successful()); var testsuite = readValidXmlFile(tempDirectory.resolve("TEST-engine.xml")); assertThat(String.join("\n", testsuite.child("testcase").children("system-out").texts())) // .containsSubsequence( // "Report Entry #1 (timestamp: " + Year.now(), "- foo: bar\n", "Report Entry #2 (timestamp: " + Year.now(), "- bar: baz\n", "- qux: foo\n"); } private void executeTests(TestEngine engine) { executeTests(engine, Clock.systemDefaultZone()); } private void executeTests(TestEngine engine, Clock clock) { var out = new PrintWriter(new StringWriter()); var reportListener = new LegacyXmlReportGeneratingListener(tempDirectory.toString(), out, clock); var launcher = createLauncher(engine); launcher.registerTestExecutionListeners(reportListener); var request = request() // .configurationParameter(LauncherConstants.STACKTRACE_PRUNING_ENABLED_PROPERTY_NAME, "false") // .selectors(selectUniqueId(UniqueId.forEngine(engine.getId()))) // .forExecution() // .build(); launcher.execute(request); } private Match readValidXmlFile(Path xmlFile) throws Exception { assertTrue(Files.exists(xmlFile), () -> "File does not exist: " + xmlFile); try (var reader = Files.newBufferedReader(xmlFile)) { var xml = $(reader); assertValidAccordingToJenkinsSchema(xml.document()); return xml; } } }
LegacyXmlReportGeneratingListenerTests
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/expressions/CallExpressionResolver.java
{ "start": 1557, "end": 3103 }
class ____ { private final ExpressionResolver resolver; public CallExpressionResolver(RelBuilder relBuilder) { FlinkContext context = unwrapContext(relBuilder.getCluster()); this.resolver = ExpressionResolver.resolverFor( context.getTableConfig(), context.getClassLoader(), name -> Optional.empty(), context.getFunctionCatalog() .asLookup( str -> { throw new TableException( "We should not need to lookup any expressions at this point"); }), context.getCatalogManager().getDataTypeFactory(), (sqlExpression, inputRowType, outputType) -> { throw new TableException( "SQL expression parsing is not supported at this location."); }) .build(); } public ResolvedExpression resolve(Expression expression) { List<ResolvedExpression> resolved = resolver.resolve(Collections.singletonList(expression)); Preconditions.checkArgument(resolved.size() == 1); return resolved.get(0); } }
CallExpressionResolver
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/component/EmbeddableAndGenericExtendingSerializableMappedSuperclassTest.java
{ "start": 1468, "end": 1791 }
class ____ extends MyAbstractEmbeddable { @Column private String text; public MyEmbeddable() { } private MyEmbeddable(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } } @Embeddable public static
MyEmbeddable
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanLogger.java
{ "start": 1526, "end": 7229 }
class ____ { private final Logger logger = LoggerFactory.getLogger(getClass()); public void writePlan(BuildPlan plan) { if (logger.isDebugEnabled()) { writePlan(logger::debug, plan); } } public void writePlan(BuildPlan plan, MavenProject project) { if (logger.isDebugEnabled()) { writePlan(logger::debug, plan, project); } } public void writePlan(Consumer<String> writer, BuildPlan plan) { plan.projects().forEach(project -> writePlan(writer, plan, project)); } public void writePlan(Consumer<String> writer, BuildPlan plan, MavenProject project) { writer.accept("=== PROJECT BUILD PLAN ================================================"); writer.accept("Project: " + getKey(project)); writer.accept("Repositories (dependencies): " + project.getRemoteProjectRepositories()); writer.accept("Repositories (plugins): " + project.getRemotePluginRepositories()); Optional<BuildStep> planStep = plan.step(project, BuildStep.PLAN); if (planStep.isPresent() && planStep.get().status.get() == BuildStep.PLANNING) { writer.accept("Build plan will be lazily computed"); } else { plan.steps(project) .filter(step -> step.phase != null && step.executions().findAny().isPresent()) .sorted(Comparator.comparingInt(plan.sortedNodes()::indexOf)) .forEach(step -> { writer.accept("\t-----------------------------------------------------------------------"); writer.accept("\tPhase: " + step.name); if (!step.predecessors.isEmpty()) { writer.accept("\tPredecessors: " + nonEmptyPredecessors(step) .map(n -> phase(project, n, plan.duplicateIds())) .collect(Collectors.joining(", "))); } step.mojos.values().stream() .flatMap(m -> m.values().stream()) .forEach(mojo -> mojo(writer, mojo)); }); } writer.accept("======================================================================="); } protected Stream<BuildStep> nonEmptyPredecessors(BuildStep step) { HashSet<BuildStep> preds = new HashSet<>(); nonEmptyPredecessors(step, preds, new HashSet<>()); return preds.stream(); } private void nonEmptyPredecessors(BuildStep step, Set<BuildStep> preds, Set<BuildStep> visited) { if (visited.add(step)) { step.predecessors.forEach(ch -> { if (ch.executions().findAny().isPresent()) { preds.add(ch); } else { nonEmptyPredecessors(ch, preds, visited); } }); } } protected String phase(MavenProject currentProject, BuildStep step, Set<String> duplicateIds) { if (step.project == currentProject) { return step.name; } else { String artifactId = step.project.getArtifactId(); if (duplicateIds.contains(artifactId)) { return step.name + "(" + step.project.getGroupId() + ":" + artifactId + ")"; } else { return step.name + "(:" + artifactId + ")"; } } } protected void mojo(Consumer<String> writer, MojoExecution mojoExecution) { String mojoExecId = mojoExecution.getGroupId() + ':' + mojoExecution.getArtifactId() + ':' + mojoExecution.getVersion() + ':' + mojoExecution.getGoal() + " (" + mojoExecution.getExecutionId() + ')'; Map<String, List<MojoExecution>> forkedExecutions = mojoExecution.getForkedExecutions(); if (!forkedExecutions.isEmpty()) { for (Map.Entry<String, List<MojoExecution>> fork : forkedExecutions.entrySet()) { writer.accept("\t--- init fork of " + fork.getKey() + " for " + mojoExecId + " ---"); for (MojoExecution forkedExecution : fork.getValue()) { mojo(writer, forkedExecution); } writer.accept("\t--- exit fork of " + fork.getKey() + " for " + mojoExecId + " ---"); } } writer.accept("\t\t-----------------------------------------------------------------------"); if (mojoExecution.getMojoDescriptor().isAggregator()) { writer.accept("\t\tAggregator goal: " + mojoExecId); } else { writer.accept("\t\tGoal: " + mojoExecId); } if (mojoExecution.getConfiguration() != null) { writer.accept("\t\tConfiguration: " + mojoExecution.getConfiguration()); } if (mojoExecution.getMojoDescriptor().getDependencyCollectionRequired() != null) { writer.accept("\t\tDependencies (collect): " + mojoExecution.getMojoDescriptor().getDependencyCollectionRequired()); } if (mojoExecution.getMojoDescriptor().getDependencyResolutionRequired() != null) { writer.accept("\t\tDependencies (resolve): " + mojoExecution.getMojoDescriptor().getDependencyResolutionRequired()); } } protected String getKey(MavenProject project) { return project.getGroupId() + ':' + project.getArtifactId() + ':' + project.getVersion(); } }
BuildPlanLogger
java
spring-projects__spring-boot
buildSrc/src/test/java/org/springframework/boot/build/architecture/untangled/sub/UntangledTwo.java
{ "start": 707, "end": 803 }
class ____ { public static final String ID = "Two"; private UntangledTwo() { } }
UntangledTwo
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/MapFormatShape5405Test.java
{ "start": 779, "end": 924 }
class ____ extends Map5405Base { } @JsonPropertyOrder({ "a", "b", "c" }) @JsonInclude(JsonInclude.Include.NON_NULL) static
Map5405AsPOJO
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/EagerManyToOneFetchModeJoinWhereTest.java
{ "start": 4238, "end": 4594 }
class ____ { @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name = "containedCategoryId") @Fetch(FetchMode.JOIN) private Category category; public ContainedCategory() { } public ContainedCategory(Category category) { this.category = category; } } }
ContainedCategory
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java
{ "start": 9341, "end": 9521 }
class ____ the bean * @param name an explicit name for the bean * @param qualifiers specific qualifier annotations to consider, if any, * in addition to qualifiers at the bean
of
java
apache__flink
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/test/program/FunctionTestStep.java
{ "start": 1308, "end": 2586 }
enum ____ { SYSTEM, CATALOG } public final FunctionPersistence persistence; public final FunctionBehavior behavior; public final String name; public final Class<? extends UserDefinedFunction> function; FunctionTestStep( FunctionPersistence persistence, FunctionBehavior behavior, String name, Class<? extends UserDefinedFunction> function) { this.persistence = persistence; this.behavior = behavior; this.name = name; this.function = function; } @Override public TestKind getKind() { return TestKind.FUNCTION; } public void apply(TableEnvironment env) { if (behavior == FunctionBehavior.SYSTEM) { if (persistence == FunctionPersistence.TEMPORARY) { env.createTemporarySystemFunction(name, function); } else { throw new UnsupportedOperationException("System functions must be temporary."); } } else { if (persistence == FunctionPersistence.TEMPORARY) { env.createTemporaryFunction(name, function); } else { env.createFunction(name, function); } } } }
FunctionBehavior
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/Meta.java
{ "start": 1160, "end": 1302 }
interface ____ { /** * Add a comment to the query. * * @return empty {@link String} by default. */ String comment() default ""; }
Meta
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/optional_on_mapper_method/Mapper.java
{ "start": 795, "end": 968 }
interface ____ { @Select("select * from users where id = #{id}") Optional<User> getUserUsingAnnotation(Integer id); Optional<User> getUserUsingXml(Integer id); }
Mapper
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/Context.java
{ "start": 2797, "end": 12850 }
interface ____ { /** * Is the current thread a worker thread? * <p> * NOTE! This is not always the same as calling {@link Context#isWorkerContext}. If you are running blocking code * from an event loop context, then this will return true but {@link Context#isWorkerContext} will return false. * * @return true if current thread is a worker thread, false otherwise */ static boolean isOnWorkerThread() { Thread t = Thread.currentThread(); return t instanceof VertxThread && ((VertxThread) t).isWorker(); } /** * Is the current thread an event thread? * <p> * NOTE! This is not always the same as calling {@link Context#isEventLoopContext}. If you are running blocking code * from an event loop context, then this will return false but {@link Context#isEventLoopContext} will return true. * * @return true if current thread is an event thread, false otherwise */ static boolean isOnEventLoopThread() { Thread t = Thread.currentThread(); return t instanceof VertxThread && !((VertxThread) t).isWorker(); } /** * Is the current thread a Vert.x thread? That's either a worker thread or an event loop thread * * @return true if current thread is a Vert.x thread, false otherwise */ static boolean isOnVertxThread() { return Thread.currentThread() instanceof VertxThread; } /** * Run the specified action asynchronously on the same context, some time after the current execution has completed. * * @param action the action to run */ void runOnContext(Handler<Void> action); /** * Safely execute some blocking code. * <p> * Executes the blocking code in the handler {@code blockingCodeHandler} using a thread from the worker pool. * <p> * The returned future will be completed with the result on the original context (i.e. on the original event loop of the caller) * or failed when the handler throws an exception. * <p> * The blocking code should block for a reasonable amount of time (i.e. no more than a few seconds). Long blocking operations * or polling operations (i.e a thread that spin in a loop polling events in a blocking fashion) are precluded. * <p> * When the blocking operation lasts more than the 10 seconds, a message will be printed on the console by the * blocked thread checker. * <p> * Long blocking operations should use a dedicated thread managed by the application, which can interact with * verticles using the event-bus or {@link Context#runOnContext(Handler)} * * @param blockingCodeHandler handler representing the blocking code to run * @param ordered if true then if executeBlocking is called several times on the same context, the executions * for that context will be executed serially, not in parallel. if false then they will be no ordering * guarantees * @param <T> the type of the result * @return a future completed when the blocking code is complete */ @GenIgnore(GenIgnore.PERMITTED_TYPE) <T> Future<@Nullable T> executeBlocking(Callable<T> blockingCodeHandler, boolean ordered); /** * Invoke {@link #executeBlocking(Callable, boolean)} with order = true. * @param blockingCodeHandler handler representing the blocking code to run * @param <T> the type of the result * @return a future completed when the blocking code is complete */ @GenIgnore(GenIgnore.PERMITTED_TYPE) default <T> Future<@Nullable T> executeBlocking(Callable<T> blockingCodeHandler) { return executeBlocking(blockingCodeHandler, true); } /** * If the context is associated with a Verticle deployment, this returns the deployment ID of that deployment. * * @return the deployment ID of the deployment or null if not a Verticle deployment */ String deploymentID(); /** * If the context is associated with a Verticle deployment, this returns the configuration that was specified when * the verticle was deployed. * * @return the configuration of the deployment or null if not a Verticle deployment */ @Nullable JsonObject config(); /** * @return an empty list * @deprecated As of version 5, Vert.x is no longer tightly coupled to the CLI */ @Deprecated default List<String> processArgs() { return Collections.emptyList(); } /** * Is the current context an event loop context? * <p> * NOTE! when running blocking code using {@link io.vertx.core.Vertx#executeBlocking(Callable)} from a * standard (not worker) verticle, the context will still an event loop context and this {@link #isEventLoopContext()} * will return true. * * @return {@code true} if the current context is an event-loop context, {@code false} otherwise */ boolean isEventLoopContext(); /** * Is the current context a worker context? * <p> * NOTE! when running blocking code using {@link io.vertx.core.Vertx#executeBlocking(Callable)} from a * standard (not worker) verticle, the context will still an event loop context and this {@link this#isWorkerContext()} * will return false. * * @return {@code true} if the current context is a worker context, {@code false} otherwise */ boolean isWorkerContext(); /** * @return the context threading model */ ThreadingModel threadingModel(); /** * Get some data from the context. * * @param key the key of the data * @param <T> the type of the data * @return the data */ <T> T get(Object key); /** * Put some data in the context. * <p> * This can be used to share data between different handlers that share a context * * @param key the key of the data * @param value the data */ void put(Object key, Object value); /** * Remove some data from the context. * * @param key the key to remove * @return true if removed successfully, false otherwise */ boolean remove(Object key); /** * @return The Vertx instance that created the context */ Vertx owner(); /** * @return the number of instances of the verticle that were deployed in the deployment (if any) related * to this context */ int getInstanceCount(); /** * Set an exception handler called when the context runs an action throwing an uncaught throwable.<p/> * * When this handler is called, {@link Vertx#currentContext()} will return this context. * * @param handler the exception handler * @return a reference to this, so the API can be used fluently */ @Fluent Context exceptionHandler(@Nullable Handler<Throwable> handler); /** * @return the current exception handler of this context */ @GenIgnore @Nullable Handler<Throwable> exceptionHandler(); /** * Get local data associated with {@code key} using the concurrent access mode. * * @param key the key of the data * @param <T> the type of the data * @return the local data */ @GenIgnore(GenIgnore.PERMITTED_TYPE) default <T> T getLocal(ContextLocal<T> key) { return getLocal(key, AccessMode.CONCURRENT); } /** * <p>Get local data associated with {@code key} using the concurrent access mode.</p> * * <p>When it does not exist the {@code initialValueSupplier} is called to obtain the initial value.</p> * * <p> The {@code initialValueSupplier} might be called multiple times when multiple threads call this method concurrently. * * @param key the key of the data * @param initialValueSupplier the supplier of the initial value optionally called * @param <T> the type of the data * @return the local data */ @GenIgnore default <T> T getLocal(ContextLocal<T> key, Supplier<? extends T> initialValueSupplier) { return getLocal(key, AccessMode.CONCURRENT, initialValueSupplier); } /** * <p>Associate local data with {@code key} using the concurrent access mode.</p> * * @param key the key of the data * @param value the data */ @GenIgnore(GenIgnore.PERMITTED_TYPE) default <T> void putLocal(ContextLocal<T> key, T value) { putLocal(key, AccessMode.CONCURRENT, value); } /** * <p>Remove local data associated with {@code key} using the concurrent access mode.</p> * * @param key the key to be removed */ @GenIgnore(GenIgnore.PERMITTED_TYPE) default <T> void removeLocal(ContextLocal<T> key) { putLocal(key, null); } /** * <p>Get local data associated with {@code key} using the specified access mode.</p> * * @param key the key of the data * @param accessMode the access mode * @param <T> the type of the data * @return the local data */ @GenIgnore(GenIgnore.PERMITTED_TYPE) <T> T getLocal(ContextLocal<T> key, AccessMode accessMode); /** * <p>Get local data associated with {@code key} using the specified access mode.</p> * * <p>When it does not exist the {@code initialValueSupplier} is called to obtain the initial value.</p> * * <p> The {@code initialValueSupplier} might be called multiple times when multiple threads call this method concurrently. * * @param key the key of the data * @param initialValueSupplier the supplier of the initial value optionally called * @param <T> the type of the data * @return the local data */ @GenIgnore <T> T getLocal(ContextLocal<T> key, AccessMode accessMode, Supplier<? extends T> initialValueSupplier); /** * <p>Associate local data with {@code key} using the specified access mode.</p> * * @param key the key of the data * @param accessMode the access mode * @param value the data */ @GenIgnore(GenIgnore.PERMITTED_TYPE) <T> void putLocal(ContextLocal<T> key, AccessMode accessMode, T value); /** * <p>Remove local data associated with {@code key} using the specified access mode.</p> * * @param key the key to be removed * @param accessMode the access mode */ @GenIgnore(GenIgnore.PERMITTED_TYPE) default <T> void removeLocal(ContextLocal<T> key, AccessMode accessMode) { putLocal(key, accessMode, null); } }
Context
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java
{ "start": 24348, "end": 26065 }
class ____ { * int number; * String street; * } * * Person sherlock = new Person("Sherlock", 1.80); * sherlock.home.address.street = "Baker Street"; * sherlock.home.address.number = 221; * * Person moriarty = new Person("Moriarty", 1.80); * moriarty.home.address.street = "Butcher Street"; * moriarty.home.address.number = 221; * * * // assertion succeeds as it only compared fields height and home.address.number since their types match compared types * assertThat(sherlock).usingRecursiveComparison() * .comparingOnlyFieldsOfTypes(Integer.class, Double.class) * .isEqualTo(moriarty); * * // assertion fails as home.address.street fields differ (Home fields and its subfields were compared) * assertThat(sherlock).usingRecursiveComparison() * .comparingOnlyFieldsOfTypes(Home.class) * .isEqualTo(moriarty);</code></pre> * <p> * Note that the recursive comparison checks whether the fields actually exist and throws an {@link IllegalArgumentException} if some of them don't, * this is done to catch typos. * * @param typesToCompare the types to compare in the recursive comparison. * @return this {@link RecursiveComparisonAssert} to chain other methods. */ public SELF comparingOnlyFieldsOfTypes(Class<?>... typesToCompare) { recursiveComparisonConfiguration.compareOnlyFieldsOfTypes(typesToCompare); return myself; } /** * Makes the recursive comparison to ignore all <b>actual null fields</b> (but note that the expected object null fields are used in the comparison). * <p> * Example: * <pre><code class='java'>
Address
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedWindowStoreBuilderTest.java
{ "start": 2126, "end": 10894 }
class ____ { private static final String TIMESTAMP_STORE_NAME = "Timestamped Store"; private static final String TIMEORDERED_STORE_NAME = "TimeOrdered Store"; private static final String STORE_NAME = "name"; private static final String METRICS_SCOPE = "metricsScope"; @Mock private WindowBytesStoreSupplier supplier; @Mock private RocksDBTimestampedWindowStore timestampedStore; @Mock private RocksDBTimeOrderedWindowStore timeOrderedStore; private TimestampedWindowStoreBuilder<String, String> builder; private boolean isTimeOrderedStore; private WindowStore inner; public void setUpWithoutInner(final String storeName) { isTimeOrderedStore = TIMEORDERED_STORE_NAME.equals(storeName); when(supplier.name()).thenReturn(STORE_NAME); when(supplier.metricsScope()).thenReturn(METRICS_SCOPE); builder = new TimestampedWindowStoreBuilder<>( supplier, Serdes.String(), Serdes.String(), new MockTime()); } @SuppressWarnings("unchecked") public void setUp(final String storeName) { isTimeOrderedStore = TIMEORDERED_STORE_NAME.equals(storeName); inner = isTimeOrderedStore ? timeOrderedStore : timestampedStore; when(supplier.get()).thenReturn(inner); setUpWithoutInner(storeName); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldHaveMeteredStoreAsOuterStore(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder.build(); assertThat(store, instanceOf(MeteredTimestampedWindowStore.class)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldHaveChangeLoggingStoreByDefault(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder.build(); final StateStore next = ((WrappedStateStore) store).wrapped(); assertThat(next, instanceOf(ChangeLoggingTimestampedWindowBytesStore.class)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldNotHaveChangeLoggingStoreWhenDisabled(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder.withLoggingDisabled().build(); final StateStore next = ((WrappedStateStore) store).wrapped(); assertThat(next, CoreMatchers.equalTo(inner)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldHaveCachingStoreWhenEnabled(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder.withCachingEnabled().build(); final StateStore wrapped = ((WrappedStateStore) store).wrapped(); assertThat(store, instanceOf(MeteredTimestampedWindowStore.class)); if (isTimeOrderedStore) { assertThat(wrapped, instanceOf(TimeOrderedCachingWindowStore.class)); } else { assertThat(wrapped, instanceOf(CachingWindowStore.class)); } } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldHaveChangeLoggingStoreWhenLoggingEnabled(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder .withLoggingEnabled(Collections.emptyMap()) .build(); final StateStore wrapped = ((WrappedStateStore) store).wrapped(); assertThat(store, instanceOf(MeteredTimestampedWindowStore.class)); assertThat(wrapped, instanceOf(ChangeLoggingTimestampedWindowBytesStore.class)); assertThat(((WrappedStateStore) wrapped).wrapped(), CoreMatchers.equalTo(inner)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldHaveCachingAndChangeLoggingWhenBothEnabled(final String storeName) { setUp(storeName); final TimestampedWindowStore<String, String> store = builder .withLoggingEnabled(Collections.emptyMap()) .withCachingEnabled() .build(); final WrappedStateStore caching = (WrappedStateStore) ((WrappedStateStore) store).wrapped(); final WrappedStateStore changeLogging = (WrappedStateStore) caching.wrapped(); assertThat(store, instanceOf(MeteredTimestampedWindowStore.class)); if (isTimeOrderedStore) { assertThat(caching, instanceOf(TimeOrderedCachingWindowStore.class)); } else { assertThat(caching, instanceOf(CachingWindowStore.class)); } assertThat(changeLogging, instanceOf(ChangeLoggingTimestampedWindowBytesStore.class)); assertThat(changeLogging.wrapped(), CoreMatchers.equalTo(inner)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldNotWrapTimestampedByteStore(final String storeName) { setUp(storeName); when(supplier.get()).thenReturn(new RocksDBTimestampedWindowStore( new RocksDBTimestampedSegmentedBytesStore( "name", "metric-scope", 10L, 5L, new WindowKeySchema()), false, 1L)); final TimestampedWindowStore<String, String> store = builder .withLoggingDisabled() .withCachingDisabled() .build(); assertThat(((WrappedStateStore) store).wrapped(), instanceOf(RocksDBTimestampedWindowStore.class)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldWrapPlainKeyValueStoreAsTimestampStore(final String storeName) { setUp(storeName); when(supplier.get()).thenReturn(new RocksDBWindowStore( new RocksDBSegmentedBytesStore( "name", "metric-scope", 10L, 5L, new WindowKeySchema()), false, 1L)); final TimestampedWindowStore<String, String> store = builder .withLoggingDisabled() .withCachingDisabled() .build(); assertThat(((WrappedStateStore) store).wrapped(), instanceOf(WindowToTimestampedWindowByteStoreAdapter.class)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @SuppressWarnings("unchecked") @ParameterizedTest public void shouldDisableCachingWithRetainDuplicates(final String storeName) { setUpWithoutInner(storeName); supplier = Stores.persistentTimestampedWindowStore("name", Duration.ofMillis(10L), Duration.ofMillis(10L), true); final StoreBuilder<TimestampedWindowStore<String, String>> builder = new TimestampedWindowStoreBuilder<>( supplier, Serdes.String(), Serdes.String(), new MockTime() ).withCachingEnabled(); builder.build(); assertFalse(((AbstractStoreBuilder<String, String, TimestampedWindowStore<String, String>>) builder).enableCaching); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @SuppressWarnings("all") @ParameterizedTest public void shouldThrowNullPointerIfInnerIsNull(final String storeName) { setUpWithoutInner(storeName); assertThrows(NullPointerException.class, () -> new TimestampedWindowStoreBuilder<>(null, Serdes.String(), Serdes.String(), new MockTime())); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldThrowNullPointerIfTimeIsNull(final String storeName) { setUpWithoutInner(storeName); assertThrows(NullPointerException.class, () -> new TimestampedWindowStoreBuilder<>(supplier, Serdes.String(), Serdes.String(), null)); } @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME}) @ParameterizedTest public void shouldThrowNullPointerIfMetricsScopeIsNull(final String storeName) { setUpWithoutInner(storeName); when(supplier.metricsScope()).thenReturn(null); final Exception e = assertThrows(NullPointerException.class, () -> new TimestampedWindowStoreBuilder<>(supplier, Serdes.String(), Serdes.String(), new MockTime())); assertEquals("storeSupplier's metricsScope can't be null", e.getMessage()); } }
TimestampedWindowStoreBuilderTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/TransactionalConcurrencyCollectionCacheEvictionTest.java
{ "start": 4541, "end": 5543 }
class ____ { @Id @Access(value = AccessType.PROPERTY) @Column(name = "PERSONID", nullable = false) private Long id; @Column(name = "NAME") private String name; @OneToMany(fetch = FetchType.LAZY, mappedBy = "person") @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) private final Set<Phone> phones = new HashSet<>(); public Person() { } public Person(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Set<Phone> getPhones() { return phones; } public Phone addPhone(String number) { Phone phone = new Phone( number, this ); getPhones().add( phone ); return phone; } } @Entity(name = "Phone") @Table(name = "PHONE") @Cacheable @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) public static
Person
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timeline/TimelineEntityGroupId.java
{ "start": 1502, "end": 5042 }
class ____ implements Comparable<TimelineEntityGroupId> { private static final Splitter SPLITTER = Splitter.on('_').trimResults(); private ApplicationId applicationId; private String id; @Private @Unstable public static final String TIMELINE_ENTITY_GROUPID_STR_PREFIX = "timelineEntityGroupId"; public TimelineEntityGroupId() { } public static TimelineEntityGroupId newInstance(ApplicationId applicationId, String id) { TimelineEntityGroupId timelineEntityGroupId = new TimelineEntityGroupId(); timelineEntityGroupId.setApplicationId(applicationId); timelineEntityGroupId.setTimelineEntityGroupId(id); return timelineEntityGroupId; } /** * Get the <code>ApplicationId</code> of the * <code>TimelineEntityGroupId</code>. * * @return <code>ApplicationId</code> of the * <code>TimelineEntityGroupId</code> */ public ApplicationId getApplicationId() { return this.applicationId; } public void setApplicationId(ApplicationId appID) { this.applicationId = appID; } /** * Get the <code>timelineEntityGroupId</code>. * * @return <code>timelineEntityGroupId</code> */ public String getTimelineEntityGroupId() { return this.id; } @Private @Unstable protected void setTimelineEntityGroupId(String timelineEntityGroupId) { this.id = timelineEntityGroupId; } @Override public int hashCode() { int result = getTimelineEntityGroupId().hashCode(); result = 31 * result + getApplicationId().hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TimelineEntityGroupId otherObject = (TimelineEntityGroupId) obj; if (!this.getApplicationId().equals(otherObject.getApplicationId())) { return false; } if (!this.getTimelineEntityGroupId().equals( otherObject.getTimelineEntityGroupId())) { return false; } return true; } @Override public int compareTo(TimelineEntityGroupId other) { int compareAppIds = this.getApplicationId().compareTo(other.getApplicationId()); if (compareAppIds == 0) { return this.getTimelineEntityGroupId().compareTo( other.getTimelineEntityGroupId()); } else { return compareAppIds; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(TIMELINE_ENTITY_GROUPID_STR_PREFIX + "_"); ApplicationId appId = getApplicationId(); sb.append(appId.getClusterTimestamp()).append("_") .append(appId.getId()).append("_") .append(getTimelineEntityGroupId()); return sb.toString(); } public static TimelineEntityGroupId fromString(String timelineEntityGroupIdStr) { StringBuilder buf = new StringBuilder(); Iterator<String> it = SPLITTER.split(timelineEntityGroupIdStr).iterator(); if (!it.next().equals(TIMELINE_ENTITY_GROUPID_STR_PREFIX)) { throw new IllegalArgumentException( "Invalid TimelineEntityGroupId prefix: " + timelineEntityGroupIdStr); } ApplicationId appId = ApplicationId.newInstance(Long.parseLong(it.next()), Integer.parseInt(it.next())); buf.append(it.next()); while (it.hasNext()) { buf.append("_"); buf.append(it.next()); } return TimelineEntityGroupId.newInstance(appId, buf.toString()); } }
TimelineEntityGroupId
java
apache__thrift
lib/javame/src/org/apache/thrift/TApplicationException.java
{ "start": 1103, "end": 3646 }
class ____ extends TException { private static final long serialVersionUID = 1L; public static final int UNKNOWN = 0; public static final int UNKNOWN_METHOD = 1; public static final int INVALID_MESSAGE_TYPE = 2; public static final int WRONG_METHOD_NAME = 3; public static final int BAD_SEQUENCE_ID = 4; public static final int MISSING_RESULT = 5; public static final int INTERNAL_ERROR = 6; public static final int PROTOCOL_ERROR = 7; public static final int INVALID_TRANSFORM = 8; public static final int INVALID_PROTOCOL = 9; public static final int UNSUPPORTED_CLIENT_TYPE = 10; protected int type_ = UNKNOWN; public TApplicationException() { super(); } public TApplicationException(int type) { super(); type_ = type; } public TApplicationException(int type, String message) { super(message); type_ = type; } public TApplicationException(String message) { super(message); } public int getType() { return type_; } public static TApplicationException read(TProtocol iprot) throws TException { TField field; iprot.readStructBegin(); String message = null; int type = UNKNOWN; while (true) { field = iprot.readFieldBegin(); if (field.type == TType.STOP) { break; } switch (field.id) { case 1: if (field.type == TType.STRING) { message = iprot.readString(); } else { TProtocolUtil.skip(iprot, field.type); } break; case 2: if (field.type == TType.I32) { type = iprot.readI32(); } else { TProtocolUtil.skip(iprot, field.type); } break; default: TProtocolUtil.skip(iprot, field.type); break; } iprot.readFieldEnd(); } iprot.readStructEnd(); return new TApplicationException(type, message); } public void write(TProtocol oprot) throws TException { TStruct struct = new TStruct("TApplicationException"); TField field = new TField(); oprot.writeStructBegin(struct); if (getMessage() != null) { field.name = "message"; field.type = TType.STRING; field.id = 1; oprot.writeFieldBegin(field); oprot.writeString(getMessage()); oprot.writeFieldEnd(); } field.name = "type"; field.type = TType.I32; field.id = 2; oprot.writeFieldBegin(field); oprot.writeI32(type_); oprot.writeFieldEnd(); oprot.writeFieldStop(); oprot.writeStructEnd(); } }
TApplicationException
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/jpa/AbstractJpaSelection.java
{ "start": 528, "end": 1123 }
class ____<T> extends AbstractJpaTupleElement<T> implements SqmSelectableNode<T>, JpaSelection<T> { protected AbstractJpaSelection(@Nullable SqmBindableType<? super T> sqmExpressible, NodeBuilder criteriaBuilder) { super( sqmExpressible, criteriaBuilder ); } @Override public JpaSelection<T> alias(String alias) { setAlias( alias ); return this; } @Override public boolean isCompoundSelection() { return false; } @Override public List<? extends JpaSelection<?>> getSelectionItems() { throw new IllegalStateException( "Not a compound selection" ); } }
AbstractJpaSelection
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/resolve/ResolveTest_0.java
{ "start": 5014, "end": 6133 }
class ____ extends SQLASTVisitorAdapter { public boolean visit(SQLExprTableSource x) { if (x.getSchemaObject() != null) { x.setCatalog("c1", "s1"); } return false; } public boolean visit(SQLPropertyExpr x) { SQLExprTableSource tableSource = (SQLExprTableSource) x.getResolvedTableSource(); if (tableSource.getSchemaObject() == null) { return false; } SQLExpr owner = x.getOwner(); if (owner instanceof SQLIdentifierExpr) { x.setOwner( new SQLPropertyExpr("c1", "s1", ((SQLIdentifierExpr) owner).getName()) ); } else if (owner instanceof SQLPropertyExpr) { SQLPropertyExpr owner2 = (SQLPropertyExpr) owner; if (owner2.getOwner() instanceof SQLIdentifierExpr) { owner2.setOwner(new SQLPropertyExpr("c1", ((SQLIdentifierExpr) owner2.getOwner()).getName())); } } return false; } } }
SetCatalogVisitor
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/specific/SpecificData.java
{ "start": 14372, "end": 14953 }
class ____ implements a schema, or null if none exists. */ public Class getClass(Schema schema) { switch (schema.getType()) { case FIXED: case RECORD: case ENUM: String name = schema.getFullName(); if (name == null) return null; Class<?> c = classCache.computeIfAbsent(name, n -> { try { return ClassUtils.forName(getClassLoader(), getClassName(schema)); } catch (ClassNotFoundException e) { // This might be a nested namespace. Try using the last tokens in the // namespace as an enclosing
that
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java
{ "start": 48723, "end": 49297 }
class ____ implements TempDirFactory { @Nullable private static FileSystem fileSystem; @Override public Path createTempDirectory(AnnotatedElementContext elementContext, ExtensionContext extensionContext) throws Exception { fileSystem = Jimfs.newFileSystem(Configuration.unix()); return Files.createTempDirectory(fileSystem.getPath("/"), "prefix"); } @Override public void close() throws IOException { requireNonNull(fileSystem).close(); fileSystem = null; } } } @SuppressWarnings("JUnitMalformedDeclaration") static
Factory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/procedure/Helper.java
{ "start": 428, "end": 990 }
interface ____ { void accept(Statement statement) throws SQLException; } public static void withStatement(SessionFactoryImplementor sessionFactory, StatementAction action) throws SQLException { TransactionUtil.doWithJDBC( sessionFactory.getServiceRegistry(), connection -> { withStatement( connection, action ); } ); } public static void withStatement(Connection connection, StatementAction action) throws SQLException { try (Statement statement = connection.createStatement()) { action.accept( statement ); } } }
StatementAction
java
apache__camel
components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpClientProducerRequiredEndOfDataWithValidationTest.java
{ "start": 956, "end": 2836 }
class ____ extends TcpClientProducerEndOfDataAndValidationTestSupport { @Override boolean requireEndOfData() { return true; } @Override boolean validatePayload() { return false; } @Override @Test public void testSendSingleMessageWithoutEndOfData() { expectedTimeoutCount = 1; assertDoesNotThrow(() -> runSendSingleMessageWithoutEndOfData()); } @Override @Test public void testSendMultipleMessagesWithoutEndOfDataByte() { assertDoesNotThrow(() -> runSendMultipleMessagesWithoutEndOfDataByte(ackTimeoutError)); } @Override @Test public void testEmptyAcknowledgement() { assertDoesNotThrow(() -> runEmptyAcknowledgement(aa)); } @Override @Test public void testInvalidAcknowledgement() { assertDoesNotThrow(() -> runInvalidAcknowledgement(aa)); } @Override @Test public void testMissingEndOfDataByte() { expectedAACount = 2; expectedTimeoutCount = 1; assertDoesNotThrow(() -> runMissingEndOfDataByte()); } @Override @Test public void testInvalidAcknowledgementContainingEmbeddedStartOfBlock() { expectedAACount = 1; assertDoesNotThrow(() -> runInvalidAcknowledgementContainingEmbeddedEndOfBlockByte()); } @Override @Test public void testInvalidAcknowledgementContainingEmbeddedEndOfBlockByte() { expectedTimeoutCount = 1; assertDoesNotThrow(() -> runInvalidAcknowledgementContainingEmbeddedEndOfBlockByte()); } @Override @Test public void testSendMultipleMessagesWithoutSomeEndOfDataByte() { expectedAACount = 2; expectedTimeoutCount = 1; assertDoesNotThrow(() -> runSendMultipleMessagesWithoutSomeEndOfDataByte()); } }
MllpTcpClientProducerRequiredEndOfDataWithValidationTest
java
elastic__elasticsearch
x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/generative/GenerativeRestTest.java
{ "start": 1995, "end": 13759 }
class ____ extends ESRestTestCase implements QueryExecutor { @Rule(order = Integer.MIN_VALUE) public ProfileLogger profileLogger = new ProfileLogger(); public static final int ITERATIONS = 100; public static final int MAX_DEPTH = 20; public static final Set<String> ALLOWED_ERRORS = Set.of( "Reference \\[.*\\] is ambiguous", "Cannot use field \\[.*\\] due to ambiguities", "cannot sort on .*", "argument of \\[count.*\\] must", "Cannot use field \\[.*\\] with unsupported type \\[.*\\]", "Unbounded SORT not supported yet", "The field names are too complex to process", // field_caps problem "must be \\[any type except counter types\\]", // TODO refine the generation of count() "INLINE STATS cannot be used after an explicit or implicit LIMIT command", "sub-plan execution results too large", // INLINE STATS limitations // Awaiting fixes for query failure "Unknown column \\[<all-fields-projected>\\]", // https://github.com/elastic/elasticsearch/issues/121741, // https://github.com/elastic/elasticsearch/issues/125866 "Plan \\[ProjectExec\\[\\[<no-fields>.* optimized incorrectly due to missing references", "The incoming YAML document exceeds the limit:", // still to investigate, but it seems to be specific to the test framework "Data too large", // Circuit breaker exceptions eg. https://github.com/elastic/elasticsearch/issues/130072 "long overflow", // https://github.com/elastic/elasticsearch/issues/135759 "cannot be cast to class", // https://github.com/elastic/elasticsearch/issues/133992 "can't find input for", // https://github.com/elastic/elasticsearch/issues/136596 "unexpected byte", // https://github.com/elastic/elasticsearch/issues/136598 "out of bounds for length", // https://github.com/elastic/elasticsearch/issues/136851 "optimized incorrectly due to missing references", // https://github.com/elastic/elasticsearch/issues/138231 "Potential cycle detected", // https://github.com/elastic/elasticsearch/issues/138346 // Awaiting fixes for correctness "Expecting at most \\[.*\\] columns, got \\[.*\\]", // https://github.com/elastic/elasticsearch/issues/129561 // TS-command tests "time-series.*the first aggregation.*is not allowed", "count_star .* can't be used with TS command", "time_series aggregate.* can only be used with the TS command", "implicit time-series aggregation function .* doesn't support type .*", "INLINE STATS .* can only be used after STATS when used with TS command", "cannot group by a metric field .* in a time-series aggregation", "a @timestamp field of type date or date_nanos to be present when run with the TS command, but it was not present", "Output has changed from \\[.*\\] to \\[.*\\]" // https://github.com/elastic/elasticsearch/issues/134794 ); public static final Set<Pattern> ALLOWED_ERROR_PATTERNS = ALLOWED_ERRORS.stream() .map(x -> ".*" + x + ".*") .map(x -> Pattern.compile(x, Pattern.DOTALL)) .collect(Collectors.toSet()); @Before public void setup() throws IOException { if (indexExists(CSV_DATASET_MAP.keySet().iterator().next()) == false) { loadDataSetIntoEs(client(), true, supportsSourceFieldMapping(), false); } } protected abstract boolean supportsSourceFieldMapping(); protected boolean requiresTimeSeries() { return false; } @AfterClass public static void wipeTestData() throws IOException { try { adminClient().performRequest(new Request("DELETE", "/*")); } catch (ResponseException e) { // 404 here just means we had no indexes if (e.getResponse().getStatusLine().getStatusCode() != 404) { throw e; } } } public void test() throws IOException { List<String> indices = availableIndices(); List<LookupIdx> lookupIndices = lookupIndices(); List<CsvTestsDataLoader.EnrichConfig> policies = availableEnrichPolicies(); CommandGenerator.QuerySchema mappingInfo = new CommandGenerator.QuerySchema(indices, lookupIndices, policies); for (int i = 0; i < ITERATIONS; i++) { var exec = new EsqlQueryGenerator.Executor() { @Override public void run(CommandGenerator generator, CommandGenerator.CommandDescription current) { previousCommands.add(current); final String command = current.commandString(); final QueryExecuted result = previousResult == null ? execute(command, 0) : execute(previousResult.query() + command, previousResult.depth()); previousResult = result; final boolean hasException = result.exception() != null; if (hasException || checkResults(List.of(), generator, current, previousResult, result).success() == false) { if (hasException) { checkException(result); } continueExecuting = false; currentSchema = List.of(); } else { continueExecuting = true; currentSchema = result.outputSchema(); } } @Override public List<CommandGenerator.CommandDescription> previousCommands() { return previousCommands; } @Override public boolean continueExecuting() { return continueExecuting; } @Override public List<Column> currentSchema() { return currentSchema; } boolean continueExecuting; List<Column> currentSchema; final List<CommandGenerator.CommandDescription> previousCommands = new ArrayList<>(); QueryExecuted previousResult; }; EsqlQueryGenerator.generatePipeline(MAX_DEPTH, sourceCommand(), mappingInfo, exec, requiresTimeSeries(), this); } } protected CommandGenerator sourceCommand() { return EsqlQueryGenerator.sourceCommand(); } private static CommandGenerator.ValidationResult checkResults( List<CommandGenerator.CommandDescription> previousCommands, CommandGenerator commandGenerator, CommandGenerator.CommandDescription commandDescription, QueryExecuted previousResult, QueryExecuted result ) { CommandGenerator.ValidationResult outputValidation = commandGenerator.validateOutput( previousCommands, commandDescription, previousResult == null ? null : previousResult.outputSchema(), previousResult == null ? null : previousResult.result(), result.outputSchema(), result.result() ); if (outputValidation.success() == false) { for (Pattern allowedError : ALLOWED_ERROR_PATTERNS) { if (isAllowedError(outputValidation.errorMessage(), allowedError)) { return outputValidation; } } fail("query: " + result.query() + "\nerror: " + outputValidation.errorMessage()); } return outputValidation; } private void checkException(QueryExecuted query) { for (Pattern allowedError : ALLOWED_ERROR_PATTERNS) { if (isAllowedError(query.exception().getMessage(), allowedError)) { return; } } fail("query: " + query.query() + "\nexception: " + query.exception().getMessage()); } /** * Long lines in exceptions can be split across several lines. When a newline is inserted, the end of the current line and the beginning * of the new line are marked with a backslash {@code \}; the new line will also have whitespace before the backslash for aligning. */ private static final Pattern ERROR_MESSAGE_LINE_BREAK = Pattern.compile("\\\\\n\\s*\\\\"); private static boolean isAllowedError(String errorMessage, Pattern allowedPattern) { String errorWithoutLineBreaks = ERROR_MESSAGE_LINE_BREAK.matcher(errorMessage).replaceAll(""); return allowedPattern.matcher(errorWithoutLineBreaks).matches(); } @Override @SuppressWarnings("unchecked") public QueryExecuted execute(String query, int depth) { try { Map<String, Object> json = RestEsqlTestCase.runEsql( new RestEsqlTestCase.RequestObjectBuilder().query(query).build(), new AssertWarnings.AllowedRegexes(List.of(Pattern.compile(".*"))),// we don't care about warnings profileLogger, RestEsqlTestCase.Mode.SYNC ); List<Column> outputSchema = outputSchema(json); List<List<Object>> values = (List<List<Object>>) json.get("values"); return new QueryExecuted(query, depth, outputSchema, values, null); } catch (Exception e) { return new QueryExecuted(query, depth, null, null, e); } catch (AssertionError ae) { // this is for ensureNoWarnings() return new QueryExecuted(query, depth, null, null, new RuntimeException(ae.getMessage())); } } @SuppressWarnings("unchecked") private static List<Column> outputSchema(Map<String, Object> a) { List<Map<String, ?>> cols = (List<Map<String, ?>>) a.get("columns"); if (cols == null) { return null; } return cols.stream() .map(x -> new Column((String) x.get(COLUMN_NAME), (String) x.get(COLUMN_TYPE), originalTypes(x))) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") private static List<String> originalTypes(Map<String, ?> x) { List<String> originalTypes = (List<String>) x.get(COLUMN_ORIGINAL_TYPES); if (originalTypes == null) { return List.of(); } return originalTypes; } private List<String> availableIndices() throws IOException { return availableDatasetsForEs(true, supportsSourceFieldMapping(), false, requiresTimeSeries(), false).stream() .filter(x -> x.requiresInferenceEndpoint() == false) .map(x -> x.indexName()) .toList(); } private List<LookupIdx> lookupIndices() { List<LookupIdx> result = new ArrayList<>(); // we don't have key info from the dataset loader, let's hardcode it for now result.add(new LookupIdx("languages_lookup", List.of(new LookupIdxColumn("language_code", "integer")))); result.add(new LookupIdx("message_types_lookup", List.of(new LookupIdxColumn("message", "keyword")))); List<LookupIdxColumn> multiColumnJoinableLookupKeys = List.of( new LookupIdxColumn("id_int", "integer"), new LookupIdxColumn("name_str", "keyword"), new LookupIdxColumn("is_active_bool", "boolean"), new LookupIdxColumn("ip_addr", "ip"), new LookupIdxColumn("other1", "keyword"), new LookupIdxColumn("other2", "integer") ); result.add(new LookupIdx("multi_column_joinable_lookup", multiColumnJoinableLookupKeys)); return result; } List<CsvTestsDataLoader.EnrichConfig> availableEnrichPolicies() { return ENRICH_POLICIES; } }
GenerativeRestTest
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FilterAutoConfiguration.java
{ "start": 1708, "end": 2121 }
class ____ { @Bean public FilterBeanFactoryDiscoverer filterBeanFactoryDiscoverer(BeanFactory beanFactory) { return new FilterBeanFactoryDiscoverer(beanFactory); } @Bean public FilterFunctions.FilterSupplier filterFunctionsSupplier() { return new FilterFunctions.FilterSupplier(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(BucketConfiguration.class) static
FilterAutoConfiguration
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/main/java/org/apache/hadoop/mapred/YARNRunner.java
{ "start": 4998, "end": 6312 }
class ____ implements ClientProtocol { private static final Logger LOG = LoggerFactory.getLogger(YARNRunner.class); private static final String RACK_GROUP = "rack"; private static final String NODE_IF_RACK_GROUP = "node1"; private static final String NODE_IF_NO_RACK_GROUP = "node2"; /** * Matches any of the following patterns with capturing groups: * <ul> * <li>/rack</li> * <li>/rack/node</li> * <li>node (assumes /default-rack)</li> * </ul> * The groups can be retrieved using the RACK_GROUP, NODE_IF_RACK_GROUP, * and/or NODE_IF_NO_RACK_GROUP group keys. */ private static final Pattern RACK_NODE_PATTERN = Pattern.compile( String.format("(?<%s>[^/]+?)|(?<%s>/[^/]+?)(?:/(?<%s>[^/]+?))?", NODE_IF_NO_RACK_GROUP, RACK_GROUP, NODE_IF_RACK_GROUP)); private final static RecordFactory recordFactory = RecordFactoryProvider .getRecordFactory(null); public final static Priority AM_CONTAINER_PRIORITY = recordFactory .newRecordInstance(Priority.class); static { AM_CONTAINER_PRIORITY.setPriority(0); } private ResourceMgrDelegate resMgrDelegate; private ClientCache clientCache; private Configuration conf; private final FileContext defaultFileContext; /** * Yarn runner incapsulates the client
YARNRunner
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/IdentifierGeneratorDefinition.java
{ "start": 1560, "end": 5048 }
class ____ implements Serializable { private final String name; private final String strategy; private final Map<String, String> parameters; public IdentifierGeneratorDefinition( final String name, final String strategy, final Map<String, String> parameters) { this.name = name; this.strategy = strategy; this.parameters = isEmpty( parameters ) ? emptyMap() : unmodifiableMap( parameters ); } public IdentifierGeneratorDefinition( final String name, final Map<String, String> parameters) { this( name, name, parameters ); } public IdentifierGeneratorDefinition(String name) { this( name, name ); } public IdentifierGeneratorDefinition(String name, String strategy) { this.name = name; this.strategy = strategy; this.parameters = emptyMap(); } /** * @return identifier generator strategy */ public String getStrategy() { return strategy; } /** * @return generator name */ public String getName() { return name; } /** * @return generator configuration parameters */ public Map<String, String> getParameters() { return parameters; } @Internal public static IdentifierGeneratorDefinition createImplicit( String name, TypeDetails idType, String generatorName, GenerationType generationType) { // If we were unable to locate an actual matching named generator assume // a sequence/table of the given name, make one based on GenerationType. return switch ( generationType == null ? GenerationType.SEQUENCE : generationType ) { case SEQUENCE -> buildSequenceGeneratorDefinition( name ); case TABLE -> buildTableGeneratorDefinition( name ); case AUTO -> new IdentifierGeneratorDefinition( name, generatorStrategy( generationType, generatorName, idType ), singletonMap( IdentifierGenerator.GENERATOR_NAME, name ) ); case IDENTITY, UUID -> throw new AnnotationException( "@GeneratedValue annotation specified 'strategy=" + generationType + "' and 'generator' but the generator name is unnecessary" ); }; } private static IdentifierGeneratorDefinition buildTableGeneratorDefinition(String name) { final TableGeneratorJpaAnnotation tableGeneratorUsage = TABLE_GENERATOR.createUsage( null ); if ( isNotEmpty( name ) ) { tableGeneratorUsage.name( name ); } final Builder builder = new Builder(); interpretTableGenerator( tableGeneratorUsage, builder ); return builder.build(); } private static IdentifierGeneratorDefinition buildSequenceGeneratorDefinition(String name) { final SequenceGeneratorJpaAnnotation sequenceGeneratorUsage = SEQUENCE_GENERATOR.createUsage( null ); if ( isNotEmpty( name ) ) { sequenceGeneratorUsage.name( name ); } final Builder builder = new Builder(); interpretSequenceGenerator( sequenceGeneratorUsage, builder ); return builder.build(); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof IdentifierGeneratorDefinition that) ) { return false; } return Objects.equals(name, that.name) && Objects.equals(strategy, that.strategy) && Objects.equals(parameters, that.parameters); } @Override public int hashCode() { return Objects.hash( name, strategy, parameters ); } @Override public String toString() { return "IdentifierGeneratorDefinition{" + "name='" + name + '\'' + ", strategy='" + strategy + '\'' + ", parameters=" + parameters + '}'; } public static
IdentifierGeneratorDefinition
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/discovery/pkg/AnEntity.java
{ "start": 557, "end": 1076 }
class ____ { @Id private Integer id; @Basic private String name; @ElementCollection @CollectionTable(name="elements", joinColumns = @JoinColumn(name = "owner_fk")) @Column(name="txt") private Collection<String> elements; protected AnEntity() { // for Hibernate use } public AnEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
AnEntity
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodePrevalidateShardPathRequest.java
{ "start": 967, "end": 2042 }
class ____ extends AbstractTransportRequest { private final Set<ShardId> shardIds; public NodePrevalidateShardPathRequest(Collection<ShardId> shardIds) { this.shardIds = Set.copyOf(Objects.requireNonNull(shardIds)); } public NodePrevalidateShardPathRequest(StreamInput in) throws IOException { super(in); this.shardIds = in.readCollectionAsImmutableSet(ShardId::new); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeCollection(shardIds); } public Set<ShardId> getShardIds() { return shardIds; } @Override public boolean equals(Object o) { if (this == o) return true; if (o instanceof NodePrevalidateShardPathRequest == false) return false; NodePrevalidateShardPathRequest other = (NodePrevalidateShardPathRequest) o; return Objects.equals(shardIds, other.shardIds); } @Override public int hashCode() { return Objects.hash(shardIds); } }
NodePrevalidateShardPathRequest
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/main/java/org/apache/camel/component/cxf/jaxws/CxfEndpointUtils.java
{ "start": 1316, "end": 4008 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(CxfEndpointUtils.class); private CxfEndpointUtils() { // not constructed } public static QName getQName(final String name) { QName qName = null; if (name != null) { try { qName = QName.valueOf(name); } catch (Exception ex) { LOG.warn("Cannot create QName: {}", ex.getMessage(), ex); } } return qName; } public static boolean hasWebServiceAnnotation(Class<?> cls) { return hasAnnotation(cls, WebService.class) || hasAnnotation(cls, WebServiceProvider.class); } public static boolean hasAnnotation(Class<?> cls, Class<? extends Annotation> annotation) { if (cls == null || cls == Object.class) { return false; } if (null != cls.getAnnotation(annotation)) { return true; } for (Class<?> interfaceClass : cls.getInterfaces()) { if (null != interfaceClass.getAnnotation(annotation)) { return true; } } return hasAnnotation(cls.getSuperclass(), annotation); } // only used by test currently public static void checkServiceClassName(String className) throws CamelException { if (ObjectHelper.isEmpty(className)) { throw new CamelException("serviceClass is required for CXF endpoint configuration"); } } /** * Get effective address for a client to invoke a service. It first looks for the * {@link org.apache.camel.Exchange#DESTINATION_OVERRIDE_URL} in the IN message header. If the header is not found, * it will return the default address. * * @param exchange * @param defaultAddress */ public static String getEffectiveAddress(Exchange exchange, String defaultAddress) { String retval = exchange.getIn().getHeader(CxfConstants.DESTINATION_OVERRIDE_URL, String.class); if (retval == null) { retval = defaultAddress; } else { LOG.trace("Client address is overridden by header '{}' to value '{}'", CxfConstants.DESTINATION_OVERRIDE_URL, retval); } return retval; } /** * Create a CXF bus with either BusFactory or SpringBusFactory if Camel Context is SpringCamelContext. In the latter * case, this method updates the bus configuration with the applicationContext which SpringCamelContext holds * */ public static Bus createBus() { BusFactory busFactory = BusFactory.newInstance(); return busFactory.createBus(); } }
CxfEndpointUtils
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/MaximumLevelTest.java
{ "start": 156, "end": 719 }
class ____ extends TestCase { public void test_for_maximum() throws Exception { int[] chars = new int[] {0x5b, 0x7b}; for (int ch : chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 500; ++i) { sb.append((char) ch); } Exception error = null; try { JSON.parseObject(sb.toString()); } catch (JSONException ex) { error = ex; } assertNotNull(error); } } }
MaximumLevelTest
java
apache__hadoop
hadoop-tools/hadoop-aliyun/src/test/java/org/apache/hadoop/fs/aliyun/oss/TestAliyunOSSFileSystemStore.java
{ "start": 2054, "end": 5703 }
class ____ { private Configuration conf; private AliyunOSSFileSystemStore store; private AliyunOSSFileSystem fs; @BeforeEach public void setUp() throws Exception { conf = new Configuration(); fs = new AliyunOSSFileSystem(); fs.initialize(URI.create(conf.get("test.fs.oss.name")), conf); store = fs.getStore(); } @AfterEach public void tearDown() throws Exception { try { store.purge("test"); } catch (Exception e) { e.printStackTrace(); throw e; } } @BeforeAll public static void checkSettings() throws Exception { Configuration conf = new Configuration(); assumeTrue(conf.get(Constants.ACCESS_KEY_ID) != null); assumeTrue(conf.get(Constants.ACCESS_KEY_SECRET) != null); assumeTrue(conf.get("test.fs.oss.name") != null); } protected void writeRenameReadCompare(Path path, long len) throws IOException, NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); OutputStream out = new BufferedOutputStream( new DigestOutputStream(fs.create(path, false), digest)); for (long i = 0; i < len; i++) { out.write('Q'); } out.flush(); out.close(); assertTrue(fs.exists(path), "Exists"); ObjectMetadata srcMeta = fs.getStore().getObjectMetadata( path.toUri().getPath().substring(1)); Path copyPath = path.suffix(".copy"); fs.rename(path, copyPath); assertTrue(fs.exists(copyPath), "Copy exists"); // file type should not change ObjectMetadata dstMeta = fs.getStore().getObjectMetadata( copyPath.toUri().getPath().substring(1)); assertEquals(srcMeta.getObjectType(), dstMeta.getObjectType()); // Download file from Aliyun OSS and compare the digest against the original MessageDigest digest2 = MessageDigest.getInstance("MD5"); InputStream in = new BufferedInputStream( new DigestInputStream(fs.open(copyPath), digest2)); long copyLen = 0; while (in.read() != -1) { copyLen++; } in.close(); assertEquals(len, copyLen, "Copy length matches original"); assertArrayEquals(digest.digest(), digest2.digest(), "Digests match"); } @Test public void testSmallUpload() throws IOException, NoSuchAlgorithmException { // Regular upload, regular copy writeRenameReadCompare(new Path("/test/small"), 16384); } @Test public void testLargeUpload() throws IOException, NoSuchAlgorithmException { // Multipart upload, shallow copy writeRenameReadCompare(new Path("/test/xlarge"), Constants.MULTIPART_UPLOAD_PART_SIZE_DEFAULT + 1); } @Test public void testDeleteObjects() throws IOException, NoSuchAlgorithmException { // generate test files final int files = 10; final long size = 5 * 1024 * 1024; final String prefix = "dir"; for (int i = 0; i < files; i++) { Path path = new Path(String.format("/%s/testFile-%d.txt", prefix, i)); ContractTestUtils.generateTestFile(this.fs, path, size, 256, 255); } OSSListRequest listRequest = store.createListObjectsRequest(prefix, MAX_PAGING_KEYS_DEFAULT, null, null, true); List<String> keysToDelete = new ArrayList<>(); OSSListResult objects = store.listObjects(listRequest); assertEquals(files, objects.getObjectSummaries().size()); // test delete files for (OSSObjectSummary objectSummary : objects.getObjectSummaries()) { keysToDelete.add(objectSummary.getKey()); } store.deleteObjects(keysToDelete); objects = store.listObjects(listRequest); assertEquals(0, objects.getObjectSummaries().size()); } }
TestAliyunOSSFileSystemStore
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/csrf/XorCsrfTokenRequestAttributeHandler.java
{ "start": 5309, "end": 5718 }
class ____ implements Supplier<CsrfToken> { private final Supplier<CsrfToken> delegate; private @Nullable CsrfToken csrfToken; private CachedCsrfTokenSupplier(Supplier<CsrfToken> delegate) { this.delegate = delegate; } @Override public CsrfToken get() { if (this.csrfToken == null) { this.csrfToken = this.delegate.get(); } return this.csrfToken; } } }
CachedCsrfTokenSupplier
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-class-loader/maven-it-plugin-class-loader/src/main/java/org/apache/maven/plugin/coreit/AbstractLoadMojo.java
{ "start": 7667, "end": 8469 }
class ____ defect while getting " + path); urls = Collections.EMPTY_LIST; } loaderProperties.setProperty(path + ".count", "" + urls.size()); for (int j = 0; j < urls.size(); j++) { loaderProperties.setProperty(path + "." + j, urls.get(j).toString()); } } catch (IOException e) { throw new MojoExecutionException("Resources could not be enumerated: " + path, e); } } } getLog().info("[MAVEN-CORE-IT-LOG] Creating output file " + outputFile); PropertiesUtil.write(outputFile, loaderProperties); getLog().info("[MAVEN-CORE-IT-LOG] Created output file " + outputFile); } }
loader
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java
{ "start": 7224, "end": 7523 }
class ____ { public int beforeStringReturn; public int afterTakesInt; @Before("execution(String *.*(..))") public void traceWithoutJoinPoint() { ++beforeStringReturn; } @AfterReturning("execution(void *.*(int))") public void traceWithoutJoinPoint2() { ++afterTakesInt; } }
TraceAspect
java
google__guava
android/guava-tests/test/com/google/common/collect/ImmutableBiMapTest.java
{ "start": 2288, "end": 21603 }
class ____ extends TestCase { // TODO: Reduce duplication of ImmutableMapTest code @J2ktIncompatible @GwtIncompatible // suite @AndroidIncompatible // test-suite builders public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest( BiMapTestSuiteBuilder.using(new ImmutableBiMapGenerator()) .named("ImmutableBiMap") .withFeatures( CollectionSize.ANY, CollectionFeature.SERIALIZABLE, CollectionFeature.KNOWN_ORDER, MapFeature.REJECTS_DUPLICATES_AT_CREATION, MapFeature.ALLOWS_ANY_NULL_QUERIES) .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods()) .createTestSuite()); suite.addTest( BiMapTestSuiteBuilder.using(new ImmutableBiMapCopyOfGenerator()) .named("ImmutableBiMap.copyOf[Map]") .withFeatures( CollectionSize.ANY, CollectionFeature.SERIALIZABLE, CollectionFeature.KNOWN_ORDER, MapFeature.ALLOWS_ANY_NULL_QUERIES) .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods()) .createTestSuite()); suite.addTest( BiMapTestSuiteBuilder.using(new ImmutableBiMapCopyOfEntriesGenerator()) .named("ImmutableBiMap.copyOf[Iterable<Entry>]") .withFeatures( CollectionSize.ANY, CollectionFeature.SERIALIZABLE, CollectionFeature.KNOWN_ORDER, MapFeature.REJECTS_DUPLICATES_AT_CREATION, MapFeature.ALLOWS_ANY_NULL_QUERIES) .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods()) .createTestSuite()); suite.addTestSuite(ImmutableBiMapTest.class); return suite; } // Creation tests public void testEmptyBuilder() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build(); assertEquals(Collections.<String, Integer>emptyMap(), map); assertEquals(Collections.<Integer, String>emptyMap(), map.inverse()); assertSame(ImmutableBiMap.of(), map); } public void testSingletonBuilder() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build(); assertMapEquals(map, "one", 1); assertMapEquals(map.inverse(), 1, "one"); } public void testBuilder_withImmutableEntry() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put(immutableEntry("one", 1)).build(); assertMapEquals(map, "one", 1); } public void testBuilder() { ImmutableBiMap<String, Integer> map = ImmutableBiMap.<String, Integer>builder() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } @GwtIncompatible public void testBuilderExactlySizedReusesArray() { ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10); Object[] builderArray = builder.alternatingKeysAndValues; for (int i = 0; i < 10; i++) { builder.put(i, i); } Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues; RegularImmutableBiMap<Integer, Integer> map = (RegularImmutableBiMap<Integer, Integer>) builder.build(); Object[] mapInternalArray = map.alternatingKeysAndValues; assertSame(builderArray, builderArrayAfterPuts); assertSame(builderArray, mapInternalArray); } public void testBuilder_orderEntriesByValue() { ImmutableBiMap<String, Integer> map = ImmutableBiMap.<String, Integer>builder() .orderEntriesByValue(Ordering.natural()) .put("three", 3) .put("one", 1) .put("five", 5) .put("four", 4) .put("two", 2) .build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testBuilder_orderEntriesByValueAfterExactSizeBuild() { ImmutableBiMap.Builder<String, Integer> builder = new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1); ImmutableMap<String, Integer> keyOrdered = builder.build(); ImmutableMap<String, Integer> valueOrdered = builder.orderEntriesByValue(Ordering.natural()).build(); assertMapEquals(keyOrdered, "four", 4, "one", 1); assertMapEquals(valueOrdered, "one", 1, "four", 4); } public void testBuilder_orderEntriesByValue_usedTwiceFails() { ImmutableBiMap.Builder<String, Integer> builder = new Builder<String, Integer>().orderEntriesByValue(Ordering.natural()); assertThrows( IllegalStateException.class, () -> builder.orderEntriesByValue(Ordering.natural())); } public void testBuilderPutAllWithEmptyMap() { ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build(); assertEquals(Collections.<String, Integer>emptyMap(), map); } public void testBuilderPutAll() { Map<String, Integer> toPut = new LinkedHashMap<>(); toPut.put("one", 1); toPut.put("two", 2); toPut.put("three", 3); Map<String, Integer> moreToPut = new LinkedHashMap<>(); moreToPut.put("four", 4); moreToPut.put("five", 5); ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build(); assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testBuilderReuse() { Builder<String, Integer> builder = new Builder<>(); ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build(); ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build(); assertMapEquals(mapOne, "one", 1, "two", 2); assertMapEquals(mapOne.inverse(), 1, "one", 2, "two"); assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four"); } public void testBuilderPutNullKey() { Builder<String, Integer> builder = new Builder<>(); assertThrows(NullPointerException.class, () -> builder.put(null, 1)); } public void testBuilderPutNullValue() { Builder<String, Integer> builder = new Builder<>(); assertThrows(NullPointerException.class, () -> builder.put("one", null)); } public void testBuilderPutNullKeyViaPutAll() { Builder<String, Integer> builder = new Builder<>(); assertThrows( NullPointerException.class, () -> builder.putAll(Collections.<String, Integer>singletonMap(null, 1))); } public void testBuilderPutNullValueViaPutAll() { Builder<String, Integer> builder = new Builder<>(); assertThrows( NullPointerException.class, () -> builder.putAll(Collections.<String, Integer>singletonMap("one", null))); } @SuppressWarnings("AlwaysThrows") public void testPuttingTheSameKeyTwiceThrowsOnBuild() { Builder<String, Integer> builder = new Builder<String, Integer>() .put("one", 1) .put("one", 1); // throwing on this line would be even better IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> builder.build()); assertThat(expected).hasMessageThat().contains("one"); } public void testOf() { assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1); assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one"); assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(), 1, "one", 2, "two", 3, "three"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(), 1, "one", 2, "two", 3, "three", 4, "four"); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals( ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9); assertMapEquals( ImmutableBiMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10); } public void testOfNullKey() { assertThrows(NullPointerException.class, () -> ImmutableBiMap.of(null, 1)); assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, null, 2)); } public void testOfNullValue() { assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", null)); assertThrows(NullPointerException.class, () -> ImmutableBiMap.of("one", 1, "two", null)); } @SuppressWarnings({"AlwaysThrows", "DistinctVarargsChecker"}) public void testOfWithDuplicateKey() { IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.of("one", 1, "one", 1)); assertThat(expected).hasMessageThat().contains("one"); } public void testOfEntries() { assertMapEquals(ImmutableBiMap.ofEntries(entry("one", 1), entry("two", 2)), "one", 1, "two", 2); } public void testOfEntriesNull() { Entry<@Nullable Integer, Integer> nullKey = entry(null, 23); assertThrows( NullPointerException.class, () -> ImmutableBiMap.ofEntries((Entry<Integer, Integer>) nullKey)); Entry<Integer, @Nullable Integer> nullValue = ImmutableBiMapTest.<@Nullable Integer>entry(23, null); assertThrows( NullPointerException.class, () -> ImmutableBiMap.ofEntries((Entry<Integer, Integer>) nullValue)); } private static <T extends @Nullable Object> Entry<T, T> entry(T key, T value) { return new AbstractMap.SimpleImmutableEntry<>(key, value); } public void testCopyOfEmptyMap() { ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableBiMap.copyOf(copy)); assertSame(ImmutableBiMap.of(), copy); } public void testCopyOfSingletonMap() { ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableBiMap.copyOf(copy)); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableBiMap.copyOf(copy)); } public void testEmpty() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of(); assertEquals(Collections.<String, Integer>emptyMap(), bimap); assertEquals(Collections.<Integer, String>emptyMap(), bimap.inverse()); } public void testFromHashMap() { Map<String, Integer> hashMap = new LinkedHashMap<>(); hashMap.put("one", 1); hashMap.put("two", 2); ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(hashMap); assertMapEquals(bimap, "one", 1, "two", 2); assertMapEquals(bimap.inverse(), 1, "one", 2, "two"); } public void testFromImmutableMap() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf( new ImmutableMap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("three", 3) .put("four", 4) .put("five", 5) .buildOrThrow()); assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); } public void testDuplicateValues() { ImmutableMap<String, Integer> map = new ImmutableMap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .put("uno", 1) .put("dos", 2) .buildOrThrow(); IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> ImmutableBiMap.copyOf(map)); assertThat(expected).hasMessageThat().containsMatch("1|2"); } // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7. public void testToImmutableBiMap_java7_combine() { ImmutableBiMap.Builder<String, Integer> zis = ImmutableBiMap.<String, Integer>builder().put("one", 1); ImmutableBiMap.Builder<String, Integer> zat = ImmutableBiMap.<String, Integer>builder().put("two", 2).put("three", 3); ImmutableBiMap<String, Integer> biMap = zis.combine(zat).build(); assertMapEquals(biMap, "one", 1, "two", 2, "three", 3); } // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7. public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() { ImmutableBiMap.Builder<String, Integer> zis = ImmutableBiMap.<String, Integer>builder().put("one", 1).put("two", 2); ImmutableBiMap.Builder<String, Integer> zat = ImmutableBiMap.<String, Integer>builder().put("two", 22).put("three", 3); assertThrows(IllegalArgumentException.class, () -> zis.combine(zat).build()); } // BiMap-specific tests @SuppressWarnings("DoNotCall") public void testForcePut() { BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); assertThrows(UnsupportedOperationException.class, () -> bimap.forcePut("three", 3)); } public void testKeySet() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<String> keys = bimap.keySet(); assertEquals(newHashSet("one", "two", "three", "four"), keys); assertThat(keys).containsExactly("one", "two", "three", "four").inOrder(); } public void testValues() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4)); Set<Integer> values = bimap.values(); assertEquals(newHashSet(1, 2, 3, 4), values); assertThat(values).containsExactly(1, 2, 3, 4).inOrder(); } public void testDoubleInverse() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); assertSame(bimap, bimap.inverse().inverse()); } @J2ktIncompatible @GwtIncompatible // SerializableTester public void testEmptySerialization() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of(); assertSame(bimap, SerializableTester.reserializeAndAssert(bimap)); } @J2ktIncompatible @GwtIncompatible // SerializableTester public void testSerialization() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap); assertEquals(Integer.valueOf(1), copy.get("one")); assertEquals("one", copy.inverse().get(1)); assertSame(copy, copy.inverse().inverse()); } @J2ktIncompatible @GwtIncompatible // SerializableTester public void testInverseSerialization() { ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse(); ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap); assertEquals(Integer.valueOf(1), copy.get("one")); assertEquals("one", copy.inverse().get(1)); assertSame(copy, copy.inverse().inverse()); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { Map<Object, Object> expected = new LinkedHashMap<>(); for (int i = 0; i < alternatingKeysAndValues.length; i += 2) { expected.put(alternatingKeysAndValues[i], alternatingKeysAndValues[i + 1]); } assertThat(map).containsExactlyEntriesIn(expected).inOrder(); } /** No-op test so that the
ImmutableBiMapTest
java
apache__flink
flink-test-utils-parent/flink-connector-test-utils/src/main/java/org/apache/flink/connector/testframe/external/sink/DataStreamSinkExternalContext.java
{ "start": 1289, "end": 2224 }
interface ____<T> extends ExternalContext, ResultTypeQueryable<T> { /** Create a reader for consuming data written to the external system by sink. */ ExternalSystemDataReader<T> createSinkDataReader(TestingSinkSettings sinkSettings); /** * Generate test data. * * <p>These test data will be sent to sink via a special source in Flink job, write to external * system by sink, consume back via {@link ExternalSystemDataReader}, and make comparison with * {@link T#equals(Object)} for validating correctness. * * <p>Make sure that the {@link T#equals(Object)} returns false when the records in different * splits. * * @param sinkSettings settings of the sink * @param seed Seed for generating random test data set. * @return List of generated test data. */ List<T> generateTestData(TestingSinkSettings sinkSettings, long seed); }
DataStreamSinkExternalContext
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/repeatable/BothSelectAndSelectProviderMapper.java
{ "start": 1003, "end": 1161 }
class ____ { public static String getUser() { return "SELECT * FROM users WHERE id = #{id}"; } private SqlProvider() { } } }
SqlProvider
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/EmptyConfigUpdate.java
{ "start": 1904, "end": 2229 }
class ____ implements InferenceConfigUpdate.Builder<Builder, EmptyConfigUpdate> { @Override public Builder setResultsField(String resultsField) { return this; } @Override public EmptyConfigUpdate build() { return new EmptyConfigUpdate(); } } }
Builder
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KafkaEndpointBuilderFactory.java
{ "start": 157594, "end": 178421 }
class ____ * exception in runtime. * * The option is a: <code>java.lang.String</code> type. * * Group: monitoring * * @param interceptorClasses the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder interceptorClasses(String interceptorClasses) { doSetProperty("interceptorClasses", interceptorClasses); return this; } /** * URL of the schema registry servers to use. The format is * host1:port1,host2:port2. This is known as schema.registry.url in * multiple Schema registries documentation. This option is only * available externally (not standard Apache Kafka). * * The option is a: <code>java.lang.String</code> type. * * Group: schema * * @param schemaRegistryURL the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder schemaRegistryURL(String schemaRegistryURL) { doSetProperty("schemaRegistryURL", schemaRegistryURL); return this; } /** * Login thread sleep time between refresh attempts. * * The option is a: <code>java.lang.Integer</code> type. * * Default: 60000 * Group: security * * @param kerberosBeforeReloginMinTime the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosBeforeReloginMinTime(Integer kerberosBeforeReloginMinTime) { doSetProperty("kerberosBeforeReloginMinTime", kerberosBeforeReloginMinTime); return this; } /** * Login thread sleep time between refresh attempts. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 60000 * Group: security * * @param kerberosBeforeReloginMinTime the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosBeforeReloginMinTime(String kerberosBeforeReloginMinTime) { doSetProperty("kerberosBeforeReloginMinTime", kerberosBeforeReloginMinTime); return this; } /** * Location of the kerberos config file. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param kerberosConfigLocation the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosConfigLocation(String kerberosConfigLocation) { doSetProperty("kerberosConfigLocation", kerberosConfigLocation); return this; } /** * Kerberos kinit command path. Default is /usr/bin/kinit. * * The option is a: <code>java.lang.String</code> type. * * Default: /usr/bin/kinit * Group: security * * @param kerberosInitCmd the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosInitCmd(String kerberosInitCmd) { doSetProperty("kerberosInitCmd", kerberosInitCmd); return this; } /** * A list of rules for mapping from principal names to short names * (typically operating system usernames). The rules are evaluated in * order, and the first rule that matches a principal name is used to * map it to a short name. Any later rules in the list are ignored. By * default, principal names of the form {username}/{hostname}{REALM} are * mapped to {username}. For more details on the format, please see the * Security Authorization and ACLs documentation (at the Apache Kafka * project website). Multiple values can be separated by comma. * * The option is a: <code>java.lang.String</code> type. * * Default: DEFAULT * Group: security * * @param kerberosPrincipalToLocalRules the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosPrincipalToLocalRules(String kerberosPrincipalToLocalRules) { doSetProperty("kerberosPrincipalToLocalRules", kerberosPrincipalToLocalRules); return this; } /** * Percentage of random jitter added to the renewal time. * * The option is a: <code>java.lang.Double</code> type. * * Default: 0.05 * Group: security * * @param kerberosRenewJitter the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosRenewJitter(Double kerberosRenewJitter) { doSetProperty("kerberosRenewJitter", kerberosRenewJitter); return this; } /** * Percentage of random jitter added to the renewal time. * * The option will be converted to a <code>java.lang.Double</code> type. * * Default: 0.05 * Group: security * * @param kerberosRenewJitter the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosRenewJitter(String kerberosRenewJitter) { doSetProperty("kerberosRenewJitter", kerberosRenewJitter); return this; } /** * Login thread will sleep until the specified window factor of time * from last refresh to ticket's expiry has been reached, at which time * it will try to renew the ticket. * * The option is a: <code>java.lang.Double</code> type. * * Default: 0.8 * Group: security * * @param kerberosRenewWindowFactor the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosRenewWindowFactor(Double kerberosRenewWindowFactor) { doSetProperty("kerberosRenewWindowFactor", kerberosRenewWindowFactor); return this; } /** * Login thread will sleep until the specified window factor of time * from last refresh to ticket's expiry has been reached, at which time * it will try to renew the ticket. * * The option will be converted to a <code>java.lang.Double</code> type. * * Default: 0.8 * Group: security * * @param kerberosRenewWindowFactor the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder kerberosRenewWindowFactor(String kerberosRenewWindowFactor) { doSetProperty("kerberosRenewWindowFactor", kerberosRenewWindowFactor); return this; } /** * Expose the kafka sasl.jaas.config parameter Example: * org.apache.kafka.common.security.plain.PlainLoginModule required * username=USERNAME password=PASSWORD;. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param saslJaasConfig the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder saslJaasConfig(String saslJaasConfig) { doSetProperty("saslJaasConfig", saslJaasConfig); return this; } /** * The Kerberos principal name that Kafka runs as. This can be defined * either in Kafka's JAAS config or in Kafka's config. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param saslKerberosServiceName the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder saslKerberosServiceName(String saslKerberosServiceName) { doSetProperty("saslKerberosServiceName", saslKerberosServiceName); return this; } /** * The Simple Authentication and Security Layer (SASL) Mechanism used. * For the valid values see * http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml. * * The option is a: <code>java.lang.String</code> type. * * Default: GSSAPI * Group: security * * @param saslMechanism the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder saslMechanism(String saslMechanism) { doSetProperty("saslMechanism", saslMechanism); return this; } /** * Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT, * SASL_SSL and SSL are supported. * * The option is a: <code>java.lang.String</code> type. * * Default: PLAINTEXT * Group: security * * @param securityProtocol the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder securityProtocol(String securityProtocol) { doSetProperty("securityProtocol", securityProtocol); return this; } /** * A list of cipher suites. This is a named combination of * authentication, encryption, MAC and key exchange algorithm used to * negotiate the security settings for a network connection using TLS or * SSL network protocol. By default, all the available cipher suites are * supported. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslCipherSuites the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslCipherSuites(String sslCipherSuites) { doSetProperty("sslCipherSuites", sslCipherSuites); return this; } /** * SSL configuration using a Camel SSLContextParameters object. If * configured, it's applied before the other SSL endpoint parameters. * NOTE: Kafka only supports loading keystore from file locations, so * prefix the location with file: in the KeyStoreParameters.resource * option. * * The option is a: * <code>org.apache.camel.support.jsse.SSLContextParameters</code> type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * SSL configuration using a Camel SSLContextParameters object. If * configured, it's applied before the other SSL endpoint parameters. * NOTE: Kafka only supports loading keystore from file locations, so * prefix the location with file: in the KeyStoreParameters.resource * option. * * The option will be converted to a * <code>org.apache.camel.support.jsse.SSLContextParameters</code> type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslContextParameters(String sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * The list of protocols enabled for SSL connections. The default is * TLSv1.2,TLSv1.3 when running with Java 11 or newer, TLSv1.2 * otherwise. With the default value for Java 11, clients and servers * will prefer TLSv1.3 if both support it and fallback to TLSv1.2 * otherwise (assuming both support at least TLSv1.2). This default * should be fine for most cases. Also see the config documentation for * SslProtocol. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslEnabledProtocols the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslEnabledProtocols(String sslEnabledProtocols) { doSetProperty("sslEnabledProtocols", sslEnabledProtocols); return this; } /** * The endpoint identification algorithm to validate server hostname * using server certificate. Use none or false to disable server * hostname verification. * * The option is a: <code>java.lang.String</code> type. * * Default: https * Group: security * * @param sslEndpointAlgorithm the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslEndpointAlgorithm(String sslEndpointAlgorithm) { doSetProperty("sslEndpointAlgorithm", sslEndpointAlgorithm); return this; } /** * The algorithm used by key manager factory for SSL connections. * Default value is the key manager factory algorithm configured for the * Java Virtual Machine. * * The option is a: <code>java.lang.String</code> type. * * Default: SunX509 * Group: security * * @param sslKeymanagerAlgorithm the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslKeymanagerAlgorithm(String sslKeymanagerAlgorithm) { doSetProperty("sslKeymanagerAlgorithm", sslKeymanagerAlgorithm); return this; } /** * The password of the private key in the key store file or the PEM key * specified in sslKeystoreKey. This is required for clients only if * two-way authentication is configured. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslKeyPassword the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslKeyPassword(String sslKeyPassword) { doSetProperty("sslKeyPassword", sslKeyPassword); return this; } /** * The location of the key store file. This is optional for the client * and can be used for two-way authentication for the client. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslKeystoreLocation the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslKeystoreLocation(String sslKeystoreLocation) { doSetProperty("sslKeystoreLocation", sslKeystoreLocation); return this; } /** * The store password for the key store file. This is optional for the * client and only needed if sslKeystoreLocation is configured. Key * store password is not supported for PEM format. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslKeystorePassword the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslKeystorePassword(String sslKeystorePassword) { doSetProperty("sslKeystorePassword", sslKeystorePassword); return this; } /** * The file format of the key store file. This is optional for the * client. The default value is JKS. * * The option is a: <code>java.lang.String</code> type. * * Default: JKS * Group: security * * @param sslKeystoreType the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslKeystoreType(String sslKeystoreType) { doSetProperty("sslKeystoreType", sslKeystoreType); return this; } /** * The SSL protocol used to generate the SSLContext. The default is * TLSv1.3 when running with Java 11 or newer, TLSv1.2 otherwise. This * value should be fine for most use cases. Allowed values in recent * JVMs are TLSv1.2 and TLSv1.3. TLS, TLSv1.1, SSL, SSLv2 and SSLv3 may * be supported in older JVMs, but their usage is discouraged due to * known security vulnerabilities. With the default value for this * config and sslEnabledProtocols, clients will downgrade to TLSv1.2 if * the server does not support TLSv1.3. If this config is set to * TLSv1.2, clients will not use TLSv1.3 even if it is one of the values * in sslEnabledProtocols and the server only supports TLSv1.3. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslProtocol the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslProtocol(String sslProtocol) { doSetProperty("sslProtocol", sslProtocol); return this; } /** * The name of the security provider used for SSL connections. Default * value is the default security provider of the JVM. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslProvider the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslProvider(String sslProvider) { doSetProperty("sslProvider", sslProvider); return this; } /** * The algorithm used by trust manager factory for SSL connections. * Default value is the trust manager factory algorithm configured for * the Java Virtual Machine. * * The option is a: <code>java.lang.String</code> type. * * Default: PKIX * Group: security * * @param sslTrustmanagerAlgorithm the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslTrustmanagerAlgorithm(String sslTrustmanagerAlgorithm) { doSetProperty("sslTrustmanagerAlgorithm", sslTrustmanagerAlgorithm); return this; } /** * The location of the trust store file. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslTruststoreLocation the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslTruststoreLocation(String sslTruststoreLocation) { doSetProperty("sslTruststoreLocation", sslTruststoreLocation); return this; } /** * The password for the trust store file. If a password is not set, * trust store file configured will still be used, but integrity * checking is disabled. Trust store password is not supported for PEM * format. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param sslTruststorePassword the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslTruststorePassword(String sslTruststorePassword) { doSetProperty("sslTruststorePassword", sslTruststorePassword); return this; } /** * The file format of the trust store file. The default value is JKS. * * The option is a: <code>java.lang.String</code> type. * * Default: JKS * Group: security * * @param sslTruststoreType the value to set * @return the dsl builder */ default KafkaEndpointProducerBuilder sslTruststoreType(String sslTruststoreType) { doSetProperty("sslTruststoreType", sslTruststoreType); return this; } } /** * Advanced builder for endpoint producers for the Kafka component. */ public
cast
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoderFactory.java
{ "start": 1085, "end": 1371 }
interface ____<C> { /** * Creates a {@code ReactiveJwtDecoder} using the supplied "contextual" type. * @param context the type that provides contextual information * @return a {@link ReactiveJwtDecoder} */ ReactiveJwtDecoder createDecoder(C context); }
ReactiveJwtDecoderFactory
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/BeanDefinitionProcessorListener.java
{ "start": 1505, "end": 3403 }
class ____ implements BeanCreatedEventListener<BeanDefinitionProcessor<?>> { @Override public BeanDefinitionProcessor<?> onCreated(BeanCreatedEvent<BeanDefinitionProcessor<?>> event) { BeanDefinitionProcessor<?> beanDefinitionProcessor = event.getBean(); BeanDefinition<BeanDefinitionProcessor<?>> processorDefinition = event.getBeanDefinition(); BeanContext beanContext = event.getSource(); if (beanDefinitionProcessor instanceof LifeCycle<?> cycle) { try { cycle.start(); } catch (Exception e) { throw new BeanContextException("Error starting bean processing: " + e.getMessage(), e); } } final List<Argument<?>> typeArguments = processorDefinition.getTypeArguments(BeanDefinitionProcessor.class); if (typeArguments.size() == 1) { final Argument<?> annotation = typeArguments.get(0); Collection<BeanDefinition<?>> beanDefinitions = beanContext.getBeanDefinitions(Qualifiers.byStereotype((Class) annotation.getType())); for (BeanDefinition<?> beanDefinition : beanDefinitions) { try { beanDefinitionProcessor.process(beanDefinition, beanContext); } catch (Exception e) { throw new BeanContextException( "Error processing bean definition [" + beanDefinition + "]: " + e.getMessage(), e ); } } } if (beanDefinitionProcessor instanceof LifeCycle<?> cycle) { try { cycle.stop(); } catch (Exception e) { throw new BeanContextException("Error finalizing bean processing: " + e.getMessage(), e); } } return beanDefinitionProcessor; } }
BeanDefinitionProcessorListener
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/spies/SpyAsDefaultMockUsageTest.java
{ "start": 858, "end": 1059 }
class ____ { Strategy strategy; Producer(Strategy f) { strategy = f; } Sampler produce() { return new Sampler(strategy); } } }
Producer
java
apache__camel
components/camel-aws/camel-aws2-kms/src/test/java/org/apache/camel/component/aws2/kms/localstack/KmsDescribeKeyIT.java
{ "start": 1470, "end": 3219 }
class ____ extends Aws2KmsBase { @EndpointInject private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint result; @Test public void sendIn() throws Exception { result.expectedMessageCount(1); Exchange ex = template.send("direct:createKey", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(KMS2Constants.OPERATION, "createKey"); } }); String keyId = ex.getMessage().getBody(CreateKeyResponse.class).keyMetadata().keyId(); template.send("direct:describeKey", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(KMS2Constants.OPERATION, "describeKey"); exchange.getIn().setHeader(KMS2Constants.KEY_ID, keyId); } }); MockEndpoint.assertIsSatisfied(context); assertEquals(1, result.getExchanges().size()); assertEquals(KeyState.ENABLED, result.getExchanges().get(0).getIn().getBody(DescribeKeyResponse.class).keyMetadata().keyState()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { String awsEndpoint = "aws2-kms://default?operation=createKey"; String describeKey = "aws2-kms://default?operation=describeKey"; from("direct:createKey").to(awsEndpoint); from("direct:describeKey").to(describeKey).to("mock:result"); } }; } }
KmsDescribeKeyIT
java
elastic__elasticsearch
modules/apm/src/test/java/org/elasticsearch/telemetry/apm/RecordingOtelMeter.java
{ "start": 18794, "end": 19466 }
class ____ extends AbstractInstrument implements ObservableLongMeasurement, OtelInstrument { LongMeasurementRecorder(String name, InstrumentType instrument) { super(name, instrument); } LongMeasurementRecorder(String name) { super(name, InstrumentType.LONG_GAUGE); } @Override public void record(long value) { recorder.call(instrument, name, value, null); } @Override public void record(long value, Attributes attributes) { recorder.call(instrument, name, value, toMap(attributes)); } } // Histograms private
LongMeasurementRecorder
java
eclipse-vertx__vert.x
vertx-core/src/main/java/examples/HTTPExamples.java
{ "start": 28362, "end": 47398 }
class ____ extends Exception { private final int code; public MyCustomException(int code, String message) { super(message); this.code = code; } } public void exampleFollowRedirect01(HttpClient client) { client .request(HttpMethod.GET, "some-uri") .onComplete(ar1 -> { if (ar1.succeeded()) { HttpClientRequest request = ar1.result(); request.setFollowRedirects(true); request .send() .onComplete(ar2 -> { if (ar2.succeeded()) { HttpClientResponse response = ar2.result(); System.out.println("Received response with status code " + response.statusCode()); } }); } }); } public void exampleFollowRedirect02(Vertx vertx) { HttpClientAgent client = vertx.createHttpClient( new HttpClientOptions() .setMaxRedirects(32)); client .request(HttpMethod.GET, "some-uri") .onComplete(ar1 -> { if (ar1.succeeded()) { HttpClientRequest request = ar1.result(); request.setFollowRedirects(true); request .send() .onComplete(ar2 -> { if (ar2.succeeded()) { HttpClientResponse response = ar2.result(); System.out.println("Received response with status code " + response.statusCode()); } }); } }); } private String resolveURI(String base, String uriRef) { throw new UnsupportedOperationException(); } public void exampleFollowRedirect03(Vertx vertx) { HttpClientAgent client = vertx.httpClientBuilder() .withRedirectHandler(response -> { // Only follow 301 code if (response.statusCode() == 301 && response.getHeader("Location") != null) { // Compute the redirect URI String absoluteURI = resolveURI(response.request().absoluteURI(), response.getHeader("Location")); // Create a new ready to use request that the client will use return Future.succeededFuture(new RequestOptions().setAbsoluteURI(absoluteURI)); } // We don't redirect return null; }) .build(); } public void example50(HttpClient client) { client.request(HttpMethod.PUT, "some-uri") .onSuccess(request -> { request.response().onSuccess(response -> { System.out.println("Received response with status code " + response.statusCode()); }); request.putHeader("Expect", "100-Continue"); request.continueHandler(v -> { // OK to send rest of body request.write("Some data"); request.write("Some more data"); request.end(); }); request.writeHead(); }); } public void example50_1(HttpServer httpServer) { httpServer.requestHandler(request -> { if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) { // Send a 100 continue response request.response().writeContinue(); // The client should send the body when it receives the 100 response request.bodyHandler(body -> { // Do something with body }); request.endHandler(v -> { request.response().end(); }); } }); } public void example50_2(HttpServer httpServer) { httpServer.requestHandler(request -> { if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) { // boolean rejectAndClose = true; if (rejectAndClose) { // Reject with a failure code and close the connection // this is probably best with persistent connection request.response() .setStatusCode(405) .putHeader("Connection", "close") .end(); } else { // Reject with a failure code and ignore the body // this may be appropriate if the body is small request.response() .setStatusCode(405) .end(); } } }); } public void clientTunnel(HttpClient client) { client.request(HttpMethod.CONNECT, "some-uri") .onSuccess(request -> { // Connect to the server request .connect() .onComplete(ar -> { if (ar.succeeded()) { HttpClientResponse response = ar.result(); if (response.statusCode() != 200) { // Connect failed for some reason } else { // Tunnel created, raw buffers are transmitted on the wire NetSocket socket = response.netSocket(); } } }); }); } public void example51(HttpServer server) { server.webSocketHandler(webSocket -> { System.out.println("Connected!"); }); } public void exampleAsynchronousHandshake(HttpServer server) { server.webSocketHandshakeHandler(handshake -> { authenticate(handshake.headers(), ar -> { if (ar.succeeded()) { if (ar.result()) { // Terminate the handshake with the status code 101 (Switching Protocol) handshake.accept(); } else { // Reject the handshake with 401 (Unauthorized) handshake.reject(401); } } else { // Will send a 500 error handshake.reject(500); } }); }); } private static void authenticate(MultiMap headers, Handler<AsyncResult<Boolean>> handler) { } public void example53(HttpServer server) { server.requestHandler(request -> { if (request.path().equals("/myapi")) { Future<ServerWebSocket> fut = request.toWebSocket(); fut.onSuccess(ws -> { // Do something }); } else { // Reject request.response().setStatusCode(400).end(); } }); } public void example54(Vertx vertx) { WebSocketClient client = vertx.createWebSocketClient(); client .connect(80, "example.com", "/some-uri") .onComplete(res -> { if (res.succeeded()) { WebSocket ws = res.result(); ws.textMessageHandler(msg -> { // Handle msg }); System.out.println("Connected!"); } }); } public void example54_bis(Vertx vertx) { WebSocketClient client = vertx.createWebSocketClient(); client .webSocket() .textMessageHandler(msg -> { // Handle msg }) .connect(80, "example.com", "/some-uri") .onComplete(res -> { if (res.succeeded()) { WebSocket ws = res.result(); } }); } public void exampleWebSocketDisableOriginHeader(WebSocketClient client, String host, int port, String requestUri) { WebSocketConnectOptions options = new WebSocketConnectOptions() .setHost(host) .setPort(port) .setURI(requestUri) .setAllowOriginHeader(false); client .connect(options) .onComplete(res -> { if (res.succeeded()) { WebSocket ws = res.result(); System.out.println("Connected!"); } }); } public void exampleWebSocketSetOriginHeader(WebSocketClient client, String host, int port, String requestUri, String origin) { WebSocketConnectOptions options = new WebSocketConnectOptions() .setHost(host) .setPort(port) .setURI(requestUri) .addHeader(HttpHeaders.ORIGIN, origin); client .connect(options) .onComplete(res -> { if (res.succeeded()) { WebSocket ws = res.result(); System.out.println("Connected!"); } }); } public void example55(WebSocket webSocket) { // Write a simple binary message Buffer buffer = Buffer.buffer().appendInt(123).appendFloat(1.23f); webSocket.writeBinaryMessage(buffer); // Write a simple text message String message = "hello"; webSocket.writeTextMessage(message); } public void example56(WebSocket webSocket, Buffer buffer1, Buffer buffer2, Buffer buffer3) { WebSocketFrame frame1 = WebSocketFrame.binaryFrame(buffer1, false); webSocket.writeFrame(frame1); WebSocketFrame frame2 = WebSocketFrame.continuationFrame(buffer2, false); webSocket.writeFrame(frame2); // Write the final frame WebSocketFrame frame3 = WebSocketFrame.continuationFrame(buffer2, true); webSocket.writeFrame(frame3); } public void example56_1(WebSocket webSocket) { // Send a WebSocket message consisting of a single final text frame: webSocket.writeFinalTextFrame("Geronimo!"); // Send a WebSocket message consisting of a single final binary frame: Buffer buff = Buffer.buffer().appendInt(12).appendString("foo"); webSocket.writeFinalBinaryFrame(buff); } public void example57(WebSocket webSocket) { webSocket.frameHandler(frame -> { System.out.println("Received a frame of size!"); }); } public void example58(Vertx vertx) { HttpClientOptions options = new HttpClientOptions() .setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP) .setHost("localhost").setPort(3128) .setUsername("username").setPassword("secret")); HttpClientAgent client = vertx.createHttpClient(options); } public void example59(Vertx vertx) { HttpClientOptions options = new HttpClientOptions() .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5) .setHost("localhost").setPort(1080) .setUsername("username").setPassword("secret")); HttpClientAgent client = vertx.createHttpClient(options); } public void nonProxyHosts(Vertx vertx) { HttpClientOptions options = new HttpClientOptions() .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5) .setHost("localhost").setPort(1080) .setUsername("username").setPassword("secret")) .addNonProxyHost("*.foo.com") .addNonProxyHost("localhost"); HttpClientAgent client = vertx.createHttpClient(options); } public void perRequestProxyOptions(HttpClient client, ProxyOptions proxyOptions) { client.request(new RequestOptions() .setHost("example.com") .setProxyOptions(proxyOptions)) .compose(request -> request .send() .compose(HttpClientResponse::body)) .onSuccess(body -> { System.out.println("Received response"); }); } public void proxyOptionsConnectTimeout(ProxyOptions proxyOptions) { proxyOptions.setConnectTimeout(Duration.ofSeconds(60)); } public void example60(Vertx vertx) { HttpClientOptions options = new HttpClientOptions() .setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP)); HttpClientAgent client = vertx.createHttpClient(options); client .request(HttpMethod.GET, "ftp://ftp.gnu.org/gnu/") .onComplete(ar -> { if (ar.succeeded()) { HttpClientRequest request = ar.result(); request .send() .onComplete(ar2 -> { if (ar2.succeeded()) { HttpClientResponse response = ar2.result(); System.out.println("Received response with status code " + response.statusCode()); } }); } }); } public void example61(Vertx vertx) { HttpServerOptions options = new HttpServerOptions() .setUseProxyProtocol(true); HttpServer server = vertx.createHttpServer(options); server.requestHandler(request -> { // Print the actual client address provided by the HA proxy protocol instead of the proxy address System.out.println(request.remoteAddress()); // Print the address of the proxy System.out.println(request.localAddress()); }); } public void serversharing(Vertx vertx) { vertx.createHttpServer().requestHandler(request -> { request.response().end("Hello from server " + this); }).listen(8080); } public void serversharingclient(Vertx vertx) { vertx.setPeriodic(100, (l) -> { vertx .createHttpClient() .request(HttpMethod.GET, 8080, "localhost", "/") .onComplete(ar1 -> { if (ar1.succeeded()) { HttpClientRequest request = ar1.result(); request .send() .onComplete(ar2 -> { if (ar2.succeeded()) { HttpClientResponse resp = ar2.result(); resp.bodyHandler(body -> { System.out.println(body.toString("ISO-8859-1")); }); } }); } }); }); } public void randomServersharing(Vertx vertx) { vertx.createHttpServer().requestHandler(request -> { request.response().end("Hello from server " + this); }).listen(-1); } public void setSSLPerRequest(HttpClient client) { client .request(new RequestOptions() .setHost("localhost") .setPort(8080) .setURI("/") .setSsl(true)) .onComplete(ar1 -> { if (ar1.succeeded()) { HttpClientRequest request = ar1.result(); request .send() .onComplete(ar2 -> { if (ar2.succeeded()) { HttpClientResponse response = ar2.result(); System.out.println("Received response with status code " + response.statusCode()); } }); } }); } public static void setIdentityContentEncodingHeader(HttpServerRequest request) { // Disable compression and send an image request.response() .putHeader(HttpHeaders.CONTENT_ENCODING, HttpHeaders.IDENTITY) .sendFile("/path/to/image.jpg"); } public static void setCompressors() { new HttpServerOptions() .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.gzip()) .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.deflate()) .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.brotli()) .addCompressor(io.netty.handler.codec.compression.StandardCompressionOptions.zstd()); } public static void compressorConfig() { GzipOptions gzip = StandardCompressionOptions.gzip(6, 15, 8); } public void serverShutdown(HttpServer server) { server .shutdown() .onSuccess(res -> { System.out.println("Server is now closed"); }); } public void serverShutdownWithAmountOfTime(HttpServer server) { server .shutdown(60, TimeUnit.SECONDS) .onSuccess(res -> { System.out.println("Server is now closed"); }); } public void example9(HttpServer server) { server .close() .onSuccess(res -> { System.out.println("Server is now closed"); }); } public void shutdownHandler(HttpServer server) { server.connectionHandler(conn -> { conn.shutdownHandler(v -> { // Perform clean-up }); }); } public static void httpClientSharing1(Vertx vertx) { HttpClientAgent client = vertx.createHttpClient(new HttpClientOptions().setShared(true)); vertx.deployVerticle(() -> new AbstractVerticle() { @Override public void start() throws Exception { // Use the client } }, new DeploymentOptions().setInstances(4)); } public static void httpClientSharing2(Vertx vertx) { vertx.deployVerticle(() -> new AbstractVerticle() { HttpClientAgent client; @Override public void start() { // Get or create a shared client // this actually creates a lease to the client // when the verticle is undeployed, the lease will be released automaticaly client = vertx.createHttpClient(new HttpClientOptions().setShared(true).setName("my-client")); } }, new DeploymentOptions().setInstances(4)); } public static void httpClientSharing3(Vertx vertx) { vertx.deployVerticle(() -> new AbstractVerticle() { HttpClientAgent client; @Override public void start() { // The client creates and use two event-loops for 4 instances client = vertx.createHttpClient(new HttpClientOptions().setShared(true).setName("my-client"), new PoolOptions().setEventLoopSize(2)); } }, new DeploymentOptions().setInstances(4)); } public static void httpClientSideLoadBalancing(Vertx vertx) { HttpClientAgent client = vertx .httpClientBuilder() .withLoadBalancer(LoadBalancer.ROUND_ROBIN) .build(); } public static void httpClientSideConsistentHashing(Vertx vertx, int servicePort) { HttpClientAgent client = vertx .httpClientBuilder() .withLoadBalancer(LoadBalancer.CONSISTENT_HASHING) .build(); HttpServer server = vertx.createHttpServer() .requestHandler(inboundReq -> { // Get a routing key, in this example we will hash the incoming request host/ip // it could be anything else, e.g. user id, request id, ... String routingKey = inboundReq.remoteAddress().hostAddress(); client.request(new RequestOptions() .setHost("example.com") .setURI("/test") .setRoutingKey(routingKey)) .compose(outboundReq -> outboundReq.send() .expecting(HttpResponseExpectation.SC_OK) .compose(HttpClientResponse::body)) .onComplete(ar -> { if (ar.succeeded()) { Buffer response = ar.result(); } }); }); server.listen(servicePort); } public static void consistentHashingConfiguration() { // Use 10 virtual nodes per server and Power of two choices policy in the absence of a routing key LoadBalancer loadBalancer = LoadBalancer.consistentHashing(10, LoadBalancer.POWER_OF_TWO_CHOICES); } public static void customLoadBalancingPolicy(Vertx vertx) { LoadBalancer loadBalancer = endpoints -> { // Returns an endpoint selector for the given endpoints // a selector is a stateful view of the provided immutable list of endpoints return () -> indexOfEndpoint(endpoints); }; HttpClientAgent client = vertx .httpClientBuilder() .withLoadBalancer(loadBalancer) .build(); } private static int indexOfEndpoint(List<? extends ServerEndpoint> endpoints) { return 0; } private static String getRoutingKey() { return null; } public static void connect(HttpClientAgent client) { HttpConnectOptions connectOptions = new HttpConnectOptions() .setHost("example.com") .setPort(80); Future<HttpClientConnection> fut = client.connect(connectOptions); } public static void connectAndGet(HttpClientConnection connection) { connection .request() .onSuccess(request -> { request.setMethod(HttpMethod.GET); request.setURI("/some-uri"); Future<HttpClientResponse> response = request.send(); }); } }
MyCustomException
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/scalar/string/CIDRMatchFunctionPipe.java
{ "start": 852, "end": 4171 }
class ____ extends Pipe { private final Pipe input; private final List<Pipe> addresses; public CIDRMatchFunctionPipe(Source source, Expression expression, Pipe input, List<Pipe> addresses) { super(source, expression, CollectionUtils.combine(Collections.singletonList(input), addresses)); this.input = input; this.addresses = addresses; } @Override public final Pipe replaceChildren(List<Pipe> newChildren) { return replaceChildren(newChildren.get(0), newChildren.subList(1, newChildren.size())); } @Override public final Pipe resolveAttributes(AttributeResolver resolver) { Pipe newInput = input.resolveAttributes(resolver); boolean same = (newInput == input); ArrayList<Pipe> newAddresses = new ArrayList<Pipe>(addresses.size()); for (Pipe address : addresses) { Pipe newAddress = address.resolveAttributes(resolver); newAddresses.add(newAddress); same = same && (address == newAddress); } return same ? this : replaceChildren(newInput, newAddresses); } @Override public boolean supportedByAggsOnlyQuery() { if (input.supportedByAggsOnlyQuery() == false) { return false; } for (Pipe address : addresses) { if (address.supportedByAggsOnlyQuery() == false) { return false; } } return true; } @Override public boolean resolved() { if (input.resolved() == false) { return false; } for (Pipe address : addresses) { if (address.resolved() == false) { return false; } } return true; } protected CIDRMatchFunctionPipe replaceChildren(Pipe newInput, List<Pipe> newAddresses) { return new CIDRMatchFunctionPipe(source(), expression(), newInput, newAddresses); } @Override public final void collectFields(QlSourceBuilder sourceBuilder) { input.collectFields(sourceBuilder); for (Pipe address : addresses) { address.collectFields(sourceBuilder); } } @Override protected NodeInfo<CIDRMatchFunctionPipe> info() { return NodeInfo.create(this, CIDRMatchFunctionPipe::new, expression(), input, addresses); } @Override public CIDRMatchFunctionProcessor asProcessor() { ArrayList<Processor> processors = new ArrayList<>(addresses.size()); for (Pipe address : addresses) { processors.add(address.asProcessor()); } return new CIDRMatchFunctionProcessor(input.asProcessor(), processors); } public Pipe input() { return input; } public List<Pipe> addresses() { return addresses; } @Override public int hashCode() { return Objects.hash(input(), addresses()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } CIDRMatchFunctionPipe other = (CIDRMatchFunctionPipe) obj; return Objects.equals(input(), other.input()) && Objects.equals(addresses(), other.addresses()); } }
CIDRMatchFunctionPipe
java
apache__rocketmq
proxy/src/test/java/org/apache/rocketmq/proxy/common/RenewStrategyPolicyTest.java
{ "start": 1132, "end": 2314 }
class ____ { private RetryPolicy retryPolicy; private final AtomicInteger times = new AtomicInteger(0); @Before public void before() throws Throwable { this.retryPolicy = new RenewStrategyPolicy(); } @Test public void testNextDelayDuration() { long value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.MINUTES.toMillis(1)); value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.MINUTES.toMillis(3)); value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.MINUTES.toMillis(5)); value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.MINUTES.toMillis(10)); value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.MINUTES.toMillis(30)); value = this.retryPolicy.nextDelayDuration(times.getAndIncrement()); assertEquals(value, TimeUnit.HOURS.toMillis(1)); } @After public void after() { } }
RenewStrategyPolicyTest
java
netty__netty
buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java
{ "start": 200732, "end": 202336 }
class ____ implements GatheringByteChannel { private final ByteArrayOutputStream out = new ByteArrayOutputStream(); private final WritableByteChannel channel = Channels.newChannel(out); private final int limit; TestGatheringByteChannel(int limit) { this.limit = limit; } TestGatheringByteChannel() { this(Integer.MAX_VALUE); } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { long written = 0; for (; offset < length; offset++) { written += write(srcs[offset]); if (written >= limit) { break; } } return written; } @Override public long write(ByteBuffer[] srcs) throws IOException { return write(srcs, 0, srcs.length); } @Override public int write(ByteBuffer src) throws IOException { int oldLimit = src.limit(); if (limit < src.remaining()) { src.limit(src.position() + limit); } int w = channel.write(src); src.limit(oldLimit); return w; } @Override public boolean isOpen() { return channel.isOpen(); } @Override public void close() throws IOException { channel.close(); } public byte[] writtenBytes() { return out.toByteArray(); } } private static final
TestGatheringByteChannel
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2624/Issue2624Mapper.java
{ "start": 1254, "end": 1633 }
class ____ { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
Department
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/PausableDefinition.java
{ "start": 1407, "end": 5190 }
class ____ extends NoOutputDefinition<PausableDefinition> { @XmlTransient private ConsumerListener<?, ?> consumerListenerBean; @XmlTransient private Predicate<?> untilCheckBean; @XmlAttribute(required = true) @Metadata(required = true, javaType = "org.apache.camel.resume.ConsumerListener") private String consumerListener; @XmlAttribute(required = true) @Metadata(required = true, javaType = "java.util.function.Predicate") private String untilCheck; public PausableDefinition() { } protected PausableDefinition(PausableDefinition source) { super(source); this.consumerListenerBean = source.consumerListenerBean; this.untilCheckBean = source.untilCheckBean; this.consumerListener = source.consumerListener; this.untilCheck = source.untilCheck; } @Override public PausableDefinition copyDefinition() { return new PausableDefinition(this); } @Override public String getShortName() { return "pausable"; } @Override public String getLabel() { return "pausable"; } public ConsumerListener<?, ?> getConsumerListenerBean() { return consumerListenerBean; } public void setConsumerListener(ConsumerListener<?, ?> consumerListenerBean) { this.consumerListenerBean = consumerListenerBean; } public String getConsumerListener() { return consumerListener; } public void setConsumerListener(String consumerListener) { this.consumerListener = consumerListener; } public Predicate<?> getUntilCheckBean() { return untilCheckBean; } public void setUntilCheck(Predicate<?> untilCheckBean) { this.untilCheckBean = untilCheckBean; } public String getUntilCheck() { return untilCheck; } public void setUntilCheck(String untilCheck) { this.untilCheck = untilCheck; } // Fluent API // ------------------------------------------------------------------------- /** * Sets the consumer listener to use */ public PausableDefinition consumerListener(String consumerListenerRef) { setConsumerListener(consumerListenerRef); return this; } /** * Sets the consumer listener to use */ public PausableDefinition consumerListener(ConsumerListener<?, ?> consumerListener) { setConsumerListener(consumerListener); return this; } /** * References to a java.util.function.Predicate to use for until checks. * * The predicate is responsible for evaluating whether the processing can resume or not. Such predicate should * return true if the consumption can resume, or false otherwise. The exact point of when the predicate is called is * dependent on the component, and it may be called on either one of the available events. Implementations should * not assume the predicate to be called at any specific point. */ public PausableDefinition untilCheck(String untilCheck) { setUntilCheck(untilCheck); return this; } /** * The java.util.function.Predicate to use for until checks. * * The predicate is responsible for evaluating whether the processing can resume or not. Such predicate should * return true if the consumption can resume, or false otherwise. The exact point of when the predicate is called is * dependent on the component, and it may be called on either one of the available events. Implementations should * not assume the predicate to be called at any specific point. */ public PausableDefinition untilCheck(Predicate<?> untilCheck) { setUntilCheck(untilCheck); return this; } }
PausableDefinition
java
google__guice
core/src/com/google/inject/spi/ModuleSource.java
{ "start": 1107, "end": 2766 }
class ____ of module that this {@link ModuleSource} associated to. */ private final String moduleClassName; /** The parent {@link ModuleSource module source}. */ private final ModuleSource parent; /** * Permit map created by the binder that installed this module. * * <p>The permit map is a binder-scoped object, but it's saved here because these maps have to * outlive the binders that created them in order to be used at injector creation, and there isn't * a 'BinderSource' object. */ private final BindingSourceRestriction.PermitMap permitMap; /** * Creates a new {@link ModuleSource} with a {@literal null} parent. * * @param moduleClass the corresponding module */ ModuleSource(Class<?> moduleClass, BindingSourceRestriction.PermitMap permitMap) { this(null, moduleClass, permitMap); } /** * Creates a new {@link ModuleSource} Object. * * @param parent the parent module {@link ModuleSource source} * @param moduleClass the corresponding module * @param partialCallStack the chunk of call stack that starts from the parent module {@link * Module#configure(Binder) configure(Binder)} call and ends just before the module {@link * Module#configure(Binder) configure(Binder)} method invocation */ private ModuleSource( @Nullable ModuleSource parent, Class<?> moduleClass, BindingSourceRestriction.PermitMap permitMap) { Preconditions.checkNotNull(moduleClass, "module cannot be null."); this.parent = parent; this.moduleClassName = moduleClass.getName(); this.permitMap = permitMap; } /** * Returns the corresponding module
name
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java
{ "start": 78584, "end": 80112 }
class ____ to register a BiPredicate for * @param equals the {@link BiPredicate} to use to compare the given fields * @param type the type of the left element to be compared with the given comparator. * @param otherType the type of the right element to be compared with the given comparator. * * @return this {@link RecursiveComparisonAssert} to chain other methods. * @throws NullPointerException if the given BiPredicate is null. */ public <T, U> SELF withEqualsForTypes(BiPredicate<? super T, ? super U> equals, Class<T> type, Class<U> otherType) { recursiveComparisonConfiguration.registerEqualsForTypes(equals, type, otherType); return myself; } /** * Overrides an error message which would be shown when differences in the given fields while comparison occurred * with the giving error message. * <p> * The fields must be specified from the root object, for example if {@code Foo} has a {@code Bar} field and both * have an {@code id} field, one can register a message for Foo and Bar's {@code id} by calling: * <pre><code class='java'> withErrorMessageForFields("some message", "foo.id", "foo.bar.id")</code></pre> * <p> * Messages registered with this method have precedence over the ones registered with {@link #withErrorMessageForType(String, Class)}. * <p> * In case of {@code null} as message the default error message will be used (See * {@link ComparisonDifference#DEFAULT_TEMPLATE}). * <p> * Example: * <pre><code class='java'> public
type
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDelay.java
{ "start": 968, "end": 1843 }
class ____<T> extends AbstractFlowableWithUpstream<T, T> { final long delay; final TimeUnit unit; final Scheduler scheduler; final boolean delayError; public FlowableDelay(Flowable<T> source, long delay, TimeUnit unit, Scheduler scheduler, boolean delayError) { super(source); this.delay = delay; this.unit = unit; this.scheduler = scheduler; this.delayError = delayError; } @Override protected void subscribeActual(Subscriber<? super T> t) { Subscriber<? super T> downstream; if (delayError) { downstream = t; } else { downstream = new SerializedSubscriber<>(t); } Scheduler.Worker w = scheduler.createWorker(); source.subscribe(new DelaySubscriber<>(downstream, delay, unit, w, delayError)); } static final
FlowableDelay
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/upgrade/HttpUpgradeCheckHeaderMergingTest.java
{ "start": 3432, "end": 3579 }
class ____ { @OnTextMessage public String onMessage(String message) { return "Hola " + message; } } }
Headers
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/RouterWebHdfsMethods.java
{ "start": 6004, "end": 23107 }
class ____ extends NamenodeWebHdfsMethods { private static final Logger LOG = LoggerFactory.getLogger(RouterWebHdfsMethods.class); private @Context HttpServletRequest request; private String method; private String query; private String reqPath; private String remoteAddr; public RouterWebHdfsMethods(@Context HttpServletRequest request) { super(request); this.method = request.getMethod(); this.query = request.getQueryString(); this.reqPath = request.getServletPath(); this.remoteAddr = JspHelper.getRemoteAddr(request); } @Override protected void init(final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final UriFsPathParam path, final HttpOpParam<?> op, final Param<?, ?>... parameters) { super.init(ugi, delegation, username, doAsUser, path, op, parameters); remoteAddr = JspHelper.getRemoteAddr(request); } @Override protected ClientProtocol getRpcClientProtocol() throws IOException { final Router router = getRouter(); final RouterRpcServer routerRpcServer = router.getRpcServer(); if (routerRpcServer == null) { throw new RetriableException("Router is in startup mode"); } return routerRpcServer; } private void reset() { remoteAddr = null; } @Override protected String getRemoteAddr() { return remoteAddr; } @Override protected void queueExternalCall(ExternalCall call) throws IOException, InterruptedException { getRouter().getRpcServer().getServer().queueCall(call); } private Router getRouter() { return (Router)getContext().getAttribute("name.node"); } private static RouterRpcServer getRPCServer(final Router router) throws IOException { final RouterRpcServer routerRpcServer = router.getRpcServer(); if (routerRpcServer == null) { throw new RetriableException("Router is in startup mode"); } return routerRpcServer; } @Override protected Response put( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final PutOpParam op, final DestinationParam destination, final OwnerParam owner, final GroupParam group, final PermissionParam permission, final UnmaskedPermissionParam unmaskedPermission, final OverwriteParam overwrite, final BufferSizeParam bufferSize, final ReplicationParam replication, final BlockSizeParam blockSize, final ModificationTimeParam modificationTime, final AccessTimeParam accessTime, final RenameOptionSetParam renameOptions, final CreateParentParam createParent, final TokenArgumentParam delegationTokenArgument, final AclPermissionParam aclPermission, final XAttrNameParam xattrName, final XAttrValueParam xattrValue, final XAttrSetFlagParam xattrSetFlag, final SnapshotNameParam snapshotName, final OldSnapshotNameParam oldSnapshotName, final ExcludeDatanodesParam exclDatanodes, final CreateFlagParam createFlagParam, final NoRedirectParam noredirectParam, final StoragePolicyParam policyName, final ECPolicyParam ecpolicy, final NameSpaceQuotaParam namespaceQuota, final StorageSpaceQuotaParam storagespaceQuota, final StorageTypeParam storageType ) throws IOException, URISyntaxException { switch(op.getValue()) { case CREATE: { final Router router = getRouter(); final URI uri = redirectURI(router, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, exclDatanodes.getValue(), permission, unmaskedPermission, overwrite, bufferSize, replication, blockSize, createParent, createFlagParam); if (!noredirectParam.getValue()) { return Response.temporaryRedirect(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } } case MKDIRS: case CREATESYMLINK: case RENAME: case SETREPLICATION: case SETOWNER: case SETPERMISSION: case SETTIMES: case RENEWDELEGATIONTOKEN: case CANCELDELEGATIONTOKEN: case MODIFYACLENTRIES: case REMOVEACLENTRIES: case REMOVEDEFAULTACL: case REMOVEACL: case SETACL: case SETXATTR: case REMOVEXATTR: case ALLOWSNAPSHOT: case CREATESNAPSHOT: case RENAMESNAPSHOT: case DISALLOWSNAPSHOT: case SETSTORAGEPOLICY: case ENABLEECPOLICY: case DISABLEECPOLICY: case SATISFYSTORAGEPOLICY: { // Whitelist operations that can handled by NamenodeWebHdfsMethods return super.put(ugi, delegation, username, doAsUser, fullpath, op, destination, owner, group, permission, unmaskedPermission, overwrite, bufferSize, replication, blockSize, modificationTime, accessTime, renameOptions, createParent, delegationTokenArgument, aclPermission, xattrName, xattrValue, xattrSetFlag, snapshotName, oldSnapshotName, exclDatanodes, createFlagParam, noredirectParam, policyName, ecpolicy, namespaceQuota, storagespaceQuota, storageType); } default: throw new UnsupportedOperationException(op + " is not supported"); } } @Override protected Response post( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final PostOpParam op, final ConcatSourcesParam concatSrcs, final BufferSizeParam bufferSize, final ExcludeDatanodesParam excludeDatanodes, final NewLengthParam newLength, final NoRedirectParam noRedirectParam ) throws IOException, URISyntaxException { switch(op.getValue()) { case APPEND: { final Router router = getRouter(); final URI uri = redirectURI(router, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, excludeDatanodes.getValue(), bufferSize); if (!noRedirectParam.getValue()) { return Response.temporaryRedirect(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } } case CONCAT: case TRUNCATE: case UNSETSTORAGEPOLICY: { return super.post(ugi, delegation, username, doAsUser, fullpath, op, concatSrcs, bufferSize, excludeDatanodes, newLength, noRedirectParam); } default: throw new UnsupportedOperationException(op + " is not supported"); } } @Override protected Response get( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final GetOpParam op, final OffsetParam offset, final LengthParam length, final RenewerParam renewer, final BufferSizeParam bufferSize, final List<XAttrNameParam> xattrNames, final XAttrEncodingParam xattrEncoding, final ExcludeDatanodesParam excludeDatanodes, final FsActionParam fsAction, final SnapshotNameParam snapshotName, final OldSnapshotNameParam oldSnapshotName, final SnapshotDiffStartPathParam snapshotDiffStartPath, final SnapshotDiffIndexParam snapshotDiffIndex, final TokenKindParam tokenKind, final TokenServiceParam tokenService, final NoRedirectParam noredirectParam, final StartAfterParam startAfter, final AllUsersParam allUsers ) throws IOException, URISyntaxException { try { final Router router = getRouter(); switch (op.getValue()) { case OPEN: { final URI uri = redirectURI(router, ugi, delegation, username, doAsUser, fullpath, op.getValue(), offset.getValue(), excludeDatanodes.getValue(), offset, length, bufferSize); if (!noredirectParam.getValue()) { return Response.temporaryRedirect(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } } case GETFILECHECKSUM: { final URI uri = redirectURI(router, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, null); if (!noredirectParam.getValue()) { return Response.temporaryRedirect(uri) .type(MediaType.APPLICATION_OCTET_STREAM).build(); } else { final String js = JsonUtil.toJsonString("Location", uri); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } } case GETDELEGATIONTOKEN: case GET_BLOCK_LOCATIONS: case GETFILESTATUS: case LISTSTATUS: case GETCONTENTSUMMARY: case GETHOMEDIRECTORY: case GETACLSTATUS: case GETXATTRS: case LISTXATTRS: case CHECKACCESS: case GETLINKTARGET: case GETFILELINKSTATUS: case GETSTATUS: { return super.get(ugi, delegation, username, doAsUser, fullpath, op, offset, length, renewer, bufferSize, xattrNames, xattrEncoding, excludeDatanodes, fsAction, snapshotName, oldSnapshotName, snapshotDiffStartPath, snapshotDiffIndex, tokenKind, tokenService, noredirectParam, startAfter, allUsers); } default: throw new UnsupportedOperationException(op + " is not supported"); } } finally { reset(); } } /** * Get a URI to redirect an operation to. * @param router Router to check. * @param ugi User group information. * @param delegation Delegation token. * @param username User name. * @param doAsUser Do as user. * @param path Path to check. * @param op Operation to perform. * @param openOffset Offset for opening a file. * @param excludeDatanodes Blocks to exclude. * @param parameters Other parameters. * @return Redirection URI. * @throws URISyntaxException If it cannot parse the URI. * @throws IOException If it cannot create the URI. */ private URI redirectURI(final Router router, final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String path, final HttpOpParam.Op op, final long openOffset, final String excludeDatanodes, final Param<?, ?>... parameters) throws URISyntaxException, IOException { if (!DFSUtil.isValidName(path)) { throw new InvalidPathException(path); } final DatanodeInfo dn = chooseDatanode(router, path, op, openOffset, excludeDatanodes); if (dn == null) { throw new IOException("Failed to find datanode, suggest to check cluster" + " health. excludeDatanodes=" + excludeDatanodes); } final String delegationQuery; if (!UserGroupInformation.isSecurityEnabled()) { // security disabled delegationQuery = Param.toSortedString("&", doAsUser, username); } else if (delegation.getValue() != null) { // client has provided a token delegationQuery = "&" + delegation; } else { // generate a token final Token<? extends TokenIdentifier> t = generateDelegationToken( ugi, ugi.getUserName()); delegationQuery = "&delegation=" + t.encodeToUrlString(); } final String redirectQuery = op.toQueryString() + delegationQuery + "&namenoderpcaddress=" + router.getRouterId() + Param.toSortedString("&", parameters); final String uripath = WebHdfsFileSystem.PATH_PREFIX + path; int port = "http".equals(getScheme()) ? dn.getInfoPort() : dn.getInfoSecurePort(); final URI uri = new URI(getScheme(), null, dn.getHostName(), port, uripath, redirectQuery, null); if (LOG.isTraceEnabled()) { LOG.trace("redirectURI={}", uri); } return uri; } private DatanodeInfo chooseDatanode(final Router router, final String path, final HttpOpParam.Op op, final long openOffset, final String excludeDatanodes) throws IOException { final RouterRpcServer rpcServer = getRPCServer(router); DatanodeInfo[] dns = {}; String resolvedNs = ""; try { dns = rpcServer.getCachedDatanodeReport(DatanodeReportType.LIVE); } catch (IOException e) { LOG.error("Cannot get the datanodes from the RPC server", e); } if (op == PutOpParam.Op.CREATE) { try { if (rpcServer.isAsync()) { rpcServer.getCreateLocation(path); RemoteLocation remoteLocation = syncReturn(RemoteLocation.class); resolvedNs = remoteLocation.getNameserviceId(); } else { resolvedNs = rpcServer.getCreateLocation(path).getNameserviceId(); } } catch (Exception e) { LOG.error("Cannot get the name service " + "to create file for path {} ", path, e); } } HashSet<Node> excludes = new HashSet<Node>(); Collection<String> collection = getTrimmedStringCollection(excludeDatanodes); for (DatanodeInfo dn : dns) { String ns = getNsFromDataNodeNetworkLocation(dn.getNetworkLocation()); if (collection.contains(dn.getName())) { excludes.add(dn); } else if (op == PutOpParam.Op.CREATE && !ns.equals(resolvedNs)) { // for CREATE, the dest dn should be in the resolved ns excludes.add(dn); } } if (op == GetOpParam.Op.OPEN || op == PostOpParam.Op.APPEND || op == GetOpParam.Op.GETFILECHECKSUM) { // Choose a datanode containing a replica final ClientProtocol cp = getRpcClientProtocol(); final HdfsFileStatus status = cp.getFileInfo(path); if (status == null) { throw new FileNotFoundException("File " + path + " not found."); } final long len = status.getLen(); if (op == GetOpParam.Op.OPEN) { if (openOffset < 0L || (openOffset >= len && len > 0)) { throw new IOException("Offset=" + openOffset + " out of the range [0, " + len + "); " + op + ", path=" + path); } } if (len > 0) { final long offset = op == GetOpParam.Op.OPEN ? openOffset : len - 1; final LocatedBlocks locations = cp.getBlockLocations(path, offset, 1); final int count = locations.locatedBlockCount(); if (count > 0) { LocatedBlock location0 = locations.get(0); return bestNode(location0.getLocations(), excludes); } } } return getRandomDatanode(dns, excludes); } /** * Get the nameservice info from datanode network location. * @param location network location with format `/ns0/rack1` * @return nameservice this datanode is in */ @VisibleForTesting public static String getNsFromDataNodeNetworkLocation(String location) { // network location should be in the format of /ns/rack Pattern pattern = Pattern.compile("^/([^/]*)/"); Matcher matcher = pattern.matcher(location); if (matcher.find()) { return matcher.group(1); } return ""; } /** * Get a random Datanode from a subcluster. * @param dns Nodes to be chosen from. * @param excludes Nodes to be excluded from. * @return Random datanode from a particular subluster. */ private static DatanodeInfo getRandomDatanode( final DatanodeInfo[] dns, final HashSet<Node> excludes) { DatanodeInfo dn = null; if (dns == null) { return dn; } int numDNs = dns.length; int availableNodes = 0; if (excludes.isEmpty()) { availableNodes = numDNs; } else { for (DatanodeInfo di : dns) { if (!excludes.contains(di)) { availableNodes++; } } } // Return a random one from the list if (availableNodes > 0) { while (dn == null || excludes.contains(dn)) { Random rnd = new Random(); int idx = rnd.nextInt(numDNs); dn = dns[idx]; } } return dn; } /** * Generate the credentials for this request. * @param ugi User group information. * @param renewer Who is asking for the renewal. * @return Credentials holding delegation token. * @throws IOException If it cannot create the credentials. */ @Override public Credentials createCredentials( final UserGroupInformation ugi, final String renewer) throws IOException { final Router router = (Router)getContext().getAttribute("name.node"); final Credentials c = RouterSecurityManager.createCredentials(router, ugi, renewer != null? renewer: ugi.getShortUserName()); return c; } }
RouterWebHdfsMethods
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/range/AbstractRangeBuilder.java
{ "start": 1279, "end": 5612 }
class ____<AB extends AbstractRangeBuilder<AB, R>, R extends Range> extends ValuesSourceAggregationBuilder< AB> { protected final InternalRange.Factory<?, ?> rangeFactory; protected List<R> ranges = new ArrayList<>(); protected boolean keyed = false; protected AbstractRangeBuilder(String name, InternalRange.Factory<?, ?> rangeFactory) { super(name); this.rangeFactory = rangeFactory; } protected AbstractRangeBuilder( AbstractRangeBuilder<AB, R> clone, AggregatorFactories.Builder factoriesBuilder, Map<String, Object> metadata ) { super(clone, factoriesBuilder, metadata); this.rangeFactory = clone.rangeFactory; this.ranges = new ArrayList<>(clone.ranges); this.keyed = clone.keyed; } /** * Read from a stream. */ protected AbstractRangeBuilder(StreamInput in, InternalRange.Factory<?, ?> rangeFactory, Writeable.Reader<R> rangeReader) throws IOException { super(in); this.rangeFactory = rangeFactory; ranges = in.readCollectionAsList(rangeReader); keyed = in.readBoolean(); } @Override public boolean supportsSampling() { return true; } @Override protected ValuesSourceType defaultValueSourceType() { // Copied over from the old targetValueType setting. Not sure what cases this is still relevant for. --Tozzi 2020-01-13 return rangeFactory.getValueSourceType(); } /** * Resolve any strings in the ranges so we have a number value for the from * and to of each range. The ranges are also sorted before being returned. */ protected Range[] processRanges(Function<Range, Range> rangeProcessor) { Range[] ranges = new Range[this.ranges.size()]; for (int i = 0; i < ranges.length; i++) { ranges[i] = rangeProcessor.apply(this.ranges.get(i)); } sortRanges(ranges); return ranges; } /** * Sort the provided ranges in place. */ static void sortRanges(final Range[] ranges) { new InPlaceMergeSorter() { @Override protected void swap(int i, int j) { final Range tmp = ranges[i]; ranges[i] = ranges[j]; ranges[j] = tmp; } @Override protected int compare(int i, int j) { int cmp = Double.compare(ranges[i].from, ranges[j].from); if (cmp == 0) { cmp = Double.compare(ranges[i].to, ranges[j].to); } return cmp; } }.sort(0, ranges.length); } @Override protected void innerWriteTo(StreamOutput out) throws IOException { out.writeCollection(ranges); out.writeBoolean(keyed); } @SuppressWarnings("unchecked") public AB addRange(R range) { if (range == null) { throw new IllegalArgumentException("[range] must not be null: [" + name + "]"); } ranges.add(range); return (AB) this; } public List<R> ranges() { return ranges; } @SuppressWarnings("unchecked") public AB keyed(boolean keyed) { this.keyed = keyed; return (AB) this; } public boolean keyed() { return keyed; } @Override public BucketCardinality bucketCardinality() { return BucketCardinality.MANY; } @Override protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { builder.field(RangeAggregator.RANGES_FIELD.getPreferredName(), ranges); builder.field(RangeAggregator.KEYED_FIELD.getPreferredName(), keyed); return builder; } @Override public int hashCode() { return Objects.hash(super.hashCode(), ranges, keyed); } @Override @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; AbstractRangeBuilder<AB, R> other = (AbstractRangeBuilder<AB, R>) obj; return Objects.equals(ranges, other.ranges) && Objects.equals(keyed, other.keyed); } }
AbstractRangeBuilder
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java
{ "start": 1283, "end": 4129 }
class ____ { private final LogUserAdvice logAdvice = new LogUserAdvice(); private final GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); @Test void manualGroovyBeanWithUnconditionalPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); testAdvice(new DefaultPointcutAdvisor(logAdvice), logAdvice, target, "GroovyServiceImpl"); } @Test void manualGroovyBeanWithStaticPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(String.format("execution(* %s.TestService+.*(..))", ClassUtils.getPackageName(getClass()))); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", true); } @Test void manualGroovyBeanWithDynamicPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", false); } @Test void manualGroovyBeanWithDynamicPointcutProxyTargetClass() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", true); } private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message) { testAdvice(advisor, logAdvice, target, message, false); } private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message, boolean proxyTargetClass) { logAdvice.reset(); ProxyFactory factory = new ProxyFactory(target); factory.setProxyTargetClass(proxyTargetClass); factory.addAdvisor(advisor); TestService bean = (TestService) factory.getProxy(); assertThat(logAdvice.getCountThrows()).isEqualTo(0); assertThatExceptionOfType(TestException.class).isThrownBy( bean::sayHello) .withMessage(message); assertThat(logAdvice.getCountThrows()).isEqualTo(1); } }
GroovyAspectTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/component/AttributeOverridingTest.java
{ "start": 794, "end": 1946 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope){ scope.inTransaction( session -> { Publisher ebookPublisher = new Publisher(); ebookPublisher.setName( "eprint" ); Publisher paperPublisher = new Publisher(); paperPublisher.setName( "paperbooks" ); Book book = new Book(); book.setTitle( "Hibernate" ); book.setAuthor( "Steve" ); book.setEbookPublisher( ebookPublisher ); book.setPaperBackPublisher( paperPublisher ); session.persist( book ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope){ scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testGet(SessionFactoryScope scope){ scope.inTransaction( session -> { session.createQuery( "from Book" ).list(); } ); } @Entity(name = "Book") @AttributeOverrides({ @AttributeOverride( name = "ebookPublisher.name", column = @Column(name = "ebook_publisher_name") ), @AttributeOverride( name = "paperBackPublisher.name", column = @Column(name = "paper_back_publisher_name") ) }) public static
AttributeOverridingTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java
{ "start": 3016, "end": 3336 }
class ____ { // is a pojo public ComplexNestedClass complex; // is a pojo private int count; // is a BasicType public WC() {} public int getCount() { return count; } public void setCount(int c) { this.count = c; } } public static
WC
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/http/RequestBasedTaskRunner.java
{ "start": 1017, "end": 2491 }
class ____ { private final Runnable command; private final ThreadPool threadPool; private final String executorServiceName; private final AtomicInteger loopCount = new AtomicInteger(0); private final AtomicBoolean isRunning = new AtomicBoolean(true); RequestBasedTaskRunner(Runnable command, ThreadPool threadPool, String executorServiceName) { this.command = Objects.requireNonNull(command); this.threadPool = Objects.requireNonNull(threadPool); this.executorServiceName = Objects.requireNonNull(executorServiceName); } /** * If there is currently a thread running in a loop, it should pick up this new request. * If not, check if this thread is one of ours and reuse it. * Else, offload to a new thread so we do not block another threadpool's thread. */ public void requestNextRun() { if (isRunning.get() && loopCount.getAndIncrement() == 0) { var currentThreadPool = EsExecutors.executorName(Thread.currentThread()); if (executorServiceName.equalsIgnoreCase(currentThreadPool)) { run(); } else { threadPool.executor(executorServiceName).execute(this::run); } } } public void cancel() { isRunning.set(false); } private void run() { do { command.run(); } while (isRunning.get() && loopCount.decrementAndGet() > 0); } }
RequestBasedTaskRunner
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/aggregate/window/combines/GlobalAggCombiner.java
{ "start": 5305, "end": 7283 }
class ____ implements RecordsCombiner.Factory { private static final long serialVersionUID = 1L; private final GeneratedNamespaceAggsHandleFunction<Long> genLocalAggsHandler; private final GeneratedNamespaceAggsHandleFunction<Long> genGlobalAggsHandler; public Factory( GeneratedNamespaceAggsHandleFunction<Long> genLocalAggsHandler, GeneratedNamespaceAggsHandleFunction<Long> genGlobalAggsHandler) { this.genLocalAggsHandler = genLocalAggsHandler; this.genGlobalAggsHandler = genGlobalAggsHandler; } @Override public RecordsCombiner createRecordsCombiner( RuntimeContext runtimeContext, WindowTimerService<Long> timerService, KeyedStateBackend<RowData> stateBackend, WindowState<Long> windowState, boolean isEventTime) throws Exception { final NamespaceAggsHandleFunction<Long> localAggregator = genLocalAggsHandler.newInstance(runtimeContext.getUserCodeClassLoader()); final NamespaceAggsHandleFunction<Long> globalAggregator = genGlobalAggsHandler.newInstance(runtimeContext.getUserCodeClassLoader()); localAggregator.open( new PerWindowStateDataViewStore( stateBackend, LongSerializer.INSTANCE, runtimeContext)); globalAggregator.open( new PerWindowStateDataViewStore( stateBackend, LongSerializer.INSTANCE, runtimeContext)); WindowValueState<Long> windowValueState = (WindowValueState<Long>) windowState; return new GlobalAggCombiner( timerService, stateBackend::setCurrentKey, windowValueState, localAggregator, globalAggregator); } } }
Factory
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/GenericValuesDeserTest.java
{ "start": 447, "end": 498 }
class ____ { static abstract
GenericValuesDeserTest
java
dropwizard__dropwizard
dropwizard-logging/src/main/java/io/dropwizard/logging/common/layout/LayoutFactory.java
{ "start": 240, "end": 352 }
interface ____ building Logback {@link PatternLayoutBase} layouts * @param <E> The type of log event */ public
for
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/ResourceStreamLocator.java
{ "start": 354, "end": 639 }
interface ____ { /** * Locate the named resource * * @param resourceName The resource name to locate * * @return The located resource's InputStream, or {@code null} if no match found */ @Nullable InputStream locateResourceStream(String resourceName); }
ResourceStreamLocator
java
google__guava
android/guava/src/com/google/common/collect/ContiguousSet.java
{ "start": 3400, "end": 10101 }
class ____, we are allowed to throw CCE if necessary empty = Range.compareOrThrow(afterLower, beforeUpper) > 0; } return empty ? new EmptyContiguousSet<C>(domain) : new RegularContiguousSet<C>(effectiveRange, domain); } /** * Returns a nonempty contiguous set containing all {@code int} values from {@code lower} * (inclusive) to {@code upper} (inclusive). (These are the same values contained in {@code * Range.closed(lower, upper)}.) * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @since 23.0 */ public static ContiguousSet<Integer> closed(int lower, int upper) { return create(Range.closed(lower, upper), DiscreteDomain.integers()); } /** * Returns a nonempty contiguous set containing all {@code long} values from {@code lower} * (inclusive) to {@code upper} (inclusive). (These are the same values contained in {@code * Range.closed(lower, upper)}.) * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @since 23.0 */ public static ContiguousSet<Long> closed(long lower, long upper) { return create(Range.closed(lower, upper), DiscreteDomain.longs()); } /** * Returns a contiguous set containing all {@code int} values from {@code lower} (inclusive) to * {@code upper} (exclusive). If the endpoints are equal, an empty set is returned. (These are the * same values contained in {@code Range.closedOpen(lower, upper)}.) * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @since 23.0 */ public static ContiguousSet<Integer> closedOpen(int lower, int upper) { return create(Range.closedOpen(lower, upper), DiscreteDomain.integers()); } /** * Returns a contiguous set containing all {@code long} values from {@code lower} (inclusive) to * {@code upper} (exclusive). If the endpoints are equal, an empty set is returned. (These are the * same values contained in {@code Range.closedOpen(lower, upper)}.) * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @since 23.0 */ public static ContiguousSet<Long> closedOpen(long lower, long upper) { return create(Range.closedOpen(lower, upper), DiscreteDomain.longs()); } final DiscreteDomain<C> domain; ContiguousSet(DiscreteDomain<C> domain) { super(Ordering.natural()); this.domain = domain; } @Override public ContiguousSet<C> headSet(C toElement) { return headSetImpl(checkNotNull(toElement), false); } /** * @since 12.0 */ @GwtIncompatible // NavigableSet @Override public ContiguousSet<C> headSet(C toElement, boolean inclusive) { return headSetImpl(checkNotNull(toElement), inclusive); } @Override public ContiguousSet<C> subSet(C fromElement, C toElement) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, true, toElement, false); } /** * @since 12.0 */ @GwtIncompatible // NavigableSet @Override public ContiguousSet<C> subSet( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator().compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); } @Override public ContiguousSet<C> tailSet(C fromElement) { return tailSetImpl(checkNotNull(fromElement), true); } /** * @since 12.0 */ @GwtIncompatible // NavigableSet @Override public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) { return tailSetImpl(checkNotNull(fromElement), inclusive); } /* * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation. */ @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT. abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive); @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT. abstract ContiguousSet<C> subSetImpl( C fromElement, boolean fromInclusive, C toElement, boolean toInclusive); @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT. abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive); /** * Returns the set of values that are contained in both this set and the other. * * <p>This method should always be used instead of {@link Sets#intersection} for {@link * ContiguousSet} instances. */ public abstract ContiguousSet<C> intersection(ContiguousSet<C> other); /** * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values * contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(); /** * Returns the minimal range with the given boundary types for which all values in this set are * {@linkplain Range#contains(Comparable) contained} within the range. * * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN} * is requested for a domain minimum or maximum. For example, if {@code set} was created from the * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return {@code * [1..∞)}. * * @throws NoSuchElementException if this set is empty */ public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType); @Override @GwtIncompatible // NavigableSet ImmutableSortedSet<C> createDescendingSet() { return new DescendingImmutableSortedSet<>(this); } /** Returns a shorthand representation of the contents such as {@code "[1..100]"}. */ @Override public String toString() { return range().toString(); } /** * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code * ContiguousSet}. * * @throws UnsupportedOperationException always * @deprecated Use {@link #create}. */ @Deprecated @DoNotCall("Always throws UnsupportedOperationException") public static <E> ImmutableSortedSet.Builder<E> builder() { throw new UnsupportedOperationException(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @J2ktIncompatible // serialization @Override @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } }
spec
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/optionallong/OptionalLongAssert_hasValue_Test.java
{ "start": 1189, "end": 2567 }
class ____ { @Test void should_fail_when_OptionalLong_is_null() { // GIVEN OptionalLong nullActual = null; // THEN assertThatAssertionErrorIsThrownBy(() -> assertThat(nullActual).hasValue(10L)).withMessage(actualIsNull()); } @Test void should_pass_if_OptionalLong_has_expected_value() { assertThat(OptionalLong.of(10L)).hasValue(10L); } @Test void should_fail_if_OptionalLong_does_not_have_expected_value() { // GIVEN OptionalLong actual = OptionalLong.of(5L); long expectedValue = 10L; // WHEN AssertionFailedError error = catchThrowableOfType(AssertionFailedError.class, () -> assertThat(actual).hasValue(expectedValue)); // THEN assertThat(error).hasMessage(shouldContain(actual, expectedValue).create()); assertThat(error.getActual().getStringRepresentation()).isEqualTo(String.valueOf(actual.getAsLong())); assertThat(error.getExpected().getStringRepresentation()).isEqualTo(String.valueOf(expectedValue)); } @Test void should_fail_if_OptionalLong_is_empty() { // GIVEN long expectedValue = 10L; // WHEN Throwable error = catchThrowable(() -> assertThat(OptionalLong.empty()).hasValue(expectedValue)); // THEN assertThat(error).hasMessage(shouldContain(expectedValue).create()); } }
OptionalLongAssert_hasValue_Test
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
{ "start": 27789, "end": 27870 }
class ____ { public static Object create() { return null; } } }
NullFactory
java
elastic__elasticsearch
modules/aggregations/src/main/java/org/elasticsearch/aggregations/bucket/histogram/AutoDateHistogramAggregator.java
{ "start": 17776, "end": 31035 }
class ____ extends AutoDateHistogramAggregator { /** * An array of prepared roundings in the same order as * {@link #roundingInfos}. The 0th entry is prepared initially, * and other entries are null until first needed. */ private final Rounding.Prepared[] preparedRoundings; /** * Map from value to bucket ordinals. * <p> * It is important that this is the exact subtype of * {@link LongKeyedBucketOrds} so that the JVM can make a monomorphic * call to {@link LongKeyedBucketOrds#add(long, long)} in the tight * inner loop of {@link LeafBucketCollector#collect(int, long)}. */ private LongKeyedBucketOrds.FromMany bucketOrds; /** * The index of the rounding that each {@code owningBucketOrd} is * currently using. * <p> * During collection we use overestimates for how much buckets are save * by bumping to the next rounding index. So we end up bumping less * aggressively than a "perfect" algorithm. That is fine because we * correct the error when we merge the buckets together. In particular, * on final reduce we bump the rounding until it we appropriately * cover the date range across all of the results returned by all of * the {@link AutoDateHistogramAggregator}s. */ private ByteArray roundingIndices; /** * The minimum key per {@code owningBucketOrd}. */ private LongArray mins; /** * The max key per {@code owningBucketOrd}. */ private LongArray maxes; /** * An underestimate of the number of buckets that are "live" in the * current rounding for each {@code owningBucketOrdinal}. */ private IntArray liveBucketCountUnderestimate; /** * An over estimate of the number of wasted buckets. When this gets * too high we {@link #rebucket} which sets it to 0. */ private long wastedBucketsOverestimate = 0; /** * The next {@link #wastedBucketsOverestimate} that will trigger a * {@link #rebucket() rebucketing}. */ private long nextRebucketAt = 1000; // TODO this could almost certainly start higher when asMultiBucketAggregator is gone /** * The number of times the aggregator had to {@link #rebucket()} the * results. We keep this just to report to the profiler. */ private int rebucketCount = 0; FromMany( String name, AggregatorFactories factories, int targetBuckets, RoundingInfo[] roundingInfos, ValuesSourceConfig valuesSourceConfig, AggregationContext context, Aggregator parent, Map<String, Object> metadata ) throws IOException { super(name, factories, targetBuckets, roundingInfos, valuesSourceConfig, context, parent, metadata); assert roundingInfos.length < 127 : "Rounding must fit in a signed byte"; roundingIndices = bigArrays().newByteArray(1, true); mins = bigArrays().newLongArray(1, false); mins.set(0, Long.MAX_VALUE); maxes = bigArrays().newLongArray(1, false); maxes.set(0, Long.MIN_VALUE); preparedRoundings = new Rounding.Prepared[roundingInfos.length]; // Prepare the first rounding because we know we'll need it. preparedRoundings[0] = prepareRounding(0); bucketOrds = new LongKeyedBucketOrds.FromMany(bigArrays()); liveBucketCountUnderestimate = bigArrays().newIntArray(1, true); } @Override protected LeafBucketCollector getLeafCollector(SortedNumericLongValues values, LeafBucketCollector sub) { return new LeafBucketCollectorBase(sub, values) { @Override public void collect(int doc, long owningBucketOrd) throws IOException { if (false == values.advanceExact(doc)) { return; } int valuesCount = values.docValueCount(); long previousRounded = Long.MIN_VALUE; int roundingIdx = roundingIndexFor(owningBucketOrd); for (int i = 0; i < valuesCount; ++i) { long value = values.nextValue(); long rounded = preparedRoundings[roundingIdx].round(value); assert rounded >= previousRounded; if (rounded == previousRounded) { continue; } roundingIdx = collectValue(owningBucketOrd, roundingIdx, doc, rounded, sub); previousRounded = rounded; } } }; } @Override protected LeafBucketCollector getLeafCollector(LongValues values, LeafBucketCollector sub) { return new LeafBucketCollectorBase(sub, values) { @Override public void collect(int doc, long owningBucketOrd) throws IOException { if (values.advanceExact(doc)) { final int roundingIdx = roundingIndexFor(owningBucketOrd); final long rounded = preparedRoundings[roundingIdx].round(values.longValue()); collectValue(owningBucketOrd, roundingIdx, doc, rounded, sub); } } }; } private int collectValue(long owningBucketOrd, int roundingIdx, int doc, long rounded, LeafBucketCollector sub) throws IOException { long bucketOrd = bucketOrds.add(owningBucketOrd, rounded); if (bucketOrd < 0) { // already seen bucketOrd = -1 - bucketOrd; collectExistingBucket(sub, doc, bucketOrd); return roundingIdx; } collectBucket(sub, doc, bucketOrd); liveBucketCountUnderestimate = bigArrays().grow(liveBucketCountUnderestimate, owningBucketOrd + 1); int estimatedBucketCount = liveBucketCountUnderestimate.increment(owningBucketOrd, 1); return increaseRoundingIfNeeded(owningBucketOrd, estimatedBucketCount, rounded, roundingIdx); } /** * Increase the rounding of {@code owningBucketOrd} using * estimated, bucket counts, {@link FromMany#rebucket() rebucketing} the all * buckets if the estimated number of wasted buckets is too high. */ private int increaseRoundingIfNeeded(long owningBucketOrd, int oldEstimatedBucketCount, long newKey, int oldRounding) { if (oldRounding >= roundingInfos.length - 1) { return oldRounding; } if (mins.size() < owningBucketOrd + 1) { long oldSize = mins.size(); mins = bigArrays().grow(mins, owningBucketOrd + 1); mins.fill(oldSize, mins.size(), Long.MAX_VALUE); } if (maxes.size() < owningBucketOrd + 1) { long oldSize = maxes.size(); maxes = bigArrays().grow(maxes, owningBucketOrd + 1); maxes.fill(oldSize, maxes.size(), Long.MIN_VALUE); } long min = Math.min(mins.get(owningBucketOrd), newKey); mins.set(owningBucketOrd, min); long max = Math.max(maxes.get(owningBucketOrd), newKey); maxes.set(owningBucketOrd, max); if (oldEstimatedBucketCount <= targetBuckets * roundingInfos[oldRounding].getMaximumInnerInterval() && max - min <= targetBuckets * roundingInfos[oldRounding].getMaximumRoughEstimateDurationMillis()) { return oldRounding; } long oldRoughDuration = roundingInfos[oldRounding].roughEstimateDurationMillis; int newRounding = oldRounding; int newEstimatedBucketCount; do { newRounding++; double ratio = (double) oldRoughDuration / (double) roundingInfos[newRounding].getRoughEstimateDurationMillis(); newEstimatedBucketCount = (int) Math.ceil(oldEstimatedBucketCount * ratio); } while (newRounding < roundingInfos.length - 1 && (newEstimatedBucketCount > targetBuckets * roundingInfos[newRounding].getMaximumInnerInterval() || max - min > targetBuckets * roundingInfos[newRounding].getMaximumRoughEstimateDurationMillis())); setRounding(owningBucketOrd, newRounding); mins.set(owningBucketOrd, preparedRoundings[newRounding].round(mins.get(owningBucketOrd))); maxes.set(owningBucketOrd, preparedRoundings[newRounding].round(maxes.get(owningBucketOrd))); wastedBucketsOverestimate += oldEstimatedBucketCount - newEstimatedBucketCount; if (wastedBucketsOverestimate > nextRebucketAt) { rebucket(); // Bump the threshold for the next rebucketing wastedBucketsOverestimate = 0; nextRebucketAt *= 2; } else { liveBucketCountUnderestimate.set(owningBucketOrd, newEstimatedBucketCount); } return newRounding; } private void rebucket() { rebucketCount++; LongKeyedBucketOrds oldOrds = bucketOrds; boolean success = false; try { long[] mergeMap = new long[Math.toIntExact(oldOrds.size())]; bucketOrds = new LongKeyedBucketOrds.FromMany(bigArrays()); success = true; long maxOwning = oldOrds.maxOwningBucketOrd(); for (long owningBucketOrd = 0; owningBucketOrd <= maxOwning; owningBucketOrd++) { /* * Check for cancelation during this tight loop as it can take a while and the standard * cancelation checks don't run during the loop. Becuase it's a tight loop. */ if (context.isCancelled()) { throw new TaskCancelledException("cancelled"); } LongKeyedBucketOrds.BucketOrdsEnum ordsEnum = oldOrds.ordsEnum(owningBucketOrd); Rounding.Prepared preparedRounding = preparedRoundings[roundingIndexFor(owningBucketOrd)]; while (ordsEnum.next()) { long oldKey = ordsEnum.value(); long newKey = preparedRounding.round(oldKey); long newBucketOrd = bucketOrds.add(owningBucketOrd, newKey); mergeMap[(int) ordsEnum.ord()] = newBucketOrd >= 0 ? newBucketOrd : -1 - newBucketOrd; } liveBucketCountUnderestimate = bigArrays().grow(liveBucketCountUnderestimate, owningBucketOrd + 1); liveBucketCountUnderestimate.set(owningBucketOrd, Math.toIntExact(bucketOrds.bucketsInOrd(owningBucketOrd))); } merge(mergeMap, bucketOrds.size()); } finally { if (success) { oldOrds.close(); } } } @Override public InternalAggregation[] buildAggregations(LongArray owningBucketOrds) throws IOException { /* * Rebucket before building the aggregation to build as small as result * as possible. * * TODO it'd be faster if we could apply the merging on the fly as we * replay the hits and build the buckets. How much faster is not clear, * but it does have the advantage of only touching the buckets that we * want to collect. */ rebucket(); return buildAggregations(bucketOrds, this::roundingIndexFor, owningBucketOrds); } @Override public void collectDebugInfo(BiConsumer<String, Object> add) { super.collectDebugInfo(add); add.accept("surviving_buckets", bucketOrds.size()); add.accept("wasted_buckets_overestimate", wastedBucketsOverestimate); add.accept("next_rebucket_at", nextRebucketAt); add.accept("rebucket_count", rebucketCount); } private void setRounding(long owningBucketOrd, int newRounding) { roundingIndices = bigArrays().grow(roundingIndices, owningBucketOrd + 1); roundingIndices.set(owningBucketOrd, (byte) newRounding); if (preparedRoundings[newRounding] == null) { preparedRoundings[newRounding] = prepareRounding(newRounding); } } private int roundingIndexFor(long owningBucketOrd) { return owningBucketOrd < roundingIndices.size() ? roundingIndices.get(owningBucketOrd) : 0; } @Override public void doClose() { Releasables.close(bucketOrds, roundingIndices, mins, maxes, liveBucketCountUnderestimate); } } }
FromMany
java
netty__netty
transport-sctp/src/test/java/io/netty/handler/codec/sctp/SctpMessageCompletionHandlerTest.java
{ "start": 1142, "end": 2038 }
class ____ { @Test public void testFragmentsReleased() { EmbeddedChannel channel = new EmbeddedChannel(new SctpMessageCompletionHandler()); ByteBuf buffer = Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }); ByteBuf buffer2 = Unpooled.wrappedBuffer(new byte[] { 1, 2, 3, 4 }); SctpMessage message = new SctpMessage(new TestMessageInfo(false, 1), buffer); assertFalse(channel.writeInbound(message)); assertEquals(1, buffer.refCnt()); SctpMessage message2 = new SctpMessage(new TestMessageInfo(false, 2), buffer2); assertFalse(channel.writeInbound(message2)); assertEquals(1, buffer2.refCnt()); assertFalse(channel.finish()); assertEquals(0, buffer.refCnt()); assertEquals(0, buffer2.refCnt()); } @SuppressForbidden(reason = "test-only") private final
SctpMessageCompletionHandlerTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 41354, "end": 41995 }
class ____ { public final Object mu = new Object(); @GuardedBy("mu") int x = 1; { new Object() { void f() { synchronized (mu) { x++; } } }; } } """) .doTest(); } @Ignore("b/26834754") // fix resolution of qualified type names @Test public void qualifiedType() { compilationHelper .addSourceLines( "lib/Lib.java", """ package lib; public
Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/decorator/jsr330/annotatewith/Jsr330AnnotateWithMapperDecorator.java
{ "start": 575, "end": 1045 }
class ____ implements Jsr330AnnotateWithMapper { @Inject @Named("org.mapstruct.ap.test.decorator.jsr330.annotatewith.Jsr330AnnotateWithMapperImpl_") private Jsr330AnnotateWithMapper delegate; @Override public PersonDto personToPersonDto(Person person) { PersonDto dto = delegate.personToPersonDto( person ); dto.setName( person.getFirstName() + " " + person.getLastName() ); return dto; } }
Jsr330AnnotateWithMapperDecorator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MockitoDoSetupTest.java
{ "start": 1178, "end": 1544 }
class ____ { public int test(Test test) { Mockito.doReturn(1).when(test).test(null); return 1; } } """) .addOutputLines( "Test.java", """ import static org.mockito.Mockito.when; import org.mockito.Mockito; public
Test
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/onetomany/detached/ListJoinColumnBidirectionalRefEdEntity.java
{ "start": 688, "end": 2516 }
class ____ { @Id @GeneratedValue private Integer id; private String data; @ManyToOne @JoinColumn(name = "some_join_column", insertable = false, updatable = false) private ListJoinColumnBidirectionalRefIngEntity owner; public ListJoinColumnBidirectionalRefEdEntity() { } public ListJoinColumnBidirectionalRefEdEntity( Integer id, String data, ListJoinColumnBidirectionalRefIngEntity owner) { this.id = id; this.data = data; this.owner = owner; } public ListJoinColumnBidirectionalRefEdEntity(String data, ListJoinColumnBidirectionalRefIngEntity owner) { this.data = data; this.owner = owner; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public ListJoinColumnBidirectionalRefIngEntity getOwner() { return owner; } public void setOwner(ListJoinColumnBidirectionalRefIngEntity owner) { this.owner = owner; } public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof ListJoinColumnBidirectionalRefEdEntity) ) { return false; } ListJoinColumnBidirectionalRefEdEntity that = (ListJoinColumnBidirectionalRefEdEntity) o; if ( data != null ? !data.equals( that.data ) : that.data != null ) { return false; } //noinspection RedundantIfStatement if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } return true; } public int hashCode() { int result; result = (id != null ? id.hashCode() : 0); result = 31 * result + (data != null ? data.hashCode() : 0); return result; } public String toString() { return "ListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; } }
ListJoinColumnBidirectionalRefEdEntity
java
apache__flink
flink-metrics/flink-metrics-jmx/src/test/java/org/apache/flink/metrics/jmx/JMXReporterTest.java
{ "start": 1984, "end": 11512 }
class ____ { private static final Map<String, String> variables; private static final MetricGroup metricGroup; static { variables = new HashMap<>(); variables.put("<host>", "localhost"); metricGroup = TestMetricGroup.newBuilder() .setLogicalScopeFunction((characterFilter, character) -> "taskmanager") .setVariables(variables) .build(); } @AfterEach void shutdownService() throws IOException { JMXService.stopInstance(); } @Test void testReplaceInvalidChars() { assertThat(JMXReporter.replaceInvalidChars("")).isEqualTo(""); assertThat(JMXReporter.replaceInvalidChars("abc")).isEqualTo("abc"); assertThat(JMXReporter.replaceInvalidChars("abc\"")).isEqualTo("abc"); assertThat(JMXReporter.replaceInvalidChars("\"abc")).isEqualTo("abc"); assertThat(JMXReporter.replaceInvalidChars("\"abc\"")).isEqualTo("abc"); assertThat(JMXReporter.replaceInvalidChars("\"a\"b\"c\"")).isEqualTo("abc"); assertThat(JMXReporter.replaceInvalidChars("\"\"\"\"")).isEqualTo(""); assertThat(JMXReporter.replaceInvalidChars(" ")).isEqualTo("____"); assertThat(JMXReporter.replaceInvalidChars("\"ab ;(c)'")).isEqualTo("ab_-(c)-"); assertThat(JMXReporter.replaceInvalidChars("a b c")).isEqualTo("a_b_c"); assertThat(JMXReporter.replaceInvalidChars("a b c ")).isEqualTo("a_b_c_"); assertThat(JMXReporter.replaceInvalidChars("a;b'c*")).isEqualTo("a-b-c-"); assertThat(JMXReporter.replaceInvalidChars("a,=;:?'b,=;:?'c")).isEqualTo("a------b------c"); } /** Verifies that the JMXReporter properly generates the JMX table. */ @Test void testGenerateTable() { Map<String, String> vars = new HashMap<>(); vars.put("key0", "value0"); vars.put("key1", "value1"); vars.put("\"key2,=;:?'", "\"value2 (test),=;:?'"); Hashtable<String, String> jmxTable = JMXReporter.generateJmxTable(vars); assertThat(jmxTable).containsEntry("key0", "value0"); assertThat(jmxTable).containsEntry("key0", "value0"); assertThat(jmxTable).containsEntry("key1", "value1"); assertThat(jmxTable).containsEntry("key2------", "value2_(test)------"); } /** * Verifies that multiple JMXReporters can be started on the same machine and register metrics * at the MBeanServer. * * @throws Exception if the attribute/mbean could not be found or the test is broken */ @Test void testPortConflictHandling() throws Exception { final MetricReporter rep1 = new JMXReporter("9020-9035"); final MetricReporter rep2 = new JMXReporter("9020-9035"); Gauge<Integer> g1 = () -> 1; Gauge<Integer> g2 = () -> 2; rep1.notifyOfAddedMetric(g1, "rep1", metricGroup); rep2.notifyOfAddedMetric(g2, "rep2", metricGroup); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName1 = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager.rep1", JMXReporter.generateJmxTable(metricGroup.getAllVariables())); ObjectName objectName2 = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager.rep2", JMXReporter.generateJmxTable(metricGroup.getAllVariables())); assertThat(mBeanServer.getAttribute(objectName1, "Value")).isEqualTo(1); assertThat(mBeanServer.getAttribute(objectName2, "Value")).isEqualTo(2); rep1.notifyOfRemovedMetric(g1, "rep1", null); rep1.notifyOfRemovedMetric(g2, "rep2", null); } /** Verifies that we can connect to multiple JMXReporters running on the same machine. */ @Test void testJMXAvailability() throws Exception { final JMXReporter rep1 = new JMXReporter("9040-9055"); final JMXReporter rep2 = new JMXReporter("9040-9055"); Gauge<Integer> g1 = () -> 1; Gauge<Integer> g2 = () -> 2; rep1.notifyOfAddedMetric(g1, "rep1", metricGroup); rep2.notifyOfAddedMetric(g2, "rep2", metricGroup); ObjectName objectName1 = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager.rep1", JMXReporter.generateJmxTable(metricGroup.getAllVariables())); ObjectName objectName2 = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager.rep2", JMXReporter.generateJmxTable(metricGroup.getAllVariables())); JMXServiceURL url1 = new JMXServiceURL( "service:jmx:rmi://localhost:" + rep1.getPort().get() + "/jndi/rmi://localhost:" + rep1.getPort().get() + "/jmxrmi"); JMXConnector jmxCon1 = JMXConnectorFactory.connect(url1); MBeanServerConnection mCon1 = jmxCon1.getMBeanServerConnection(); assertThat(mCon1.getAttribute(objectName1, "Value")).isEqualTo(1); assertThat(mCon1.getAttribute(objectName2, "Value")).isEqualTo(2); jmxCon1.close(); JMXServiceURL url2 = new JMXServiceURL( "service:jmx:rmi://localhost:" + rep2.getPort().get() + "/jndi/rmi://localhost:" + rep2.getPort().get() + "/jmxrmi"); JMXConnector jmxCon2 = JMXConnectorFactory.connect(url2); MBeanServerConnection mCon2 = jmxCon2.getMBeanServerConnection(); assertThat(mCon2.getAttribute(objectName1, "Value")).isEqualTo(1); assertThat(mCon2.getAttribute(objectName2, "Value")).isEqualTo(2); // JMX Server URL should be identical since we made it static. assertThat(url2).isEqualTo(url1); rep1.notifyOfRemovedMetric(g1, "rep1", null); rep1.notifyOfRemovedMetric(g2, "rep2", null); jmxCon2.close(); rep1.close(); rep2.close(); } /** Tests that histograms are properly reported via the JMXReporter. */ @Test void testHistogramReporting() throws Exception { String histogramName = "histogram"; final JMXReporter reporter = new JMXReporter(null); TestHistogram histogram = new TestHistogram(); reporter.notifyOfAddedMetric(histogram, histogramName, metricGroup); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager." + histogramName, JMXReporter.generateJmxTable(metricGroup.getAllVariables())); MBeanInfo info = mBeanServer.getMBeanInfo(objectName); MBeanAttributeInfo[] attributeInfos = info.getAttributes(); assertThat(attributeInfos).hasSize(11); assertThat(mBeanServer.getAttribute(objectName, "Count")).isEqualTo(histogram.getCount()); HistogramStatistics statistics = histogram.getStatistics(); assertThat(mBeanServer.getAttribute(objectName, "Mean")).isEqualTo(statistics.getMean()); assertThat(mBeanServer.getAttribute(objectName, "StdDev")) .isEqualTo(statistics.getStdDev()); assertThat(mBeanServer.getAttribute(objectName, "Max")).isEqualTo(statistics.getMax()); assertThat(mBeanServer.getAttribute(objectName, "Min")).isEqualTo(statistics.getMin()); assertThat(mBeanServer.getAttribute(objectName, "Median")) .isEqualTo(statistics.getQuantile(0.5)); assertThat(mBeanServer.getAttribute(objectName, "75thPercentile")) .isEqualTo(statistics.getQuantile(0.75)); assertThat(mBeanServer.getAttribute(objectName, "95thPercentile")) .isEqualTo(statistics.getQuantile(0.95)); assertThat(mBeanServer.getAttribute(objectName, "98thPercentile")) .isEqualTo(statistics.getQuantile(0.98)); assertThat(mBeanServer.getAttribute(objectName, "99thPercentile")) .isEqualTo(statistics.getQuantile(0.99)); assertThat(mBeanServer.getAttribute(objectName, "999thPercentile")) .isEqualTo(statistics.getQuantile(0.999)); } /** Tests that meters are properly reported via the JMXReporter. */ @Test void testMeterReporting() throws Exception { String meterName = "meter"; final JMXReporter reporter = new JMXReporter(null); TestMeter meter = new TestMeter(); reporter.notifyOfAddedMetric(meter, meterName, metricGroup); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName( JMX_DOMAIN_PREFIX + "taskmanager." + meterName, JMXReporter.generateJmxTable(metricGroup.getAllVariables())); MBeanInfo info = mBeanServer.getMBeanInfo(objectName); MBeanAttributeInfo[] attributeInfos = info.getAttributes(); assertThat(attributeInfos).hasSize(2); assertThat(mBeanServer.getAttribute(objectName, "Rate")).isEqualTo(meter.getRate()); assertThat(mBeanServer.getAttribute(objectName, "Count")).isEqualTo(meter.getCount()); } }
JMXReporterTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmanager/SlotCountExceedingParallelismTest.java
{ "start": 7120, "end": 9380 }
class ____ extends AbstractInvokable { public static final String CONFIG_KEY = "number-of-indexes-to-receive"; public SubtaskIndexReceiver(Environment environment) { super(environment); } @Override public void invoke() throws Exception { RecordReader<IntValue> reader = new RecordReader<>( getEnvironment().getInputGate(0), IntValue.class, getEnvironment().getTaskManagerInfo().getTmpDirectories()); try { final int numberOfSubtaskIndexesToReceive = getTaskConfiguration().get(getIntConfigOption(CONFIG_KEY), 0); final BitSet receivedSubtaskIndexes = new BitSet(numberOfSubtaskIndexesToReceive); IntValue record; int numberOfReceivedSubtaskIndexes = 0; while ((record = reader.next()) != null) { // Check that we don't receive more than expected numberOfReceivedSubtaskIndexes++; if (numberOfReceivedSubtaskIndexes > numberOfSubtaskIndexesToReceive) { throw new IllegalStateException("Received more records than expected."); } int subtaskIndex = record.getValue(); // Check that we only receive each subtask index once if (receivedSubtaskIndexes.get(subtaskIndex)) { throw new IllegalStateException("Received expected subtask index twice."); } else { receivedSubtaskIndexes.set(subtaskIndex, true); } } // Check that we have received all expected subtask indexes if (receivedSubtaskIndexes.cardinality() != numberOfSubtaskIndexesToReceive) { throw new IllegalStateException( "Finished receive, but did not receive " + "all expected subtask indexes."); } } finally { reader.clearBuffers(); } } } }
SubtaskIndexReceiver
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/CollectionDeserTest.java
{ "start": 1557, "end": 1642 }
class ____ { public AbstractList<String> values; } static
ListAsAbstract
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/integers/Integers_assertGreaterThan_Test.java
{ "start": 1492, "end": 3866 }
class ____ extends IntegersBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> integers.assertGreaterThan(someInfo(), null, 8)) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_greater_than_other() { integers.assertGreaterThan(someInfo(), 8, 6); } @Test void should_fail_if_actual_is_equal_to_other() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integers.assertGreaterThan(info, 6, 6)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(6, 6, StandardComparisonStrategy.instance())); } @Test void should_fail_if_actual_is_less_than_other() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integers.assertGreaterThan(info, 6, 8)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(6, 8)); } // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @Test void should_pass_if_actual_is_greater_than_other_according_to_custom_comparison_strategy() { integersWithAbsValueComparisonStrategy.assertGreaterThan(someInfo(), -8, 6); } @Test void should_fail_if_actual_is_equal_to_other_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integersWithAbsValueComparisonStrategy.assertGreaterThan(info, 6, -6)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(6, -6, absValueComparisonStrategy)); } @Test void should_fail_if_actual_is_less_than_other_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> integersWithAbsValueComparisonStrategy.assertGreaterThan(info, -6, -8)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeGreater(-6, -8, absValueComparisonStrategy)); } }
Integers_assertGreaterThan_Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ArrayHashCodeTest.java
{ "start": 6104, "end": 7142 }
class ____ { private Object[] objArray = {1, 2, 3}; private String[] stringArray = {"1", "2", "3"}; private int[] intArray = {1, 2, 3}; private byte[] byteArray = {1, 2, 3}; private Object obj = new Object(); private String str = "foo"; public void nonVaragsHashCodeOnNonArrayType() { int hashCode; hashCode = Objects.hashCode(obj); hashCode = Objects.hashCode(str); } public void varagsHashCodeOnNonArrayType() { int hashCode; hashCode = Objects.hash(obj); hashCode = Objects.hash(str); } public void varagsHashCodeOnObjectOrStringArray() { int hashCode; hashCode = Objects.hash(objArray); hashCode = Objects.hash((Object[]) stringArray); } }\ """) .doTest(); } }
ArrayHashCodeNegativeCases2
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestReduceTask.java
{ "start": 1612, "end": 5150 }
class ____ { String key; String value; Pair(String k, String v) { key = k; value = v; } } private static Pair[][] testCases = new Pair[][]{ new Pair[]{ new Pair("k1", "v1"), new Pair("k2", "v2"), new Pair("k3", "v3"), new Pair("k3", "v4"), new Pair("k4", "v5"), new Pair("k5", "v6"), }, new Pair[]{ new Pair("", "v1"), new Pair("k1", "v2"), new Pair("k2", "v3"), new Pair("k2", "v4"), }, new Pair[] {}, new Pair[]{ new Pair("k1", "v1"), new Pair("k1", "v2"), new Pair("k1", "v3"), new Pair("k1", "v4"), } }; public void runValueIterator(Path tmpDir, Pair[] vals, Configuration conf, CompressionCodec codec) throws IOException { FileSystem localFs = FileSystem.getLocal(conf); FileSystem rfs = ((LocalFileSystem)localFs).getRaw(); Path path = new Path(tmpDir, "data.in"); IFile.Writer<Text, Text> writer = new IFile.Writer<Text, Text>(conf, rfs.create(path), Text.class, Text.class, codec, null); for(Pair p: vals) { writer.append(new Text(p.key), new Text(p.value)); } writer.close(); @SuppressWarnings("unchecked") RawKeyValueIterator rawItr = Merger.merge(conf, rfs, Text.class, Text.class, codec, new Path[]{path}, false, conf.getInt(JobContext.IO_SORT_FACTOR, 100), tmpDir, new Text.Comparator(), new NullProgress(), null, null, null); @SuppressWarnings("unchecked") // WritableComparators are not generic ReduceTask.ValuesIterator valItr = new ReduceTask.ValuesIterator<Text,Text>(rawItr, WritableComparator.get(Text.class), Text.class, Text.class, conf, new NullProgress()); int i = 0; while (valItr.more()) { Object key = valItr.getKey(); String keyString = key.toString(); // make sure it matches! assertEquals(vals[i].key, keyString); // must have at least 1 value! assertTrue(valItr.hasNext()); while (valItr.hasNext()) { String valueString = valItr.next().toString(); // make sure the values match assertEquals(vals[i].value, valueString); // make sure the keys match assertEquals(vals[i].key, valItr.getKey().toString()); i += 1; } // make sure the key hasn't changed under the hood assertEquals(keyString, valItr.getKey().toString()); valItr.nextKey(); } assertEquals(vals.length, i); // make sure we have progress equal to 1.0 assertEquals(1.0f, rawItr.getProgress().get(),0.0000); } @Test public void testValueIterator() throws Exception { Path tmpDir = new Path("build/test/test.reduce.task"); Configuration conf = new Configuration(); for (Pair[] testCase: testCases) { runValueIterator(tmpDir, testCase, conf, null); } } @Test public void testValueIteratorWithCompression() throws Exception { Path tmpDir = new Path("build/test/test.reduce.task.compression"); Configuration conf = new Configuration(); DefaultCodec codec = new DefaultCodec(); codec.setConf(conf); for (Pair[] testCase: testCases) { runValueIterator(tmpDir, testCase, conf, codec); } } }
Pair
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/interceptor/TransactionalClientDataSourceOnExceptionRedeliveryTest.java
{ "start": 1288, "end": 3942 }
class ____ extends TransactionalClientDataSourceTest { @Test public void testTransactionRollbackWithExchange() throws Exception { Exchange out = template.send("direct:fail", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }); int count = jdbc.queryForObject("select count(*) from books", Integer.class); assertEquals(1, count, "Number of books"); assertNotNull(out); Exception e = out.getException(); assertIsInstanceOf(RuntimeCamelException.class, e); assertTrue(e.getCause() instanceof IllegalArgumentException); assertEquals("We don't have Donkeys, only Camels", e.getCause().getMessage()); assertEquals(true, out.getIn().getHeader(Exchange.REDELIVERED)); assertEquals(3, out.getIn().getHeader(Exchange.REDELIVERY_COUNTER)); assertEquals(true, out.getExchangeExtension().isFailureHandled()); assertEquals(false, out.getExchangeExtension().isErrorHandlerHandled()); } @Override // The API is deprecated, we can remove warnings safely as the tests will disappear when removing this component. @SuppressWarnings("deprecation") protected RouteBuilder createRouteBuilder() throws Exception { return new SpringRouteBuilder() { public void configure() throws Exception { onException(IllegalArgumentException.class).maximumRedeliveries(3); // START SNIPPET: e1 from("direct:okay") // marks this route as transacted, and we dont pass in any parameters so we // will auto lookup and use the Policy defined in the spring XML file .transacted() .setBody(constant("Tiger in Action")).bean("bookService") .setBody(constant("Elephant in Action")).bean("bookService"); // marks this route as transacted that will use the single policy defined in the registry from("direct:fail") // marks this route as transacted, and we dont pass in any parameters so we // will auto lookup and use the Policy defined in the spring XML file .transacted() .setBody(constant("Tiger in Action")).bean("bookService") .setBody(constant("Donkey in Action")).bean("bookService"); // END SNIPPET: e1 } }; } }
TransactionalClientDataSourceOnExceptionRedeliveryTest
java
google__gson
gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
{ "start": 14017, "end": 15664 }
class ____ implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType() != WithDelegatingFactory.class) { return null; } TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<>() { @Override public T read(JsonReader in) throws IOException { // Perform custom deserialization in.beginObject(); assertThat(in.nextName()).isEqualTo("custom"); T t = delegate.read(in); in.endObject(); return t; } @Override public void write(JsonWriter out, T value) throws IOException { // Perform custom serialization out.beginObject(); out.name("custom"); delegate.write(out, value); out.endObject(); } }; } } } /** * Similar to {@link #testDelegatingAdapterFactory}, except that the delegate is not looked up in * {@code create} but instead in the adapter methods. */ @Test public void testDelegatingAdapterFactory_Delayed() { WithDelayedDelegatingFactory deserialized = new Gson().fromJson("{\"custom\":{\"f\":\"de\"}}", WithDelayedDelegatingFactory.class); assertThat(deserialized.f).isEqualTo("de"); WithDelayedDelegatingFactory serialized = new WithDelayedDelegatingFactory("se"); assertThat(new Gson().toJson(serialized)).isEqualTo("{\"custom\":{\"f\":\"se\"}}"); } @JsonAdapter(WithDelayedDelegatingFactory.Factory.class) private static
Factory
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/ReflectionFreeAssertThrows.java
{ "start": 4022, "end": 7078 }
enum ____ { PLATFORM { @GwtIncompatible @J2ktIncompatible @Override // returns the types available in "normal" environments ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() { return ImmutableMap.of( InvocationTargetException.class, e -> e instanceof InvocationTargetException, StackOverflowError.class, e -> e instanceof StackOverflowError); } }; // used under GWT, etc., since the override of this method does not exist there ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> exceptions() { return ImmutableMap.of(); } } private static final ImmutableMap<Class<? extends Throwable>, Predicate<Throwable>> INSTANCE_OF = ImmutableMap.<Class<? extends Throwable>, Predicate<Throwable>>builder() .put(ArithmeticException.class, e -> e instanceof ArithmeticException) .put( ArrayIndexOutOfBoundsException.class, e -> e instanceof ArrayIndexOutOfBoundsException) .put(ArrayStoreException.class, e -> e instanceof ArrayStoreException) .put(AssertionFailedError.class, e -> e instanceof AssertionFailedError) .put(CancellationException.class, e -> e instanceof CancellationException) .put(ClassCastException.class, e -> e instanceof ClassCastException) .put( ConcurrentModificationException.class, e -> e instanceof ConcurrentModificationException) .put(ExecutionException.class, e -> e instanceof ExecutionException) .put(IllegalArgumentException.class, e -> e instanceof IllegalArgumentException) .put(IllegalStateException.class, e -> e instanceof IllegalStateException) .put(IndexOutOfBoundsException.class, e -> e instanceof IndexOutOfBoundsException) .put(NoSuchElementException.class, e -> e instanceof NoSuchElementException) .put(NullPointerException.class, e -> e instanceof NullPointerException) .put(NumberFormatException.class, e -> e instanceof NumberFormatException) .put(RuntimeException.class, e -> e instanceof RuntimeException) .put(SomeCheckedException.class, e -> e instanceof SomeCheckedException) .put(SomeError.class, e -> e instanceof SomeError) .put(SomeOtherCheckedException.class, e -> e instanceof SomeOtherCheckedException) .put(SomeUncheckedException.class, e -> e instanceof SomeUncheckedException) .put(TimeoutException.class, e -> e instanceof TimeoutException) .put(UnsupportedCharsetException.class, e -> e instanceof UnsupportedCharsetException) .put(UnsupportedOperationException.class, e -> e instanceof UnsupportedOperationException) .put(VerifyException.class, e -> e instanceof VerifyException) .putAll(PlatformSpecificExceptionBatch.PLATFORM.exceptions()) .buildOrThrow(); private ReflectionFreeAssertThrows() {} }
PlatformSpecificExceptionBatch
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-artifact/src/main/java/org/apache/maven/plugin/coreit/CollectMojo.java
{ "start": 1764, "end": 4114 }
class ____ extends AbstractMojo { /** * The local repository. */ @Parameter(defaultValue = "${localRepository}", readonly = true, required = true) private ArtifactRepository localRepository; /** * The remote repositories of the current Maven project. */ @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true) private List remoteRepositories; /** * The artifact collector. * */ @Component private ArtifactCollector collector; /** * The artifact factory. * */ @Component private ArtifactFactory factory; /** * The metadata source. * */ @Component private ArtifactMetadataSource metadataSource; /** * The dependencies to resolve. * */ @Parameter private Dependency[] dependencies; /** * Runs this mojo. * * @throws MojoFailureException If the artifact file has not been set. */ public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("[MAVEN-CORE-IT-LOG] Collecting artifacts"); try { Artifact origin = factory.createArtifact("it", "it", "0.1", null, "pom"); Set artifacts = new LinkedHashSet(); if (dependencies != null) { for (Dependency dependency : dependencies) { Artifact artifact = factory.createArtifactWithClassifier( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getType(), dependency.getClassifier()); artifacts.add(artifact); getLog().info("[MAVEN-CORE-IT-LOG] Collecting " + artifact.getId()); } } collector.collect( artifacts, origin, localRepository, remoteRepositories, metadataSource, null, Collections.EMPTY_LIST); } catch (Exception e) { throw new MojoExecutionException("Failed to collect artifacts: " + e.getMessage(), e); } } }
CollectMojo
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orphan/elementcollection/EnrolledClassSeat.java
{ "start": 159, "end": 546 }
class ____ { private String id; private int row; private int column; public String getId() { return id; } public void setId(String id) { this.id = id; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } }
EnrolledClassSeat
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java
{ "start": 32728, "end": 33127 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .headers((headers) -> headers .defaultsDisabled() .httpPublicKeyPinning((hpkp) -> hpkp .addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM="))); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity static
HpkpConfig
java
apache__camel
components/camel-crypto-pgp/src/test/java/org/apache/camel/converter/crypto/PGPDataFormatDynamicTest.java
{ "start": 1144, "end": 3288 }
class ____ extends PGPDataFormatTest { // setup a wrong userid @Override protected String getKeyUserId() { return "wrong"; } // setup a wrong userids @Override protected List<String> getKeyUserIds() { List<String> userids = new ArrayList<>(2); userids.add("wrong1"); userids.add(getKeyUserId()); return userids; } // setup a wrong signature userids @Override protected List<String> getSignatureKeyUserIds() { List<String> userids = new ArrayList<>(2); userids.add("wrong1"); userids.add(getKeyUserId()); return userids; } // setup a wrong password @Override protected String getKeyPassword() { return "wrong"; } //setup wrong algorithm @Override protected int getAlgorithm() { return -5; } //setup wrong hash algorithm @Override protected int getHashAlgorithm() { return -5; } //setup wrong compression algorithm @Override protected int getCompressionAlgorithm() { return -5; } // override wrong userid and password with correct userid and password in the headers @Override protected Map<String, Object> getHeaders() { Map<String, Object> headers = new HashMap<>(); headers.put(PGPKeyAccessDataFormat.KEY_USERID, "sdude@nowhere.net"); headers.put(PGPKeyAccessDataFormat.KEY_USERIDS, Collections.singletonList("second")); headers.put(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID, "sdude@nowhere.net"); headers.put(PGPDataFormat.KEY_PASSWORD, "sdude"); headers.put(PGPDataFormat.SIGNATURE_KEY_PASSWORD, "sdude"); headers.put(PGPKeyAccessDataFormat.ENCRYPTION_ALGORITHM, SymmetricKeyAlgorithmTags.AES_128); headers.put(PGPKeyAccessDataFormat.SIGNATURE_HASH_ALGORITHM, HashAlgorithmTags.SHA512); headers.put(PGPKeyAccessDataFormat.COMPRESSION_ALGORITHM, CompressionAlgorithmTags.ZLIB); headers.put(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERIDS, Collections.singletonList("second")); return headers; } }
PGPDataFormatDynamicTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/blockhash/AddPageTests.java
{ "start": 974, "end": 6240 }
class ____ extends ESTestCase { private final BlockFactory blockFactory = BlockFactoryTests.blockFactory(ByteSizeValue.ofGb(1)); public void testSv() { TestAddInput result = new TestAddInput(); List<Added> expected = new ArrayList<>(); try (AddPage add = new AddPage(blockFactory, 3, result)) { add.appendOrdSv(0, 0); add.appendOrdSv(1, 2); add.appendOrdSv(2, 3); expected.add(added(0, 0, 2, 3)); assertThat(result.added, equalTo(expected)); add.appendOrdSv(3, 4); add.flushRemaining(); assertThat(add.added(), equalTo(4L)); } expected.add(added(3, 4)); assertThat(result.added, equalTo(expected)); } public void testMvBlockEndsOnBatchBoundary() { TestAddInput result = new TestAddInput(); List<Added> expected = new ArrayList<>(); try (AddPage add = new AddPage(blockFactory, 3, result)) { add.appendOrdInMv(0, 0); add.appendOrdInMv(0, 2); add.appendOrdInMv(0, 3); expected.add(new Added(0, List.of(List.of(0, 2, 3)))); assertThat(result.added, equalTo(expected)); add.appendOrdInMv(0, 4); add.finishMv(); add.appendOrdInMv(1, 0); add.appendOrdInMv(1, 2); expected.add(new Added(0, List.of(List.of(4), List.of(0, 2)))); assertThat(result.added, equalTo(expected)); add.finishMv(); add.flushRemaining(); assertThat(add.added(), equalTo(6L)); } /* * We do *not* uselessly flush an empty Block of ordinals. Doing so would * be a slight performance hit, but, worse, makes testing harder to reason * about. */ assertThat(result.added, equalTo(expected)); } public void testMvPositionEndOnBatchBoundary() { TestAddInput result = new TestAddInput(); List<Added> expected = new ArrayList<>(); try (AddPage add = new AddPage(blockFactory, 4, result)) { add.appendOrdInMv(0, 0); add.appendOrdInMv(0, 2); add.appendOrdInMv(0, 3); add.appendOrdInMv(0, 4); expected.add(new Added(0, List.of(List.of(0, 2, 3, 4)))); assertThat(result.added, equalTo(expected)); add.finishMv(); add.appendOrdInMv(1, 0); add.appendOrdInMv(1, 2); add.finishMv(); add.flushRemaining(); assertThat(add.added(), equalTo(6L)); } // Because the first position ended on a block boundary we uselessly emit an empty position there expected.add(new Added(0, List.of(List.of(), List.of(0, 2)))); assertThat(result.added, equalTo(expected)); } public void testMv() { TestAddInput result = new TestAddInput(); List<Added> expected = new ArrayList<>(); try (AddPage add = new AddPage(blockFactory, 5, result)) { add.appendOrdInMv(0, 0); add.appendOrdInMv(0, 2); add.appendOrdInMv(0, 3); add.appendOrdInMv(0, 4); add.finishMv(); add.appendOrdInMv(1, 0); expected.add(new Added(0, List.of(List.of(0, 2, 3, 4), List.of(0)))); assertThat(result.added, equalTo(expected)); add.appendOrdInMv(1, 2); add.finishMv(); add.flushRemaining(); assertThat(add.added(), equalTo(6L)); } expected.add(new Added(1, List.of(List.of(2)))); assertThat(result.added, equalTo(expected)); } /** * Test that we can add more than {@link Integer#MAX_VALUE} values. That's * more than two billion values. We've made the call as fast as we can. * Locally this test takes about 40 seconds for Nik. */ public void testMvBillions() { CountingAddInput counter = new CountingAddInput(); try (AddPage add = new AddPage(blockFactory, 5, counter)) { for (int i = 0; i < Integer.MAX_VALUE; i++) { add.appendOrdInMv(0, 0); assertThat(add.added(), equalTo((long) i + 1)); if (i % 5 == 0) { assertThat(counter.count, equalTo(i / 5)); } if (i % 10_000_000 == 0) { logger.info(String.format(Locale.ROOT, "Progress: %02.0f%%", 100 * ((double) i / Integer.MAX_VALUE))); } } add.finishMv(); add.appendOrdInMv(1, 0); assertThat(add.added(), equalTo(Integer.MAX_VALUE + 1L)); add.appendOrdInMv(1, 0); assertThat(add.added(), equalTo(Integer.MAX_VALUE + 2L)); add.finishMv(); add.flushRemaining(); assertThat(counter.count, equalTo(Integer.MAX_VALUE / 5 + 1)); } } @After public void breakerClear() { assertThat(blockFactory.breaker().getUsed(), equalTo(0L)); } record Added(int positionOffset, List<List<Integer>> ords) {} Added added(int positionOffset, int... ords) { return new Added(positionOffset, Arrays.stream(ords).mapToObj(List::of).toList()); } private
AddPageTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222.java
{ "start": 642, "end": 797 }
enum ____ implements JSONAware { A, B; public String toJSONString() { return "\"Type" + this.name() + "\""; } } }
Type
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/AssignmentInformation.java
{ "start": 1513, "end": 4853 }
class ____ { public RMContainer rmContainer; public ContainerId containerId; public String queue; public AssignmentDetails(RMContainer rmContainer, String queue) { this.containerId = rmContainer.getContainerId(); this.rmContainer = rmContainer; this.queue = queue; } } private final int[] operationCounts; private final Resource[] operationResources; private final List<AssignmentDetails>[] operationDetails; @SuppressWarnings("unchecked") public AssignmentInformation() { int numOps = Operation.size(); this.operationCounts = new int[numOps]; this.operationResources = new Resource[numOps]; this.operationDetails = new List[numOps]; for (int i=0; i < numOps; i++) { operationCounts[i] = 0; operationResources[i] = Resource.newInstance(0, 0); operationDetails[i] = new ArrayList<>(); } } public int getNumAllocations() { return operationCounts[Operation.ALLOCATION.ordinal()]; } public void incrAllocations() { increment(Operation.ALLOCATION, 1); } public void incrAllocations(int by) { increment(Operation.ALLOCATION, by); } public int getNumReservations() { return operationCounts[Operation.RESERVATION.ordinal()]; } public void incrReservations() { increment(Operation.RESERVATION, 1); } public void incrReservations(int by) { increment(Operation.RESERVATION, by); } private void increment(Operation op, int by) { operationCounts[op.ordinal()] += by; } public Resource getAllocated() { return operationResources[Operation.ALLOCATION.ordinal()]; } public Resource getReserved() { return operationResources[Operation.RESERVATION.ordinal()]; } private void addAssignmentDetails(Operation op, RMContainer rmContainer, String queue) { getDetails(op).add(new AssignmentDetails(rmContainer, queue)); } public void addAllocationDetails(RMContainer rmContainer, String queue) { addAssignmentDetails(Operation.ALLOCATION, rmContainer, queue); } public void addReservationDetails(RMContainer rmContainer, String queue) { addAssignmentDetails(Operation.RESERVATION, rmContainer, queue); } private List<AssignmentDetails> getDetails(Operation op) { return operationDetails[op.ordinal()]; } public List<AssignmentDetails> getAllocationDetails() { return getDetails(Operation.ALLOCATION); } public List<AssignmentDetails> getReservationDetails() { return getDetails(Operation.RESERVATION); } private RMContainer getFirstRMContainerFromOperation(Operation op) { List<AssignmentDetails> assignDetails = getDetails(op); if (assignDetails != null && !assignDetails.isEmpty()) { return assignDetails.get(0).rmContainer; } return null; } public RMContainer getFirstAllocatedOrReservedRMContainer() { RMContainer rmContainer; rmContainer = getFirstRMContainerFromOperation(Operation.ALLOCATION); if (null != rmContainer) { return rmContainer; } return getFirstRMContainerFromOperation(Operation.RESERVATION); } public ContainerId getFirstAllocatedOrReservedContainerId() { RMContainer rmContainer = getFirstAllocatedOrReservedRMContainer(); if (null != rmContainer) { return rmContainer.getContainerId(); } return null; } }
AssignmentDetails
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcherUtils.java
{ "start": 923, "end": 1794 }
class ____ { /** * Gets the value for an argument, or null if the argument does not exist. * * @param annotationTree the AST node for the annotation * @param name the name of the argument whose value to get * @return the value of the argument, or null if the argument does not exist */ public static @Nullable ExpressionTree getArgument(AnnotationTree annotationTree, String name) { for (ExpressionTree argumentTree : annotationTree.getArguments()) { if (!(argumentTree instanceof AssignmentTree assignmentTree)) { continue; } if (!assignmentTree.getVariable().toString().equals(name)) { continue; } ExpressionTree expressionTree = assignmentTree.getExpression(); return expressionTree; } return null; } // Static class. private AnnotationMatcherUtils() {} }
AnnotationMatcherUtils
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/TransactionDescription.java
{ "start": 975, "end": 3750 }
class ____ { private final int coordinatorId; private final TransactionState state; private final long producerId; private final int producerEpoch; private final long transactionTimeoutMs; private final OptionalLong transactionStartTimeMs; private final Set<TopicPartition> topicPartitions; public TransactionDescription( int coordinatorId, TransactionState state, long producerId, int producerEpoch, long transactionTimeoutMs, OptionalLong transactionStartTimeMs, Set<TopicPartition> topicPartitions ) { this.coordinatorId = coordinatorId; this.state = state; this.producerId = producerId; this.producerEpoch = producerEpoch; this.transactionTimeoutMs = transactionTimeoutMs; this.transactionStartTimeMs = transactionStartTimeMs; this.topicPartitions = topicPartitions; } public int coordinatorId() { return coordinatorId; } public TransactionState state() { return state; } public long producerId() { return producerId; } public int producerEpoch() { return producerEpoch; } public long transactionTimeoutMs() { return transactionTimeoutMs; } public OptionalLong transactionStartTimeMs() { return transactionStartTimeMs; } public Set<TopicPartition> topicPartitions() { return topicPartitions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionDescription that = (TransactionDescription) o; return coordinatorId == that.coordinatorId && producerId == that.producerId && producerEpoch == that.producerEpoch && transactionTimeoutMs == that.transactionTimeoutMs && state == that.state && Objects.equals(transactionStartTimeMs, that.transactionStartTimeMs) && Objects.equals(topicPartitions, that.topicPartitions); } @Override public int hashCode() { return Objects.hash(coordinatorId, state, producerId, producerEpoch, transactionTimeoutMs, transactionStartTimeMs, topicPartitions); } @Override public String toString() { return "TransactionDescription(" + "coordinatorId=" + coordinatorId + ", state=" + state + ", producerId=" + producerId + ", producerEpoch=" + producerEpoch + ", transactionTimeoutMs=" + transactionTimeoutMs + ", transactionStartTimeMs=" + transactionStartTimeMs + ", topicPartitions=" + topicPartitions + ')'; } }
TransactionDescription
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/common/JsonUtilsTests.java
{ "start": 832, "end": 2556 }
class ____ extends ESTestCase { public void testToJson() throws IOException { assertThat(toJson("string", "field"), is("\"string\"")); assertThat(toJson(1, "field"), is("1")); assertThat(toJson(List.of("a", "b"), "field"), is("[\"a\",\"b\"]")); { var expected = XContentHelper.stripWhitespace(""" { "key": "value", "key2": [1, 2] } """); assertThat(toJson(new TreeMap<>(Map.of("key", "value", "key2", List.of(1, 2))), "field"), is(expected)); } { var serializer = new ToXContentFragment() { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.value("string"); return builder; } }; assertThat(toJson(serializer, "field"), is("\"string\"")); } assertThat(toJson(1.1d, "field"), is("1.1")); assertThat(toJson(1.1f, "field"), is("1.1")); assertThat(toJson(true, "field"), is("true")); assertThat(toJson(false, "field"), is("false")); assertThat(toJson(new SecureString("api_key".toCharArray()), "field"), is("\"api_key\"")); } public void testToJson_ThrowsException_WhenUnableToSerialize() { var exception = expectThrows(IllegalStateException.class, () -> toJson(new Object(), "field")); assertThat( exception.getMessage(), is( "Failed to serialize value as JSON, field: field, error: " + "cannot write xcontent for unknown value of type
JsonUtilsTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/maps/Maps_assertHasSizeGreaterThan_Test.java
{ "start": 971, "end": 1745 }
class ____ extends MapsBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasSizeGreaterThan(INFO, null, 6)) .withMessage(actualIsNull()); } @Test void should_fail_if_size_of_actual_is_not_greater_than_boundary() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasSizeGreaterThan(INFO, actual, 6)) .withMessage(shouldHaveSizeGreaterThan(actual, actual.size(), 6).create()); } @Test void should_pass_if_size_of_actual_is_greater_than_boundary() { maps.assertHasSizeGreaterThan(INFO, actual, 1); } }
Maps_assertHasSizeGreaterThan_Test