language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/management/ManagementConfig.java
{ "start": 760, "end": 970 }
interface ____ be enabled using the * {@link ManagementInterfaceBuildTimeConfig#enabled} build-time property. */ @ConfigMapping(prefix = "quarkus.management") @ConfigRoot(phase = ConfigPhase.RUN_TIME) public
must
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/InnerClassCreatorTest.java
{ "start": 1729, "end": 1899 }
class ____ { public Generic<?> generic; public InnerClass1503(@JsonProperty("generic") Generic<?> generic) {} } static
InnerClass1503
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/util/matcher/RequestMatchers.java
{ "start": 837, "end": 2229 }
class ____ { /** * Creates a {@link RequestMatcher} that matches if at least one of the given * {@link RequestMatcher}s matches, if <code>matchers</code> are empty then the * returned matcher never matches. * @param matchers the {@link RequestMatcher}s to use * @return the any-of composed {@link RequestMatcher} * @see OrRequestMatcher */ public static RequestMatcher anyOf(RequestMatcher... matchers) { return (matchers.length > 0) ? new OrRequestMatcher(List.of(matchers)) : (request) -> false; } /** * Creates a {@link RequestMatcher} that matches if all the given * {@link RequestMatcher}s match, if <code>matchers</code> are empty then the returned * matcher always matches. * @param matchers the {@link RequestMatcher}s to use * @return the all-of composed {@link RequestMatcher} * @see AndRequestMatcher */ public static RequestMatcher allOf(RequestMatcher... matchers) { return (matchers.length > 0) ? new AndRequestMatcher(List.of(matchers)) : (request) -> true; } /** * Creates a {@link RequestMatcher} that matches if the given {@link RequestMatcher} * does not match. * @param matcher the {@link RequestMatcher} to use * @return the inverted {@link RequestMatcher} */ public static RequestMatcher not(RequestMatcher matcher) { return (request) -> !matcher.matches(request); } private RequestMatchers() { } }
RequestMatchers
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/component/extension/ComponentVerifierExtensionHelper.java
{ "start": 2675, "end": 3784 }
class ____ implements Attribute { private final String name; ErrorAttribute(String name) { if (name == null) { throw new IllegalArgumentException("Name of an error attribute must not be null"); } this.name = name; } @Override public String name() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Attribute)) { return false; } Attribute that = (Attribute) o; return name.equals(that.name()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name(); } } // =========================================================================================================== // Helper classes for implementing the constants in ComponentVerifier: static
ErrorAttribute
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/jdbc/JDBCDataSource.java
{ "start": 243, "end": 760 }
class ____ { private final String name; private final boolean isDefault; private final String dbKind; @RecordableConstructor public JDBCDataSource(String name, boolean isDefault, String dbKind) { this.name = name; this.isDefault = isDefault; this.dbKind = dbKind; } public String getName() { return name; } public boolean getIsDefault() { return isDefault; } public String getDbKind() { return dbKind; } }
JDBCDataSource
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/maptypehandler/LabelsTypeHandler.java
{ "start": 1011, "end": 1715 }
class ____ implements TypeHandler<Map<String, Object>> { @Override public void setParameter(PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType) throws SQLException { // Not Implemented } @Override public Map<String, Object> getResult(ResultSet rs, String columnName) throws SQLException { // Not Implemented return null; } @Override public Map<String, Object> getResult(ResultSet rs, int columnIndex) throws SQLException { // Not Implemented return null; } @Override public Map<String, Object> getResult(CallableStatement cs, int columnIndex) throws SQLException { // Not Implemented return null; } }
LabelsTypeHandler
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/process/ListRest.java
{ "start": 1734, "end": 6832 }
class ____ extends ProcessWatchCommand { @CommandLine.Parameters(description = "Name or pid of running Camel integration", arity = "0..1") String name = "*"; @CommandLine.Option(names = { "--sort" }, completionCandidates = PidNameAgeCompletionCandidates.class, description = "Sort by pid, name or age", defaultValue = "pid") String sort; @CommandLine.Option(names = { "--verbose" }, description = "Show more details") boolean verbose; public ListRest(CamelJBangMain main) { super(main); } @Override public Integer doProcessWatchCall() throws Exception { List<Row> rows = new ArrayList<>(); List<Long> pids = findPids(name); ProcessHandle.allProcesses() .filter(ph -> pids.contains(ph.pid())) .forEach(ph -> { JsonObject root = loadStatus(ph.pid()); // there must be a status file for the running Camel integration if (root != null) { Row row = new Row(); JsonObject context = (JsonObject) root.get("context"); if (context == null) { return; } row.name = context.getString("name"); if ("CamelJBang".equals(row.name)) { row.name = ProcessHelper.extractName(root, ph); } row.pid = Long.toString(ph.pid()); row.uptime = extractSince(ph); row.age = TimeUtils.printSince(row.uptime); JsonObject jo = (JsonObject) root.get("rests"); if (jo != null) { JsonArray arr = (JsonArray) jo.get("rests"); if (arr != null) { for (int i = 0; i < arr.size(); i++) { row = row.copy(); jo = (JsonObject) arr.get(i); row.url = jo.getString("url"); row.method = jo.getString("method").toUpperCase(Locale.ROOT); row.consumes = jo.getString("consumes"); row.produces = jo.getString("produces"); row.description = jo.getString("description"); row.contractFirst = jo.getBooleanOrDefault("contractFirst", false); rows.add(row); } } } } }); // sort rows rows.sort(this::sortRow); if (!rows.isEmpty()) { printer().println(AsciiTable.getTable(AsciiTable.NO_BORDERS, rows, Arrays.asList( new Column().header("PID").headerAlign(HorizontalAlign.CENTER).with(r -> r.pid), new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).maxWidth(30, OverflowBehaviour.ELLIPSIS_RIGHT) .with(r -> r.name), new Column().header("URL").dataAlign(HorizontalAlign.LEFT).with(r -> r.url), new Column().header("METHOD").dataAlign(HorizontalAlign.LEFT).with(r -> r.method), new Column().header("FIRST").visible(verbose).dataAlign(HorizontalAlign.LEFT).with(this::getKind), new Column().header("DESCRIPTION").visible(verbose).maxWidth(40, OverflowBehaviour.NEWLINE) .dataAlign(HorizontalAlign.LEFT).with(r -> r.description), new Column().header("CONTENT-TYPE").dataAlign(HorizontalAlign.LEFT).with(this::getContent)))); } return 0; } private String getKind(Row r) { return r.contractFirst ? "Contract" : "Code"; } private String getContent(Row r) { StringJoiner sj = new StringJoiner(" "); if (r.consumes != null || r.produces != null) { if (r.consumes != null) { sj.add("accept: " + r.consumes); } if (r.produces != null) { sj.add("produces: " + r.produces); } } if (sj.length() > 0) { return sj.toString(); } return ""; } protected int sortRow(Row o1, Row o2) { String s = sort; int negate = 1; if (s.startsWith("-")) { s = s.substring(1); negate = -1; } switch (s) { case "pid": return Long.compare(Long.parseLong(o1.pid), Long.parseLong(o2.pid)) * negate; case "name": return o1.name.compareToIgnoreCase(o2.name) * negate; case "age": return Long.compare(o1.uptime, o2.uptime) * negate; default: return 0; } } private static
ListRest
java
apache__thrift
lib/javame/src/org/apache/thrift/transport/THttpClient.java
{ "start": 1244, "end": 4675 }
class ____ extends TTransport { private String url_ = null; private final ByteArrayOutputStream requestBuffer_ = new ByteArrayOutputStream(); private InputStream inputStream_ = null; private HttpConnection connection = null; private int connectTimeout_ = 0; private int readTimeout_ = 0; private Hashtable customHeaders_ = null; public THttpClient(String url) throws TTransportException { url_ = url; } public void setConnectTimeout(int timeout) { connectTimeout_ = timeout; } public void setReadTimeout(int timeout) { readTimeout_ = timeout; } public void setCustomHeaders(Hashtable headers) { customHeaders_ = headers; } public void setCustomHeader(String key, String value) { if (customHeaders_ == null) { customHeaders_ = new Hashtable(); } customHeaders_.put(key, value); } public void open() {} public void close() { if (null != inputStream_) { try { inputStream_.close(); } catch (IOException ioe) { } inputStream_ = null; } if (connection != null) { try { connection.close(); } catch (IOException ioe) { } connection = null; } } public boolean isOpen() { return true; } public int read(byte[] buf, int off, int len) throws TTransportException { if (inputStream_ == null) { throw new TTransportException("Response buffer is empty, no request."); } try { int ret = inputStream_.read(buf, off, len); if (ret == -1) { throw new TTransportException("No more data available."); } return ret; } catch (IOException iox) { throw new TTransportException(iox); } } public void write(byte[] buf, int off, int len) { requestBuffer_.write(buf, off, len); } public void flush() throws TTransportException { // Extract request and reset buffer byte[] data = requestBuffer_.toByteArray(); requestBuffer_.reset(); try { // Create connection object connection = (HttpConnection)Connector.open(url_); // Make the request connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-thrift"); connection.setRequestProperty("Accept", "application/x-thrift"); connection.setRequestProperty("User-Agent", "JavaME/THttpClient"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Keep-Alive", "5000"); connection.setRequestProperty("Http-version", "HTTP/1.1"); connection.setRequestProperty("Cache-Control", "no-transform"); if (customHeaders_ != null) { for (Enumeration e = customHeaders_.keys() ; e.hasMoreElements() ;) { String key = (String)e.nextElement(); String value = (String)customHeaders_.get(key); connection.setRequestProperty(key, value); } } OutputStream os = connection.openOutputStream(); os.write(data); os.close(); int responseCode = connection.getResponseCode(); if (responseCode != HttpConnection.HTTP_OK) { throw new TTransportException("HTTP Response code: " + responseCode); } // Read the responses inputStream_ = connection.openInputStream(); } catch (IOException iox) { System.out.println(iox.toString()); throw new TTransportException(iox); } } }
THttpClient
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestCounters.java
{ "start": 4226, "end": 14328 }
enum ____ that dont have resource bundler testCounter(getEnumCounters(keysWithoutResource)); // III. Check string counters testCounter(getEnumCounters(groups, counters)); } catch (ParseException pe) { throw new IOException(pe); } } /** * Verify counter value works */ @SuppressWarnings("deprecation") @Test public void testCounterValue() { Counters counters = new Counters(); final int NUMBER_TESTS = 100; final int NUMBER_INC = 10; final Random rand = new Random(); for (int i = 0; i < NUMBER_TESTS; i++) { long initValue = rand.nextInt(); long expectedValue = initValue; Counter counter = counters.findCounter("foo", "bar"); counter.setValue(initValue); assertEquals(expectedValue, counter.getValue(), "Counter value is not initialized correctly"); for (int j = 0; j < NUMBER_INC; j++) { int incValue = rand.nextInt(); counter.increment(incValue); expectedValue += incValue; assertEquals(expectedValue, counter.getValue(), "Counter value is not incremented correctly"); } expectedValue = rand.nextInt(); counter.setValue(expectedValue); assertEquals(expectedValue, counter.getValue(), "Counter value is not set correctly"); } } @SuppressWarnings("deprecation") @Test public void testReadWithLegacyNames() { Counters counters = new Counters(); counters.incrCounter(TaskCounter.MAP_INPUT_RECORDS, 1); counters.incrCounter(JobCounter.DATA_LOCAL_MAPS, 1); counters.findCounter("file", FileSystemCounter.BYTES_READ).increment(1); checkLegacyNames(counters); } @SuppressWarnings("deprecation") @Test public void testWriteWithLegacyNames() { Counters counters = new Counters(); counters.incrCounter(Task.Counter.MAP_INPUT_RECORDS, 1); counters.incrCounter(JobInProgress.Counter.DATA_LOCAL_MAPS, 1); counters.findCounter("FileSystemCounters", "FILE_BYTES_READ").increment(1); checkLegacyNames(counters); } @SuppressWarnings("deprecation") private void checkLegacyNames(Counters counters) { assertEquals(1, counters.findCounter( TaskCounter.class.getName(), "MAP_INPUT_RECORDS").getValue(), "New name"); assertEquals(1, counters.findCounter( "org.apache.hadoop.mapred.Task$Counter", "MAP_INPUT_RECORDS").getValue(), "Legacy name"); assertEquals(1, counters.findCounter(Task.Counter.MAP_INPUT_RECORDS).getValue(), "Legacy enum"); assertEquals(1, counters.findCounter( JobCounter.class.getName(), "DATA_LOCAL_MAPS").getValue(), "New name"); assertEquals(1, counters.findCounter( "org.apache.hadoop.mapred.JobInProgress$Counter", "DATA_LOCAL_MAPS").getValue(), "Legacy name"); assertEquals(1, counters.findCounter(JobInProgress.Counter.DATA_LOCAL_MAPS).getValue(), "Legacy enum"); assertEquals(1, counters.findCounter( FileSystemCounter.class.getName(), "FILE_BYTES_READ").getValue(), "New name"); assertEquals(1, counters.findCounter("file", FileSystemCounter.BYTES_READ).getValue(), "New name and method"); assertEquals(1, counters.findCounter( "FileSystemCounters", "FILE_BYTES_READ").getValue(), "Legacy name"); } @SuppressWarnings("deprecation") @Test public void testCounterIteratorConcurrency() { Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); Iterator<Group> iterator = counters.iterator(); counters.incrCounter("group2", "counter2", 1); iterator.next(); } @SuppressWarnings("deprecation") @Test public void testGroupIteratorConcurrency() { Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); Group group = counters.getGroup("group1"); Iterator<Counter> iterator = group.iterator(); counters.incrCounter("group1", "counter2", 1); iterator.next(); } @Test public void testFileSystemGroupIteratorConcurrency() { Counters counters = new Counters(); // create 2 filesystem counter groups counters.findCounter("fs1", FileSystemCounter.BYTES_READ).increment(1); counters.findCounter("fs2", FileSystemCounter.BYTES_READ).increment(1); // Iterate over the counters in this group while updating counters in // the group Group group = counters.getGroup(FileSystemCounter.class.getName()); Iterator<Counter> iterator = group.iterator(); counters.findCounter("fs3", FileSystemCounter.BYTES_READ).increment(1); assertTrue(iterator.hasNext()); iterator.next(); counters.findCounter("fs3", FileSystemCounter.BYTES_READ).increment(1); assertTrue(iterator.hasNext()); iterator.next(); } @Test public void testLegacyGetGroupNames() { Counters counters = new Counters(); // create 2 filesystem counter groups counters.findCounter("fs1", FileSystemCounter.BYTES_READ).increment(1); counters.findCounter("fs2", FileSystemCounter.BYTES_READ).increment(1); counters.incrCounter("group1", "counter1", 1); HashSet<String> groups = new HashSet<String>(counters.getGroupNames()); HashSet<String> expectedGroups = new HashSet<String>(); expectedGroups.add("group1"); expectedGroups.add("FileSystemCounters"); //Legacy Name expectedGroups.add("org.apache.hadoop.mapreduce.FileSystemCounter"); assertEquals(expectedGroups, groups); } @Test public void testMakeCompactString() { final String GC1 = "group1.counter1:1"; final String GC2 = "group2.counter2:3"; Counters counters = new Counters(); counters.incrCounter("group1", "counter1", 1); assertEquals("group1.counter1:1", counters.makeCompactString()); counters.incrCounter("group2", "counter2", 3); String cs = counters.makeCompactString(); assertTrue(cs.equals(GC1 + ',' + GC2) || cs.equals(GC2 + ',' + GC1), "Bad compact string"); } @Test public void testCounterLimits() { testMaxCountersLimits(new Counters()); testMaxGroupsLimits(new Counters()); } private void testMaxCountersLimits(final Counters counters) { for (int i = 0; i < org.apache.hadoop.mapred.Counters.MAX_COUNTER_LIMIT; ++i) { counters.findCounter("test", "test" + i); } setExpected(counters); shouldThrow(CountersExceededException.class, new Runnable() { public void run() { counters.findCounter("test", "bad"); } }); checkExpected(counters); } private void testMaxGroupsLimits(final Counters counters) { for (int i = 0; i < org.apache.hadoop.mapred.Counters.MAX_GROUP_LIMIT; ++i) { // assuming COUNTERS_MAX > GROUPS_MAX counters.findCounter("test" + i, "test"); } setExpected(counters); shouldThrow(CountersExceededException.class, new Runnable() { public void run() { counters.findCounter("bad", "test"); } }); checkExpected(counters); } private void setExpected(Counters counters) { counters.findCounter(FRAMEWORK_COUNTER).setValue(FRAMEWORK_COUNTER_VALUE); counters.findCounter(FS_SCHEME, FS_COUNTER).setValue(FS_COUNTER_VALUE); } private void checkExpected(Counters counters) { assertEquals(FRAMEWORK_COUNTER_VALUE, counters.findCounter(FRAMEWORK_COUNTER).getValue()); assertEquals(FS_COUNTER_VALUE, counters.findCounter(FS_SCHEME, FS_COUNTER) .getValue()); } private void shouldThrow(Class<? extends Exception> ecls, Runnable runnable) { try { runnable.run(); } catch (CountersExceededException e) { return; } fail("Should've thrown " + ecls.getSimpleName()); } public static void main(String[] args) throws IOException { new TestCounters().testCounters(); } @SuppressWarnings("rawtypes") @Test public void testFrameworkCounter() { GroupFactory groupFactory = new GroupFactoryForTest(); FrameworkGroupFactory frameworkGroupFactory = groupFactory.newFrameworkGroupFactory(JobCounter.class); Group group = (Group) frameworkGroupFactory.newGroup("JobCounter"); FrameworkCounterGroup counterGroup = (FrameworkCounterGroup) group.getUnderlyingGroup(); org.apache.hadoop.mapreduce.Counter count1 = counterGroup.findCounter(JobCounter.NUM_FAILED_MAPS.toString()); assertNotNull(count1); // Verify no exception get thrown when finding an unknown counter org.apache.hadoop.mapreduce.Counter count2 = counterGroup.findCounter("Unknown"); assertNull(count2); } @SuppressWarnings("rawtypes") @Test public void testTaskCounter() { GroupFactory groupFactory = new GroupFactoryForTest(); FrameworkGroupFactory frameworkGroupFactory = groupFactory.newFrameworkGroupFactory(TaskCounter.class); Group group = (Group) frameworkGroupFactory.newGroup("TaskCounter"); FrameworkCounterGroup counterGroup = (FrameworkCounterGroup) group.getUnderlyingGroup(); org.apache.hadoop.mapreduce.Counter count1 = counterGroup.findCounter( TaskCounter.PHYSICAL_MEMORY_BYTES.toString()); assertNotNull(count1); count1.increment(10); count1.increment(10); assertEquals(20, count1.getValue()); // Verify no exception get thrown when finding an unknown counter org.apache.hadoop.mapreduce.Counter count2 = counterGroup.findCounter( TaskCounter.MAP_PHYSICAL_MEMORY_BYTES_MAX.toString()); assertNotNull(count2); count2.increment(5); count2.increment(10); assertEquals(10, count2.getValue()); } @Test public void testFilesystemCounter() { GroupFactory groupFactory = new GroupFactoryForTest(); Group fsGroup = groupFactory.newFileSystemGroup(); org.apache.hadoop.mapreduce.Counter count1 = fsGroup.findCounter("ANY_BYTES_READ"); assertNotNull(count1); // Verify no exception get thrown when finding an unknown counter org.apache.hadoop.mapreduce.Counter count2 = fsGroup.findCounter("Unknown"); assertNull(count2); } }
counters
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/ScoredValueUnitTests.java
{ "start": 1081, "end": 4029 }
class ____ { @Test void shouldCreateEmptyScoredValueFromOptional() { Value<String> value = ScoredValue.from(42, Optional.<String> empty()); assertThat(value.hasValue()).isFalse(); } @Test void shouldCreateEmptyValue() { Value<String> value = ScoredValue.empty(); assertThat(value.hasValue()).isFalse(); } @Test void shouldCreateNonEmptyValueFromOptional() { ScoredValue<String> value = (ScoredValue) ScoredValue.from(4.2, Optional.of("hello")); assertThat(value.hasValue()).isTrue(); assertThat(value.getValue()).isEqualTo("hello"); assertThat(value.getScore()).isCloseTo(4.2, offset(0.01)); } @Test void shouldCreateEmptyValueFromValue() { Value<String> value = ScoredValue.fromNullable(42, null); assertThat(value.hasValue()).isFalse(); } @Test void shouldCreateNonEmptyValueFromValue() { ScoredValue<String> value = (ScoredValue<String>) ScoredValue.fromNullable(42, "hello"); assertThat(value.hasValue()).isTrue(); assertThat(value.getValue()).isEqualTo("hello"); } @Test void justShouldCreateValueFromValue() { ScoredValue<String> value = ScoredValue.just(42, "hello"); assertThat(value.hasValue()).isTrue(); assertThat(value.getValue()).isEqualTo("hello"); } @Test void justShouldRejectEmptyValueFromValue() { assertThatThrownBy(() -> ScoredValue.just(null)).isInstanceOf(IllegalArgumentException.class); } @Test void shouldCreateNonEmptyValue() { ScoredValue<String> value = (ScoredValue<String>) ScoredValue.from(12, Optional.of("hello")); assertThat(value.hasValue()).isTrue(); assertThat(value.getValue()).isEqualTo("hello"); } @Test void equals() { ScoredValue<String> sv1 = (ScoredValue<String>) ScoredValue.fromNullable(1.0, "a"); assertThat(sv1.equals(ScoredValue.fromNullable(1.0, "a"))).isTrue(); assertThat(sv1.equals(null)).isFalse(); assertThat(sv1.equals(ScoredValue.fromNullable(1.1, "a"))).isFalse(); assertThat(sv1.equals(ScoredValue.fromNullable(1.0, "b"))).isFalse(); } @Test void testHashCode() { assertThat(ScoredValue.fromNullable(1.0, "a").hashCode() != 0).isTrue(); assertThat(ScoredValue.fromNullable(0.0, "a").hashCode() != 0).isTrue(); assertThat(ScoredValue.fromNullable(0.0, null).hashCode() == 0).isTrue(); } @Test void toStringShouldRenderCorrectly() { ScoredValue<String> value = (ScoredValue<String>) ScoredValue.from(12.34, Optional.of("hello")); Value<String> empty = ScoredValue.fromNullable(34, null); assertThat(value.toString()).contains("ScoredValue[12").contains("340000, hello]"); assertThat(empty.toString()).contains(String.format("ScoredValue[%f].empty", 0d)); } }
ScoredValueUnitTests
java
apache__camel
components/camel-dhis2/camel-dhis2-component/src/test/java/org/apache/camel/component/dhis2/Dhis2PutIT.java
{ "start": 1597, "end": 3494 }
class ____ extends AbstractDhis2TestSupport { private static final Logger LOG = LoggerFactory.getLogger(Dhis2PutIT.class); private static final String PATH_PREFIX = Dhis2ApiCollection.getCollection().getApiName(Dhis2PutApiMethod.class).getName(); @Test public void testResourceGivenInBody() { putResource("direct://RESOURCE_WITH_INBODY"); } @Test public void testResource() { putResource("direct://RESOURCE"); } private void putResource(String endpointUri) { final Map<String, Object> headers = new HashMap<>(); // parameter type is String headers.put("CamelDhis2.path", String.format("organisationUnits/%s", Environment.ORG_UNIT_ID_UNDER_TEST)); // parameter type is java.util.Map headers.put("CamelDhis2.queryParams", new HashMap<>()); String name = RandomStringUtils.randomAlphabetic(8); final java.io.InputStream result = requestBodyAndHeaders(endpointUri, new OrganisationUnit().withName(name).withShortName(name).withOpeningDate(new Date()), headers); OrganisationUnit organisationUnit = Environment.DHIS2_CLIENT.get("organisationUnits/{id}", Environment.ORG_UNIT_ID_UNDER_TEST) .transfer().returnAs(OrganisationUnit.class); assertEquals(name, organisationUnit.getName().get()); assertNotNull(result, "resource result"); LOG.debug("Result: {}", result); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct://RESOURCE_WITH_INBODY") .to("dhis2://" + PATH_PREFIX + "/resource?inBody=resource"); from("direct://RESOURCE") .to("dhis2://" + PATH_PREFIX + "/resource"); } }; } }
Dhis2PutIT
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/archive/scan/spi/ClassDescriptor.java
{ "start": 303, "end": 382 }
enum ____ { MODEL, CONVERTER, OTHER } /** * Retrieves the
Categorization
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/ConnectorSyncJob.java
{ "start": 24282, "end": 28339 }
class ____ { private Instant cancellationRequestedAt; private Instant canceledAt; private Instant completedAt; private Connector connector; private Instant createdAt; private long deletedDocumentCount; private String error; private String id; private long indexedDocumentCount; private long indexedDocumentVolume; private ConnectorSyncJobType jobType; private Instant lastSeen; private Map<String, Object> metadata; private Instant startedAt; private ConnectorSyncStatus status; private long totalDocumentCount; private ConnectorSyncJobTriggerMethod triggerMethod; private String workerHostname; public Builder setCancellationRequestedAt(Instant cancellationRequestedAt) { this.cancellationRequestedAt = cancellationRequestedAt; return this; } public Builder setCanceledAt(Instant canceledAt) { this.canceledAt = canceledAt; return this; } public Builder setCompletedAt(Instant completedAt) { this.completedAt = completedAt; return this; } public Builder setConnector(Connector connector) { this.connector = connector; return this; } public Builder setCreatedAt(Instant createdAt) { this.createdAt = createdAt; return this; } public Builder setDeletedDocumentCount(long deletedDocumentCount) { this.deletedDocumentCount = deletedDocumentCount; return this; } public Builder setError(String error) { this.error = error; return this; } public Builder setId(String id) { this.id = id; return this; } public Builder setIndexedDocumentCount(long indexedDocumentCount) { this.indexedDocumentCount = indexedDocumentCount; return this; } public Builder setIndexedDocumentVolume(long indexedDocumentVolume) { this.indexedDocumentVolume = indexedDocumentVolume; return this; } public Builder setJobType(ConnectorSyncJobType jobType) { this.jobType = jobType; return this; } public Builder setLastSeen(Instant lastSeen) { this.lastSeen = lastSeen; return this; } public Builder setMetadata(Map<String, Object> metadata) { this.metadata = metadata; return this; } public Builder setStartedAt(Instant startedAt) { this.startedAt = startedAt; return this; } public Builder setStatus(ConnectorSyncStatus status) { this.status = status; return this; } public Builder setTotalDocumentCount(long totalDocumentCount) { this.totalDocumentCount = totalDocumentCount; return this; } public Builder setTriggerMethod(ConnectorSyncJobTriggerMethod triggerMethod) { this.triggerMethod = triggerMethod; return this; } public Builder setWorkerHostname(String workerHostname) { this.workerHostname = workerHostname; return this; } public ConnectorSyncJob build() { return new ConnectorSyncJob( cancellationRequestedAt, canceledAt, completedAt, connector, createdAt, deletedDocumentCount, error, id, indexedDocumentCount, indexedDocumentVolume, jobType, lastSeen, metadata, startedAt, status, totalDocumentCount, triggerMethod, workerHostname ); } } }
Builder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/builder/BuilderErrorHandlingTest.java
{ "start": 758, "end": 1225 }
class ____ { int x, y; public SimpleBuilderXY withX(int x0) { this.x = x0; return this; } public SimpleBuilderXY withY(int y0) { this.y = y0; return this; } public ValueClassXY build() { return new ValueClassXY(x, y); } } // [databind#2938] @JsonDeserialize(builder = ValidatingValue.Builder.class) static
SimpleBuilderXY
java
quarkusio__quarkus
integration-tests/hibernate-orm-data/src/main/java/io/quarkus/it/hibernate/processor/data/MyOtherEntityResource.java
{ "start": 829, "end": 1896 }
class ____ { @Inject MyOtherRepository repository; @POST @Transactional public void create(MyOtherEntity entity) { repository.insert(entity); } @GET public List<MyOtherEntity> get() { return repository.findAll(Order.by(Sort.asc(MyOtherEntity_.NAME))).toList(); } @GET @Transactional @Path("/by/name/{name}") public MyOtherEntity getByName(@RestPath String name) { List<MyOtherEntity> entities = repository.findByName(name); if (entities.isEmpty()) { throw new NotFoundException(); } return entities.get(0); } @POST @Transactional @Path("/rename/{before}/to/{after}") public void rename(@RestPath String before, @RestPath String after) { MyOtherEntity byName = getByName(before); byName.name = after; repository.update(byName); } @DELETE @Transactional @Path("/by/name/{name}") public void deleteByName(@RestPath String name) { repository.delete(name); } }
MyOtherEntityResource
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/UWildcardTest.java
{ "start": 998, "end": 1805 }
class ____ { @Test public void equality() { UExpression objectIdent = UClassIdent.create("java.lang.Object"); UExpression setIdent = UTypeApply.create("java.util.Set", objectIdent); new EqualsTester() .addEqualityGroup(UWildcard.create(Kind.UNBOUNDED_WILDCARD, null)) .addEqualityGroup(UWildcard.create(Kind.EXTENDS_WILDCARD, objectIdent)) .addEqualityGroup(UWildcard.create(Kind.EXTENDS_WILDCARD, setIdent)) // ? extends Set<Object> .addEqualityGroup(UWildcard.create(Kind.SUPER_WILDCARD, setIdent)) // ? super Set<Object> .testEquals(); } @Test public void serialization() { SerializableTester.reserializeAndAssert( UWildcard.create(Kind.EXTENDS_WILDCARD, UClassIdent.create("java.lang.Number"))); } }
UWildcardTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/RecursiveIgnoreProperties1755Test.java
{ "start": 897, "end": 1015 }
class ____ { public String key; public String value; } // for [databind#4417] static
KeyValue
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-core-stubs/maven-war-plugin/src/main/java/org/apache/maven/plugin/coreit/WarMojo.java
{ "start": 1430, "end": 2924 }
class ____ extends AbstractMojo { /** * The current Maven project. */ @Parameter(defaultValue = "${project}", required = true, readonly = true) private MavenProject project; /** * The path to the output file, relative to the project base directory. * */ @Parameter private String pathname = "target/war-war.txt"; /** * Runs this mojo. * * @throws MojoExecutionException If the output file could not be created. * @throws MojoFailureException If the output file has not been set. */ public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("[MAVEN-CORE-IT-LOG] Using output file path: " + pathname); if (pathname == null || pathname.length() <= 0) { throw new MojoFailureException("Path name for output file has not been specified"); } File outputFile = new File(pathname); if (!outputFile.isAbsolute()) { outputFile = new File(project.getBasedir(), pathname).getAbsoluteFile(); } getLog().info("[MAVEN-CORE-IT-LOG] Creating output file: " + outputFile); try { outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); } catch (IOException e) { throw new MojoExecutionException("Output file could not be created: " + pathname, e); } getLog().info("[MAVEN-CORE-IT-LOG] Created output file: " + outputFile); } }
WarMojo
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/contracts/services/ListResultEntrySchema.java
{ "start": 922, "end": 2191 }
interface ____ { /** * Get the name value. * @return the name value */ String name(); /** * Set the name value. * @param name the name value to set * @return the ListResultEntrySchema object itself. */ ListResultEntrySchema withName(String name); /** * Get the isDirectory value. * @return the isDirectory value */ Boolean isDirectory(); /** * Get the lastModified value. * @return the lastModified value */ String lastModified(); /** * Get the eTag value. * @return the eTag value */ String eTag(); /** * Get the contentLength value. * @return the contentLength value */ Long contentLength(); /** * Get the owner value. * @return the owner value */ String owner(); /** * Get the group value. * @return the group value */ String group(); /** * Get the permissions value. * @return the permissions value */ String permissions(); /** * Get the encryption context value. * @return the encryption context value */ String getXMsEncryptionContext(); /** * Get the customer-provided encryption-256 value. * @return the customer-provided encryption-256 value */ String getCustomerProvidedKeySha256(); }
ListResultEntrySchema
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ZooKeeperMasterEndpointBuilderFactory.java
{ "start": 7745, "end": 10003 }
interface ____ { /** * ZooKeeper Master (camel-zookeeper-master) * Have only a single consumer in a cluster consuming from a given * endpoint; with automatic failover if the JVM dies. * * Category: clustering,management,bigdata * Since: 2.19 * Maven coordinates: org.apache.camel:camel-zookeeper-master * * Syntax: <code>zookeeper-master:groupName:consumerEndpointUri</code> * * Path parameter: groupName (required) * The name of the cluster group to use * * Path parameter: consumerEndpointUri (required) * The consumer endpoint to use in master/slave mode * * @param path groupName:consumerEndpointUri * @return the dsl builder */ default ZooKeeperMasterEndpointBuilder zookeeperMaster(String path) { return ZooKeeperMasterEndpointBuilderFactory.endpointBuilder("zookeeper-master", path); } /** * ZooKeeper Master (camel-zookeeper-master) * Have only a single consumer in a cluster consuming from a given * endpoint; with automatic failover if the JVM dies. * * Category: clustering,management,bigdata * Since: 2.19 * Maven coordinates: org.apache.camel:camel-zookeeper-master * * Syntax: <code>zookeeper-master:groupName:consumerEndpointUri</code> * * Path parameter: groupName (required) * The name of the cluster group to use * * Path parameter: consumerEndpointUri (required) * The consumer endpoint to use in master/slave mode * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path groupName:consumerEndpointUri * @return the dsl builder */ default ZooKeeperMasterEndpointBuilder zookeeperMaster(String componentName, String path) { return ZooKeeperMasterEndpointBuilderFactory.endpointBuilder(componentName, path); } } static ZooKeeperMasterEndpointBuilder endpointBuilder(String componentName, String path) {
ZooKeeperMasterBuilders
java
apache__spark
core/src/main/java/org/apache/spark/api/java/StorageLevels.java
{ "start": 956, "end": 2692 }
class ____ { public static final StorageLevel NONE = create(false, false, false, false, 1); public static final StorageLevel DISK_ONLY = create(true, false, false, false, 1); public static final StorageLevel DISK_ONLY_2 = create(true, false, false, false, 2); public static final StorageLevel DISK_ONLY_3 = create(true, false, false, false, 3); public static final StorageLevel MEMORY_ONLY = create(false, true, false, true, 1); public static final StorageLevel MEMORY_ONLY_2 = create(false, true, false, true, 2); public static final StorageLevel MEMORY_ONLY_SER = create(false, true, false, false, 1); public static final StorageLevel MEMORY_ONLY_SER_2 = create(false, true, false, false, 2); public static final StorageLevel MEMORY_AND_DISK = create(true, true, false, true, 1); public static final StorageLevel MEMORY_AND_DISK_2 = create(true, true, false, true, 2); public static final StorageLevel MEMORY_AND_DISK_SER = create(true, true, false, false, 1); public static final StorageLevel MEMORY_AND_DISK_SER_2 = create(true, true, false, false, 2); public static final StorageLevel OFF_HEAP = create(true, true, true, false, 1); /** * Create a new StorageLevel object. * @param useDisk saved to disk, if true * @param useMemory saved to on-heap memory, if true * @param useOffHeap saved to off-heap memory, if true * @param deserialized saved as deserialized objects, if true * @param replication replication factor */ public static StorageLevel create( boolean useDisk, boolean useMemory, boolean useOffHeap, boolean deserialized, int replication) { return StorageLevel.apply(useDisk, useMemory, useOffHeap, deserialized, replication); } }
StorageLevels
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/throttling/ThrottlingInflightRoutePolicy.java
{ "start": 3139, "end": 11635 }
enum ____ { Context, Route } private final Set<Route> routes = new LinkedHashSet<>(); private ContextScopedEventNotifier eventNotifier; private CamelContext camelContext; private final Lock lock = new ReentrantLock(); @Metadata(description = "Sets which scope the throttling should be based upon, either route or total scoped.", enums = "Context,Route", defaultValue = "Route") private ThrottlingScope scope = ThrottlingScope.Route; @Metadata(description = "Sets the upper limit of number of concurrent inflight exchanges at which point reached the throttler should suspend the route.", defaultValue = "1000") private int maxInflightExchanges = 1000; @Metadata(description = "Sets at which percentage of the max the throttler should start resuming the route.", defaultValue = "70") private int resumePercentOfMax = 70; private int resumeInflightExchanges = 700; @Metadata(description = "Sets the logging level to report the throttling activity.", javaType = "org.apache.camel.LoggingLevel", defaultValue = "INFO", enums = "TRACE,DEBUG,INFO,WARN,ERROR,OFF") private LoggingLevel loggingLevel = LoggingLevel.INFO; private CamelLogger logger; public ThrottlingInflightRoutePolicy() { } @Override public String toString() { return "ThrottlingInflightRoutePolicy[" + maxInflightExchanges + " / " + resumePercentOfMax + "% using scope " + scope + "]"; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public void onInit(Route route) { // we need to remember the routes we apply for routes.add(route); } @Override public void onExchangeDone(Route route, Exchange exchange) { // if route scoped then throttle directly // as context scoped is handled using an EventNotifier instead if (scope == ThrottlingScope.Route) { throttle(route, exchange); } } /** * Throttles the route when {@link Exchange}s is done. * * @param route the route * @param exchange the exchange */ protected void throttle(Route route, Exchange exchange) { // this works the best when this logic is executed when the exchange is done Consumer consumer = route.getConsumer(); int size = getSize(route, exchange); boolean stop = maxInflightExchanges > 0 && size > maxInflightExchanges; if (LOG.isTraceEnabled()) { LOG.trace("{} > 0 && {} > {} evaluated as {}", maxInflightExchanges, size, maxInflightExchanges, stop); } if (stop) { try { lock.lock(); stopConsumer(size, consumer); } catch (Exception e) { handleException(e); } finally { lock.unlock(); } } // reload size in case a race condition with too many at once being invoked // so we need to ensure that we read the most current size and start the consumer if we are already to low size = getSize(route, exchange); boolean start = size <= resumeInflightExchanges; if (LOG.isTraceEnabled()) { LOG.trace("{} <= {} evaluated as {}", size, resumeInflightExchanges, start); } if (start) { try { lock.lock(); startConsumer(size, consumer); } catch (Exception e) { handleException(e); } finally { lock.unlock(); } } } public int getMaxInflightExchanges() { return maxInflightExchanges; } /** * Sets the upper limit of number of concurrent inflight exchanges at which point reached the throttler should * suspend the route. * <p/> * Is default 1000. * * @param maxInflightExchanges the upper limit of concurrent inflight exchanges */ public void setMaxInflightExchanges(int maxInflightExchanges) { this.maxInflightExchanges = maxInflightExchanges; // recalculate, must be at least at 1 this.resumeInflightExchanges = Math.max(resumePercentOfMax * maxInflightExchanges / 100, 1); } public int getResumePercentOfMax() { return resumePercentOfMax; } /** * Sets at which percentage of the max the throttler should start resuming the route. * <p/> * Will by default use 70%. * * @param resumePercentOfMax the percentage must be between 0 and 100 */ public void setResumePercentOfMax(int resumePercentOfMax) { if (resumePercentOfMax < 0 || resumePercentOfMax > 100) { throw new IllegalArgumentException("Must be a percentage between 0 and 100, was: " + resumePercentOfMax); } this.resumePercentOfMax = resumePercentOfMax; // recalculate, must be at least at 1 this.resumeInflightExchanges = Math.max(resumePercentOfMax * maxInflightExchanges / 100, 1); } public ThrottlingScope getScope() { return scope; } /** * Sets which scope the throttling should be based upon, either route or total scoped. * * @param scope the scope */ public void setScope(ThrottlingScope scope) { this.scope = scope; } public LoggingLevel getLoggingLevel() { return loggingLevel; } public CamelLogger getLogger() { if (logger == null) { logger = createLogger(); } return logger; } /** * Sets the logger to use for logging throttling activity. * * @param logger the logger */ public void setLogger(CamelLogger logger) { this.logger = logger; } /** * Sets the logging level to report the throttling activity. * <p/> * Is default <tt>INFO</tt> level. * * @param loggingLevel the logging level */ public void setLoggingLevel(LoggingLevel loggingLevel) { this.loggingLevel = loggingLevel; } protected CamelLogger createLogger() { return new CamelLogger(LOG, getLoggingLevel()); } private int getSize(Route route, Exchange exchange) { if (scope == ThrottlingScope.Context) { return exchange.getContext().getInflightRepository().size(); } else { return exchange.getContext().getInflightRepository().size(route.getId()); } } private void startConsumer(int size, Consumer consumer) throws Exception { boolean started = resumeOrStartConsumer(consumer); if (started) { getLogger().log("Throttling consumer: " + size + " <= " + resumeInflightExchanges + " inflight exchange by resuming consumer: " + consumer); } } private void stopConsumer(int size, Consumer consumer) throws Exception { boolean stopped = suspendOrStopConsumer(consumer); if (stopped) { getLogger().log("Throttling consumer: " + size + " > " + maxInflightExchanges + " inflight exchange by suspending consumer: " + consumer); } } @Override protected void doStart() throws Exception { ObjectHelper.notNull(camelContext, "CamelContext", this); if (scope == ThrottlingScope.Context) { eventNotifier = new ContextScopedEventNotifier(); // must start the notifier before it can be used ServiceHelper.startService(eventNotifier); // we are in context scope, so we need to use an event notifier to keep track // when any exchanges is done on the camel context. // This ensures we can trigger accordingly to context scope camelContext.getManagementStrategy().addEventNotifier(eventNotifier); } } @Override protected void doStop() throws Exception { ObjectHelper.notNull(camelContext, "CamelContext", this); if (scope == ThrottlingScope.Context) { camelContext.getManagementStrategy().removeEventNotifier(eventNotifier); } } /** * {@link org.apache.camel.spi.EventNotifier} to keep track on when {@link Exchange} is done, so we can throttle * accordingly. */ private
ThrottlingScope
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/ViewFsLocatedFileStatus.java
{ "start": 1092, "end": 2874 }
class ____ extends LocatedFileStatus { final LocatedFileStatus myFs; Path modifiedPath; ViewFsLocatedFileStatus(LocatedFileStatus locatedFileStatus, Path path) { myFs = locatedFileStatus; modifiedPath = path; } @Override public long getLen() { return myFs.getLen(); } @Override public boolean isFile() { return myFs.isFile(); } @Override public boolean isDirectory() { return myFs.isDirectory(); } @Override public boolean isSymlink() { return myFs.isSymlink(); } @Override public long getBlockSize() { return myFs.getBlockSize(); } @Override public short getReplication() { return myFs.getReplication(); } @Override public long getModificationTime() { return myFs.getModificationTime(); } @Override public long getAccessTime() { return myFs.getAccessTime(); } @Override public FsPermission getPermission() { return myFs.getPermission(); } @Override public String getOwner() { return myFs.getOwner(); } @Override public String getGroup() { return myFs.getGroup(); } @Override public Path getPath() { return modifiedPath; } @Override public void setPath(final Path p) { modifiedPath = p; } @Override public Path getSymlink() throws IOException { return myFs.getSymlink(); } @Override public void setSymlink(Path p) { myFs.setSymlink(p); } @Override public BlockLocation[] getBlockLocations() { return myFs.getBlockLocations(); } @Override public int compareTo(FileStatus o) { return super.compareTo(o); } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } }
ViewFsLocatedFileStatus
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/persister/filter/internal/StaticFilterAliasGenerator.java
{ "start": 250, "end": 498 }
class ____ implements FilterAliasGenerator { private final String alias; public StaticFilterAliasGenerator(String alias) { this.alias = alias; } @Override public String getAlias(String table) { return alias; } }
StaticFilterAliasGenerator
java
apache__camel
components/camel-olingo2/camel-olingo2-api/src/main/java/org/apache/camel/component/olingo2/api/impl/Olingo2Helper.java
{ "start": 1005, "end": 1433 }
class ____ { private Olingo2Helper() { } /** * Gets the content type header in a safe way */ public static ContentType getContentTypeHeader(HttpResponse response) { if (response.containsHeader(HttpHeaders.CONTENT_TYPE)) { return ContentType.parse(response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); } else { return null; } } }
Olingo2Helper
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/joincolumn/JoinColumnTest.java
{ "start": 967, "end": 3821 }
class ____ { @Test public void testIt(ServiceRegistryScope scope) { try (SessionFactoryImplementor sf = (SessionFactoryImplementor) new MetadataSources( scope.getRegistry() ) .addAnnotatedClass( Company.class ) .addAnnotatedClass( Location.class ) .buildMetadata() .buildSessionFactory()) { try { inTransaction( sf, session -> { final Company acme = new Company( 1, "Acme Corp" ); new Location( 1, "86-215", acme ); new Location( 2, "20-759", acme ); session.persist( acme ); } ); inTransaction( sf, session -> { final Company acme = session.find( Company.class, 1 ); assert acme.getLocations().size() == 2; // this fails. however it is due to a number of bad assumptions // in the TCK: // First the spec says: // // {quote} // The relationship modeling annotation constrains the use of the cascade=REMOVE specification. The // cascade=REMOVE specification should only be applied to associations that are specified as One- // ToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not por- // table. // {quote} // // Here the test is applying cascade=REMOVE to a ManyToOne. // // Secondly, the spec says: // // {quote} // The persistence provider runtime is permitted to perform synchronization to the database at other times // as well when a transaction is active and the persistence context is joined to the transaction. // {quote} // // // In other words, the provider is actually legal to perform the database delete immediately. Since // the TCK deletes the Company first, a provider is legally able to perform the database delete on // Company immediately. However the TCK test as defined makes this impossible: // 1) simply deleting Company won't work since Location rows still reference it. Locations // would need to be deleted first (cascade the remove to the @OneToMany `locations` // attribute), or // 2) perform a SQL update, updating the COMP_ID columns in the Location table to be null // so that deleting Company wont cause FK violations. But again this is made impossible // by the TCK because it defines the column as non-nullable (and not even in the @JoinColumn // btw which would be another basis for challenge). session.remove( acme ); for ( Location location : acme.getLocations() ) { session.remove( location ); } } ); } finally { inTransaction( sf, session -> { session.createQuery( "delete Location" ).executeUpdate(); session.createQuery( "delete Company" ).executeUpdate(); } ); } } } }
JoinColumnTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/aggregate/CollectAggFunction.java
{ "start": 2908, "end": 5290 }
class ____<T> { public MapView<T, Integer> map; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CollectAccumulator<?> that = (CollectAccumulator<?>) o; return Objects.equals(map, that.map); } } public CollectAccumulator<T> createAccumulator() { final CollectAccumulator<T> acc = new CollectAccumulator<>(); acc.map = new MapView<>(); return acc; } public void resetAccumulator(CollectAccumulator<T> accumulator) { accumulator.map.clear(); } public void accumulate(CollectAccumulator<T> accumulator, T value) throws Exception { if (value != null) { Integer count = accumulator.map.get(value); if (count != null) { accumulator.map.put(value, count + 1); } else { accumulator.map.put(value, 1); } } } public void retract(CollectAccumulator<T> accumulator, T value) throws Exception { if (value != null) { Integer count = accumulator.map.get(value); if (count != null) { if (count == 1) { accumulator.map.remove(value); } else { accumulator.map.put(value, count - 1); } } else { accumulator.map.put(value, -1); } } } public void merge(CollectAccumulator<T> accumulator, Iterable<CollectAccumulator<T>> others) throws Exception { for (CollectAccumulator<T> other : others) { for (Map.Entry<T, Integer> entry : other.map.entries()) { T key = entry.getKey(); Integer newCount = entry.getValue(); Integer oldCount = accumulator.map.get(key); if (oldCount == null) { accumulator.map.put(key, newCount); } else { accumulator.map.put(key, oldCount + newCount); } } } } @Override public MapData getValue(CollectAccumulator<T> accumulator) { return new GenericMapData(accumulator.map.getMap()); } }
CollectAccumulator
java
apache__avro
lang/java/ipc-jetty/src/main/java/org/apache/avro/ipc/jetty/StaticServlet.java
{ "start": 1042, "end": 1643 }
class ____ extends DefaultServlet { private static final long serialVersionUID = 1L; @Override public Resource getResource(String pathInContext) { // Take only last slice of the URL as a filename, so we can adjust path. // This also prevents mischief like '../../foo.css' String[] parts = pathInContext.split("/"); String filename = parts[parts.length - 1]; URL resource = getClass().getClassLoader().getResource("org/apache/avro/ipc/stats/static/" + filename); if (resource == null) { return null; } return Resource.newResource(resource); } }
StaticServlet
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/extension/eventtime/EventTimeWatermarkCombiner.java
{ "start": 3228, "end": 4987 }
class ____<T> implements DataOutput<T> { private Consumer<Watermark> watermarkEmitter; public WrappedDataOutput() {} public void setWatermarkEmitter(Consumer<Watermark> watermarkEmitter) { this.watermarkEmitter = watermarkEmitter; } @Override public void emitRecord(StreamRecord<T> streamRecord) throws Exception { throw new RuntimeException("Should not emit records with this output."); } @Override public void emitWatermark(org.apache.flink.streaming.api.watermark.Watermark watermark) throws Exception { watermarkEmitter.accept( EventTimeExtension.EVENT_TIME_WATERMARK_DECLARATION.newWatermark( watermark.getTimestamp())); } @Override public void emitWatermarkStatus(WatermarkStatus watermarkStatus) throws Exception { watermarkEmitter.accept( EventTimeExtension.IDLE_STATUS_WATERMARK_DECLARATION.newWatermark( watermarkStatus.isIdle())); } @Override public void emitLatencyMarker(LatencyMarker latencyMarker) throws Exception { throw new RuntimeException("Should not emit LatencyMarker with this output."); } @Override public void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception { throw new RuntimeException("Should not emit RecordAttributes with this output."); } @Override public void emitWatermark(WatermarkEvent watermark) throws Exception { throw new RuntimeException("Should not emit WatermarkEvent with this output."); } } }
WrappedDataOutput
java
spring-projects__spring-security
test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java
{ "start": 8162, "end": 8435 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .securityMatcher(pathPattern("/willnotmatchthis")); return http.build(); // @formatter:on } } @Configuration static
PartialSecurityConfig
java
spring-projects__spring-framework
framework-docs/src/main/java/org/springframework/docs/testing/mockmvc/assertj/mockmvctesterrequestsasync/AsyncControllerTests.java
{ "start": 874, "end": 1193 }
class ____ { private final MockMvcTester mockMvc = MockMvcTester.of(new AsyncController()); void asyncExchangeWithCustomTimeToWait() { // tag::duration[] assertThat(mockMvc.get().uri("/compute").exchange(Duration.ofSeconds(5))) . // ... // end::duration[] hasStatusOk(); } static
AsyncControllerTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/byte_/ByteAssert_isPositive_Test.java
{ "start": 878, "end": 1182 }
class ____ extends ByteAssertBaseTest { @Override protected ByteAssert invoke_api_method() { return assertions.isPositive(); } @Override protected void verify_internal_effects() { verify(bytes).assertIsPositive(getInfo(assertions), getActual(assertions)); } }
ByteAssert_isPositive_Test
java
spring-projects__spring-boot
module/spring-boot-session/src/test/java/org/springframework/boot/session/actuate/endpoint/ReactiveSessionsEndpointWebIntegrationTests.java
{ "start": 1592, "end": 4419 }
class ____ { private static final Session session = new MapSession(); @SuppressWarnings("unchecked") private static final ReactiveSessionRepository<Session> sessionRepository = mock(ReactiveSessionRepository.class); @SuppressWarnings("unchecked") private static final ReactiveFindByIndexNameSessionRepository<Session> indexedSessionRepository = mock( ReactiveFindByIndexNameSessionRepository.class); @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void sessionsForUsernameWithoutUsernameParam(WebTestClient client) { client.get() .uri((builder) -> builder.path("/actuator/sessions").build()) .exchange() .expectStatus() .is4xxClientError(); } @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void sessionsForUsernameNoResults(WebTestClient client) { given(indexedSessionRepository.findByPrincipalName("user")).willReturn(Mono.just(Collections.emptyMap())); client.get() .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) .exchange() .expectStatus() .isOk() .expectBody() .jsonPath("sessions") .isEmpty(); } @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void sessionsForUsernameFound(WebTestClient client) { given(indexedSessionRepository.findByPrincipalName("user")) .willReturn(Mono.just(Collections.singletonMap(session.getId(), session))); client.get() .uri((builder) -> builder.path("/actuator/sessions").queryParam("username", "user").build()) .exchange() .expectStatus() .isOk() .expectBody() .jsonPath("sessions.[*].id") .isEqualTo(new JSONArray().appendElement(session.getId())); } @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void sessionForIdFound(WebTestClient client) { given(sessionRepository.findById(session.getId())).willReturn(Mono.just(session)); client.get() .uri((builder) -> builder.path("/actuator/sessions/{id}").build(session.getId())) .exchange() .expectStatus() .isOk() .expectBody() .jsonPath("id") .isEqualTo(session.getId()); } @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void sessionForIdNotFound(WebTestClient client) { given(sessionRepository.findById("not-found")).willReturn(Mono.empty()); client.get() .uri((builder) -> builder.path("/actuator/sessions/not-found").build()) .exchange() .expectStatus() .isNotFound(); } @WebEndpointTest(infrastructure = Infrastructure.WEBFLUX) void deleteSession(WebTestClient client) { given(sessionRepository.deleteById(session.getId())).willReturn(Mono.empty()); client.delete() .uri((builder) -> builder.path("/actuator/sessions/{id}").build(session.getId())) .exchange() .expectStatus() .isNoContent(); } @Configuration(proxyBeanMethods = false) static
ReactiveSessionsEndpointWebIntegrationTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/DelegatingSSLSocketFactory.java
{ "start": 3106, "end": 10215 }
enum ____ { OpenSSL, Default, Default_JSSE, Default_JSSE_with_GCM } private static DelegatingSSLSocketFactory instance = null; private static final Logger LOG = LoggerFactory.getLogger( DelegatingSSLSocketFactory.class); private String providerName; private SSLContext ctx; private String[] ciphers; private SSLChannelMode channelMode; // This should only be modified within the #initializeDefaultFactory // method which is synchronized private boolean openSSLProviderRegistered; /** * Initialize a singleton SSL socket factory. * * @param preferredMode applicable only if the instance is not initialized. * @throws IOException if an error occurs. */ public static synchronized void initializeDefaultFactory( SSLChannelMode preferredMode) throws IOException { if (instance == null) { instance = new DelegatingSSLSocketFactory(preferredMode); } } /** * For testing only: reset the socket factory. */ @VisibleForTesting public static synchronized void resetDefaultFactory() { LOG.info("Resetting default SSL Socket Factory"); instance = null; } /** * Singleton instance of the SSLSocketFactory. * * SSLSocketFactory must be initialized with appropriate SSLChannelMode * using initializeDefaultFactory method. * * @return instance of the SSLSocketFactory, instance must be initialized by * initializeDefaultFactory. */ public static DelegatingSSLSocketFactory getDefaultFactory() { return instance; } private DelegatingSSLSocketFactory(SSLChannelMode preferredChannelMode) throws IOException { try { initializeSSLContext(preferredChannelMode); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new IOException(e); } // Get list of supported cipher suits from the SSL factory. SSLSocketFactory factory = ctx.getSocketFactory(); String[] defaultCiphers = factory.getSupportedCipherSuites(); String version = System.getProperty("java.version"); ciphers = (channelMode == SSLChannelMode.Default_JSSE && version.startsWith("1.8")) ? alterCipherList(defaultCiphers) : defaultCiphers; providerName = ctx.getProvider().getName() + "-" + ctx.getProvider().getVersion(); } private void initializeSSLContext(SSLChannelMode preferredChannelMode) throws NoSuchAlgorithmException, KeyManagementException, IOException { LOG.debug("Initializing SSL Context to channel mode {}", preferredChannelMode); switch (preferredChannelMode) { case Default: try { bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; } catch (LinkageError | NoSuchAlgorithmException | RuntimeException e) { LOG.debug("Failed to load OpenSSL. Falling back to the JSSE default.", e); ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; } break; case OpenSSL: bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; break; case Default_JSSE: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; break; case Default_JSSE_with_GCM: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE_with_GCM; break; default: throw new IOException("Unknown channel mode: " + preferredChannelMode); } } /** * Bind to the OpenSSL provider via wildfly. * This MUST be the only place where wildfly classes are referenced, * so ensuring that any linkage problems only surface here where they may * be caught by the initialization code. */ private void bindToOpenSSLProvider() throws NoSuchAlgorithmException, KeyManagementException { if (!openSSLProviderRegistered) { LOG.debug("Attempting to register OpenSSL provider"); org.wildfly.openssl.OpenSSLProvider.register(); openSSLProviderRegistered = true; } // Strong reference needs to be kept to logger until initialization of // SSLContext finished (see HADOOP-16174): java.util.logging.Logger logger = java.util.logging.Logger.getLogger( "org.wildfly.openssl.SSL"); Level originalLevel = logger.getLevel(); try { logger.setLevel(Level.WARNING); ctx = SSLContext.getInstance("openssl.TLS"); ctx.init(null, null, null); } finally { logger.setLevel(originalLevel); } } public String getProviderName() { return providerName; } @Override public String[] getDefaultCipherSuites() { return ciphers.clone(); } @Override public String[] getSupportedCipherSuites() { return ciphers.clone(); } /** * Get the channel mode of this instance. * @return a channel mode. */ public SSLChannelMode getChannelMode() { return channelMode; } public Socket createSocket() throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket(factory.createSocket()); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket( factory.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket(factory .createSocket(address, port, localAddress, localPort)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket(factory .createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket(factory.createSocket(host, port)); } @Override public Socket createSocket(String host, int port) throws IOException { SSLSocketFactory factory = ctx.getSocketFactory(); return configureSocket(factory.createSocket(host, port)); } private Socket configureSocket(Socket socket) { ((SSLSocket) socket).setEnabledCipherSuites(ciphers); return socket; } private String[] alterCipherList(String[] defaultCiphers) { ArrayList<String> preferredSuites = new ArrayList<>(); // Remove GCM mode based ciphers from the supported list. for (int i = 0; i < defaultCiphers.length; i++) { if (defaultCiphers[i].contains("_GCM_")) { LOG.debug("Removed Cipher - {} from list of enabled SSLSocket ciphers", defaultCiphers[i]); } else { preferredSuites.add(defaultCiphers[i]); } } ciphers = preferredSuites.toArray(new String[0]); return ciphers; } }
SSLChannelMode
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/JpaJandexScavenger.java
{ "start": 24503, "end": 25088 }
class ____ the reflective list with full method and field access. * Add the superclasses recursively as well as the interfaces. * Un-indexed classes/interfaces are accumulated to be thrown as a configuration error in the top level caller method * <p> * TODO should we also return the return types of all methods and fields? It could contain Enums for example. */ private void addClassHierarchyToReflectiveList(Collector collector, DotName className) { if (className == null || isIgnored(className)) { // bail out if java.lang.Object or a
to
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/FunctionScorePluginIT.java
{ "start": 2184, "end": 4314 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(CustomDistanceScorePlugin.class); } public void testPlugin() throws Exception { indicesAdmin().prepareCreate("test") .setMapping( jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("test") .field("type", "text") .endObject() .startObject("num1") .field("type", "date") .endObject() .endObject() .endObject() .endObject() ) .get(); clusterAdmin().prepareHealth(TEST_REQUEST_TIMEOUT).setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().get(); client().index( new IndexRequest("test").id("1") .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-26").endObject()) ).actionGet(); client().index( new IndexRequest("test").id("2") .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-27").endObject()) ).actionGet(); client().admin().indices().prepareRefresh().get(); DecayFunctionBuilder<?> gfb = new CustomDistanceScoreBuilder("num1", "2013-05-28", "+1d"); assertNoFailuresAndResponse( client().search( new SearchRequest(new String[] {}).searchType(SearchType.QUERY_THEN_FETCH) .source(searchSource().explain(false).query(functionScoreQuery(termQuery("test", "value"), gfb))) ), response -> { SearchHits sh = response.getHits(); assertThat(sh.getHits().length, equalTo(2)); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat(sh.getAt(1).getId(), equalTo("2")); } ); } public static
FunctionScorePluginIT
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/HasIdentifierTest.java
{ "start": 2200, "end": 2809 }
class ____ { A() { int foo = 1; int bar = foo; } } """); assertCompiles( methodHasIdentifierMatching( /* shouldMatch= */ true, hasIdentifier( new Matcher<IdentifierTree>() { @Override public boolean matches(IdentifierTree tree, VisitorState state) { return tree.getName().contentEquals("foo"); } }))); } @Test public void shouldMatchParam() { writeFile( "A.java", """ public
A
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/retry/RetryPolicies.java
{ "start": 8340, "end": 8914 }
class ____ implements RetryPolicy { @Override public RetryAction shouldRetry(Exception e, int retries, int failovers, boolean isIdempotentOrAtMostOnce) throws Exception { return RetryAction.RETRY; } } /** * Retry up to maxRetries. * The actual sleep time of the n-th retry is f(n, sleepTime), * where f is a function provided by the subclass implementation. * * The object of the subclasses should be immutable; * otherwise, the subclass must override hashCode(), equals(..) and toString(). */ static abstract
RetryForever
java
apache__camel
components/camel-platform-http-main/src/test/java/org/apache/camel/component/platform/http/main/authentication/AuthenticationConfigurationMainHttpServerTest.java
{ "start": 1060, "end": 1506 }
class ____ { @Test public void testIncompleteAuthenticationConfiguration() { Main main = new Main(); main.setPropertyPlaceholderLocations("incomplete-auth.properties"); main.configure().addRoutesBuilder(new PlatformHttpRouteBuilder()); main.enableTrace(); assertThrows(RuntimeException.class, main::start); main.stop(); } private static
AuthenticationConfigurationMainHttpServerTest
java
quarkusio__quarkus
test-framework/vertx/src/main/java/io/quarkus/test/vertx/UniAsserter.java
{ "start": 1132, "end": 4839 }
interface ____ { /** * Perform a custom assertion on the value of the {@code Uni} in cases where no exception was thrown. * <p> * If an exception is expected, then one of {@link #assertFailedWith} methods should be used. */ <T> UniAsserter assertThat(Supplier<Uni<T>> uni, Consumer<T> asserter); /** * Execute some arbitrary operation as part of the pipeline. */ <T> UniAsserter execute(Supplier<Uni<T>> uni); /** * Execute some arbitrary operation as part of the pipeline. */ UniAsserter execute(Runnable c); /** * Assert that the value of the {@code Uni} is equal to the expected value. * If both are {@code null}, they are considered equal. * * @see Object#equals(Object) */ <T> UniAsserter assertEquals(Supplier<Uni<T>> uni, T t); /** * Assert that the value of the {@code Uni} is not equal to the expected value. * Fails if both are {@code null}. * * @see Object#equals(Object) */ <T> UniAsserter assertNotEquals(Supplier<Uni<T>> uni, T t); /** * Assert that the value of the {@code Uni} and the expected value refer to the same object. */ <T> UniAsserter assertSame(Supplier<Uni<T>> uni, T t); /** * Assert that the value of the {@code Uni} and the expected value do not refer to the same object. */ <T> UniAsserter assertNotSame(Supplier<Uni<T>> uni, T t); /** * Assert that the value of the {@code Uni} is {@code null}. * <p> * If an exception is expected, then one of {@link #assertFailedWith} methods should be used. */ <T> UniAsserter assertNull(Supplier<Uni<T>> uni); /** * Assert that the value of the {@code Uni} is not {@code null}. * <p> * If an exception is expected, then one of {@link #assertFailedWith} methods should be used. */ <T> UniAsserter assertNotNull(Supplier<Uni<T>> uni); // WARNING: this method is called via reflection by io.quarkus.hibernate.reactive.panache.common.runtime.TestReactiveTransactionalInterceptor @SuppressWarnings("unused") <T> UniAsserter surroundWith(Function<Uni<T>, Uni<T>> uni); /** * Ensure that the whole pipeline always fails */ UniAsserter fail(); /** * Assert that the value of the {@code Uni} is {@code true}. */ UniAsserter assertTrue(Supplier<Uni<Boolean>> uni); /** * Assert that the value of the {@code Uni} is {@code false}. */ UniAsserter assertFalse(Supplier<Uni<Boolean>> uni); /** * Used to determine whether the {@code Uni} contains the expected failure. * The assertions fail if the {@code Uni} does not fail. * * @param c Consumer that performs custom assertions on whether the failure matches expectations. This allows * asserting on anything present in the {@code Throwable} like, the cause or the message */ <T> UniAsserter assertFailedWith(Supplier<Uni<T>> uni, Consumer<Throwable> c); /** * Used to determine whether the {@code Uni} contains the expected failure type. * The assertions fail if the {@code Uni} does not fail. */ <T> UniAsserter assertFailedWith(Supplier<Uni<T>> uni, Class<? extends Throwable> c); /** * @return the test data associated with the given key, or {@code null} * @see #putData(String, Object) */ Object getData(String key); /** * Associate the value with the given key. * * @return the previous value, or {@code null} if there was no data for the given key */ Object putData(String key, Object value); /** * Clear the test data. */ void clearData(); }
UniAsserter
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/type/AbstractMethodMetadataTests.java
{ "start": 8044, "end": 8174 }
class ____ { @Tag @MetaAnnotation public abstract String test(); } @Retention(RetentionPolicy.RUNTIME) @
WithMetaAnnotation
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customproviders/UniResponseRequestFilter.java
{ "start": 337, "end": 1156 }
class ____ { @ServerRequestFilter Uni<Response> uniResponse(UriInfo uriInfo, HttpHeaders httpHeaders, ContainerRequestContext requestContext) { String exceptionHeader = httpHeaders.getHeaderString("some-other-uni-exception-input"); if ((exceptionHeader != null) && !exceptionHeader.isEmpty()) { return Uni.createFrom().item(Response.serverError().entity(exceptionHeader).build()); } return Uni.createFrom().deferred(() -> { String inputHeader = httpHeaders.getHeaderString("some-other-uni-input"); if (inputHeader != null) { requestContext.getHeaders().putSingle("custom-uni-header", uriInfo.getPath() + "-" + inputHeader); } return Uni.createFrom().nullItem(); }); } }
UniResponseRequestFilter
java
apache__camel
components/camel-xmlsecurity/src/main/java/org/apache/camel/component/xmlsecurity/processor/XmlSignerProcessor.java
{ "start": 43906, "end": 47933 }
class ____ { private XMLSignatureFactory signatureFactory; private String signatureAlgorithm; private Node parent; private Node messageBodyNode; private Message message; private KeyInfo keyInfo; private String contentDigestAlgorithm; private String signatureId; private String contentReferenceUri; private SignatureType signatureType; private String prefixForXmlSignatureNamespace; public InputBuilder signatureFactory(XMLSignatureFactory signatureFactory) { this.signatureFactory = signatureFactory; return this; } public InputBuilder signatureAlgorithm(String signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; return this; } public InputBuilder parent(Node parent) { this.parent = parent; return this; } public InputBuilder messageBodyNode(Node messageBodyNode) { this.messageBodyNode = messageBodyNode; return this; } public InputBuilder message(Message message) { this.message = message; return this; } public InputBuilder keyInfo(KeyInfo keyInfo) { this.keyInfo = keyInfo; return this; } public InputBuilder contentDigestAlgorithm(String contentDigestAlgorithm) { this.contentDigestAlgorithm = contentDigestAlgorithm; return this; } public InputBuilder signatureId(String signatureId) { this.signatureId = signatureId; return this; } public InputBuilder contentReferenceUri(String contentReferenceUri) { this.contentReferenceUri = contentReferenceUri; return this; } public InputBuilder signatureType(SignatureType signatureType) { this.signatureType = signatureType; return this; } public InputBuilder prefixForXmlSignatureNamespace(String prefixForXmlSignatureNamespace) { this.prefixForXmlSignatureNamespace = prefixForXmlSignatureNamespace; return this; } public XmlSignatureProperties.Input build() { return new XmlSignatureProperties.Input() { @Override public XMLSignatureFactory getSignatureFactory() { return signatureFactory; } @Override public String getSignatureAlgorithm() { return signatureAlgorithm; } @Override public Node getParent() { return parent; } @Override public Node getMessageBodyNode() { return messageBodyNode; } @Override public Message getMessage() { return message; } @Override public KeyInfo getKeyInfo() { return keyInfo; } @Override public String getContentDigestAlgorithm() { return contentDigestAlgorithm; } @Override public String getSignatureId() { return signatureId; } @Override public String getContentReferenceUri() { return contentReferenceUri; } @Override public SignatureType getSignatureType() { return signatureType; } @Override public String getPrefixForXmlSignatureNamespace() { return prefixForXmlSignatureNamespace; } }; } } /** Compares nodes by their hierarchy level. */ static
InputBuilder
java
elastic__elasticsearch
x-pack/plugin/async-search/src/test/java/org/elasticsearch/xpack/search/AsyncSearchSingleNodeTests.java
{ "start": 7076, "end": 7927 }
class ____ extends Plugin implements SearchPlugin { @Override public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) { return Collections.singletonList(searchContext -> new FetchSubPhaseProcessor() { @Override public void setNextReader(LeafReaderContext readerContext) {} @Override public StoredFieldsSpec storedFieldsSpec() { return StoredFieldsSpec.NO_REQUIREMENTS; } @Override public void process(FetchSubPhase.HitContext hitContext) { if (hitContext.hit().getId().startsWith("boom")) { throw new RuntimeException("boom"); } } }); } } }
SubFetchPhasePlugin
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpPostDataTest.java
{ "start": 1346, "end": 2583 }
class ____ extends BaseNettyTest { @Test public void testPostWWWFormUrlencoded() throws Exception { String body = "x=1&y=2"; getMockEndpoint("mock:input").expectedBodiesReceived(body); DefaultExchange exchange = new DefaultExchange(context); exchange.getIn().setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_WWW_FORM_URLENCODED); exchange.getIn().setBody(body); Exchange result = template.send("netty-http:http://localhost:{{port}}/foo?reuseChannel=true", exchange); assertFalse(result.isFailed()); assertEquals("1", result.getIn().getHeader("x", String.class), "expect the x is 1"); assertEquals("2", result.getIn().getHeader("y", String.class), "expect the y is 2"); MockEndpoint.assertIsSatisfied(context); assertTrue(result.getProperty(NettyConstants.NETTY_CHANNEL, Channel.class).isActive()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("netty-http:http://0.0.0.0:{{port}}/foo") .to("mock:input"); } }; } }
NettyHttpPostDataTest
java
apache__camel
core/camel-util/src/main/java/org/apache/camel/util/PropertiesHelper.java
{ "start": 985, "end": 3489 }
class ____ { private PropertiesHelper() { } public static Map<String, Object> extractProperties(Map<String, Object> properties, String optionPrefix) { return extractProperties(properties, optionPrefix, true); } public static Map<String, Object> extractProperties(Map<String, Object> properties, String optionPrefix, boolean remove) { if (properties == null) { return new LinkedHashMap<>(0); } return doExtractProperties(properties, optionPrefix, remove); } static Map<String, Object> doExtractProperties(Map<String, Object> properties, String optionPrefix, boolean remove) { Map<String, Object> rc = new LinkedHashMap<>(properties.size()); for (Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = it.next(); String name = entry.getKey(); if (name.startsWith(optionPrefix)) { Object value = properties.get(name); name = name.substring(optionPrefix.length()); rc.put(name, value); if (remove) { it.remove(); } } } return rc; } public static boolean hasProperties(Map<String, Object> properties, String optionPrefix) { ObjectHelper.notNull(properties, "properties"); if (ObjectHelper.isNotEmpty(optionPrefix)) { for (Object o : properties.keySet()) { String name = (String) o; if (name.startsWith(optionPrefix)) { return true; } } // no parameters with this prefix return false; } else { return !properties.isEmpty(); } } public static Properties asProperties(String... properties) { if ((properties.length & 1) != 0) { throw new InternalError("length is odd"); } Properties answer = new Properties(); for (int i = 0; i < properties.length; i += 2) { answer.setProperty( Objects.requireNonNull(properties[i]), Objects.requireNonNull(properties[i + 1])); } return answer; } public static Properties asProperties(Map<String, Object> properties) { Properties answer = new Properties(); answer.putAll(properties); return answer; } }
PropertiesHelper
java
apache__camel
components/camel-test/camel-test-junit5/src/test/java/org/apache/camel/test/junit5/CamelTestSupportOneContextForAllTest.java
{ "start": 1433, "end": 2831 }
class ____ extends CamelTestSupport { private static final CamelContext CUSTOM_CONTEXT; static { CUSTOM_CONTEXT = new MockContext(); } @EndpointInject("mock:result") protected MockEndpoint resultEndpoint; @Produce("direct:start") protected ProducerTemplate template; @Override protected CamelContext createCamelContext() throws Exception { return CUSTOM_CONTEXT; } @Test @Order(1) void initContextTest() throws Exception { String expectedBody = "<matched/>"; resultEndpoint.expectedBodiesReceived(expectedBody); template.sendBodyAndHeader(expectedBody, "foo", "bar"); resultEndpoint.assertIsSatisfied(); resultEndpoint.reset(); } @Test @Order(2) void stopNotEnabledTest() throws Exception { String expectedBody = "<matched/>"; resultEndpoint.expectedBodiesReceived(expectedBody); template.sendBodyAndHeader(expectedBody, "foo", "bar"); resultEndpoint.assertIsSatisfied(); resultEndpoint.reset(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start").filter(header("foo").isEqualTo("bar")).to("mock:result"); } }; } private static
CamelTestSupportOneContextForAllTest
java
netty__netty
codec-base/src/main/java/io/netty/handler/codec/CodecException.java
{ "start": 736, "end": 1332 }
class ____ extends RuntimeException { private static final long serialVersionUID = -1464830400709348473L; /** * Creates a new instance. */ public CodecException() { } /** * Creates a new instance. */ public CodecException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public CodecException(String message) { super(message); } /** * Creates a new instance. */ public CodecException(Throwable cause) { super(cause); } }
CodecException
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/SingleDirectoryWriter.java
{ "start": 1275, "end": 3151 }
class ____<T> implements PartitionWriter<T> { private final Context<T> context; private final PartitionTempFileManager manager; private final PartitionComputer<T> computer; private final LinkedHashMap<String, String> staticPartitions; private final PartitionWriterListener writerListener; private OutputFormat<T> format; public SingleDirectoryWriter( Context<T> context, PartitionTempFileManager manager, PartitionComputer<T> computer, LinkedHashMap<String, String> staticPartitions) { this(context, manager, computer, staticPartitions, new DefaultPartitionWriterListener()); } public SingleDirectoryWriter( Context<T> context, PartitionTempFileManager manager, PartitionComputer<T> computer, LinkedHashMap<String, String> staticPartitions, PartitionWriterListener writerListener) { this.context = context; this.manager = manager; this.computer = computer; this.staticPartitions = staticPartitions; this.writerListener = writerListener; } @Override public void write(T in) throws Exception { if (format == null) { String partition = generatePartitionPath(staticPartitions); Path path = staticPartitions.isEmpty() ? manager.createPartitionDir() : manager.createPartitionDir(partition); format = context.createNewOutputFormat(path); writerListener.onFileOpened(partition, path); } format.writeRecord(computer.projectColumnsToWrite(in)); } @Override public void close() throws Exception { if (format != null) { format.close(); format = null; } } }
SingleDirectoryWriter
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/JSONTypeTest_orders_arrayMapping.java
{ "start": 257, "end": 1008 }
class ____ extends TestCase { public void test_1() throws Exception { Model vo = new Model(); vo.setId(1001); vo.setName("xx"); vo.setAge(33); String json = JSON.toJSONString(vo, SerializerFeature.BeanToArray); assertEquals("[1001,\"xx\",33]", json); JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); Model[] array = new Model[] {vo}; String json2 = JSON.toJSONString(array, SerializerFeature.BeanToArray); JSON.parseObject(json2, Model[].class, Feature.SupportArrayToBean); } public void test_2() throws Exception { String json = "[1001,\"xx\"]"; JSON.parseObject(json, Model.class, Feature.SupportArrayToBean); } @JSONType(orders = { "id", "name", "age" }) public static
JSONTypeTest_orders_arrayMapping
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchUpdateAndVersionTest.java
{ "start": 1659, "end": 5101 }
class ____ { @Test @JiraKey(value = "HHH-16394") public void testUpdate(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); scope.inTransaction( session -> { EntityA entityA1 = new EntityA( 1 ); EntityA entityA2 = new EntityA( 2 ); EntityA ownerA2 = new EntityA( 3 ); session.persist( ownerA2 ); session.persist( entityA1 ); session.persist( entityA2 ); session.flush(); entityA1.setPropertyA( 3 ); entityA2.addOwner( ownerA2 ); } ); scope.inTransaction( session -> { EntityA entityA1 = session.get( EntityA.class, 1 ); assertThat( entityA1.getVersion() ).isEqualTo( 1 ); assertThat( entityA1.getPropertyA() ).isEqualTo( 3 ); assertThat( entityA1.getOwners().size() ).isEqualTo( 0 ); EntityA entityA2 = session.get( EntityA.class, 2 ); assertThat( entityA2.getVersion() ).isEqualTo( 1 ); assertThat( entityA2.getPropertyA() ).isEqualTo( 0 ); List<EntityA> owners = entityA2.getOwners(); assertThat( owners.size() ).isEqualTo( 1 ); EntityA ownerA2 = owners.get( 0 ); assertThat( ownerA2.getId() ).isEqualTo( 3 ); assertThat( ownerA2.getPropertyA() ).isEqualTo( 0 ); assertThat( ownerA2.getOwners().size() ).isEqualTo( 0 ); } ); } @Test public void testFailedUpdate(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); scope.inTransaction( session -> { EntityA entityA1 = new EntityA( 1 ); EntityA entityA2 = new EntityA( 2 ); EntityA ownerA2 = new EntityA( 3 ); session.persist( ownerA2 ); session.persist( entityA1 ); session.persist( entityA2 ); } ); try { scope.inTransaction( session1 -> { EntityA entityA1_1 = session1.get( EntityA.class, 1 ); assertThat( entityA1_1.getVersion() ).isEqualTo( 0 ); assertThat( entityA1_1.getPropertyA() ).isEqualTo( 0 ); EntityA entityA2_1 = session1.get( EntityA.class, 2 ); assertThat( entityA2_1.getVersion() ).isEqualTo( 0 ); assertThat( entityA2_1.getPropertyA() ).isEqualTo( 0 ); scope.inTransaction( session2 -> { EntityA entityA1_2 = session2.get( EntityA.class, 1 ); assertThat( entityA1_2.getVersion() ).isEqualTo( 0 ); assertThat( entityA1_2.getPropertyA() ).isEqualTo( 0 ); EntityA entityA2_2 = session2.get( EntityA.class, 2 ); assertThat( entityA2_2.getVersion() ).isEqualTo( 0 ); assertThat( entityA2_2.getPropertyA() ).isEqualTo( 0 ); entityA1_2.setPropertyA( 5 ); entityA2_2.setPropertyA( 5 ); } ); entityA1_1.setPropertyA( 3 ); entityA2_1.setPropertyA( 3 ); } ); fail(); } catch (OptimisticLockException ole) { if (getDialect() instanceof MariaDBDialect && getDialect().getVersion().isAfter( 11, 6, 2 )) { // if @@innodb_snapshot_isolation is set, database throw an exception if record is not available anymore assertTrue( ole.getCause() instanceof SnapshotIsolationException ); } else { assertTrue( ole.getCause() instanceof StaleObjectStateException ); } } //CockroachDB errors with a Serialization Exception catch (RollbackException rbe) { assertTrue( rbe.getCause() instanceof TransactionSerializationException ); } } @Entity(name = "EntityA") @Table(name = "ENTITY_A") public static
BatchUpdateAndVersionTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/ResultSubpartitionStateHandle.java
{ "start": 1204, "end": 2210 }
class ____ extends AbstractChannelStateHandle<ResultSubpartitionInfo> implements OutputStateHandle { private static final long serialVersionUID = 1L; public ResultSubpartitionStateHandle( int subtaskIndex, ResultSubpartitionInfo info, StreamStateHandle delegate, StateContentMetaInfo contentMetaInfo) { this(subtaskIndex, info, delegate, contentMetaInfo.getOffsets(), contentMetaInfo.getSize()); } @VisibleForTesting public ResultSubpartitionStateHandle( ResultSubpartitionInfo info, StreamStateHandle delegate, List<Long> offset) { this(0, info, delegate, offset, delegate.getStateSize()); } public ResultSubpartitionStateHandle( int subtaskIndex, ResultSubpartitionInfo info, StreamStateHandle delegate, List<Long> offset, long size) { super(delegate, offset, subtaskIndex, info, size); } }
ResultSubpartitionStateHandle
java
apache__camel
components/camel-ironmq/src/generated/java/org/apache/camel/component/ironmq/IronMQEndpointConfigurer.java
{ "start": 733, "end": 12250 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { IronMQEndpoint target = (IronMQEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true; case "backoffidlethreshold": case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true; case "backoffmultiplier": case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true; case "batchdelete": case "batchDelete": target.getConfiguration().setBatchDelete(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "client": target.getConfiguration().setClient(property(camelContext, io.iron.ironmq.Client.class, value)); return true; case "concurrentconsumers": case "concurrentConsumers": target.getConfiguration().setConcurrentConsumers(property(camelContext, int.class, value)); return true; case "delay": target.setDelay(property(camelContext, long.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true; case "initialdelay": case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true; case "ironmqcloud": case "ironMQCloud": target.getConfiguration().setIronMQCloud(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxmessagesperpoll": case "maxMessagesPerPoll": target.getConfiguration().setMaxMessagesPerPoll(property(camelContext, int.class, value)); return true; case "pollstrategy": case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true; case "preserveheaders": case "preserveHeaders": target.getConfiguration().setPreserveHeaders(property(camelContext, boolean.class, value)); return true; case "projectid": case "projectId": target.getConfiguration().setProjectId(property(camelContext, java.lang.String.class, value)); return true; case "repeatcount": case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true; case "runlogginglevel": case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true; case "scheduledexecutorservice": case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true; case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true; case "schedulerproperties": case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true; case "startscheduler": case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true; case "timeunit": case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "timeout": target.getConfiguration().setTimeout(property(camelContext, int.class, value)); return true; case "token": target.getConfiguration().setToken(property(camelContext, java.lang.String.class, value)); return true; case "usefixeddelay": case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true; case "visibilitydelay": case "visibilityDelay": target.getConfiguration().setVisibilityDelay(property(camelContext, int.class, value)); return true; case "wait": target.getConfiguration().setWait(property(camelContext, int.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": return int.class; case "backoffidlethreshold": case "backoffIdleThreshold": return int.class; case "backoffmultiplier": case "backoffMultiplier": return int.class; case "batchdelete": case "batchDelete": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "client": return io.iron.ironmq.Client.class; case "concurrentconsumers": case "concurrentConsumers": return int.class; case "delay": return long.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "greedy": return boolean.class; case "initialdelay": case "initialDelay": return long.class; case "ironmqcloud": case "ironMQCloud": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxmessagesperpoll": case "maxMessagesPerPoll": return int.class; case "pollstrategy": case "pollStrategy": return org.apache.camel.spi.PollingConsumerPollStrategy.class; case "preserveheaders": case "preserveHeaders": return boolean.class; case "projectid": case "projectId": return java.lang.String.class; case "repeatcount": case "repeatCount": return long.class; case "runlogginglevel": case "runLoggingLevel": return org.apache.camel.LoggingLevel.class; case "scheduledexecutorservice": case "scheduledExecutorService": return java.util.concurrent.ScheduledExecutorService.class; case "scheduler": return java.lang.Object.class; case "schedulerproperties": case "schedulerProperties": return java.util.Map.class; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return boolean.class; case "startscheduler": case "startScheduler": return boolean.class; case "timeunit": case "timeUnit": return java.util.concurrent.TimeUnit.class; case "timeout": return int.class; case "token": return java.lang.String.class; case "usefixeddelay": case "useFixedDelay": return boolean.class; case "visibilitydelay": case "visibilityDelay": return int.class; case "wait": return int.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { IronMQEndpoint target = (IronMQEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": return target.getBackoffErrorThreshold(); case "backoffidlethreshold": case "backoffIdleThreshold": return target.getBackoffIdleThreshold(); case "backoffmultiplier": case "backoffMultiplier": return target.getBackoffMultiplier(); case "batchdelete": case "batchDelete": return target.getConfiguration().isBatchDelete(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "client": return target.getConfiguration().getClient(); case "concurrentconsumers": case "concurrentConsumers": return target.getConfiguration().getConcurrentConsumers(); case "delay": return target.getDelay(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "greedy": return target.isGreedy(); case "initialdelay": case "initialDelay": return target.getInitialDelay(); case "ironmqcloud": case "ironMQCloud": return target.getConfiguration().getIronMQCloud(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxmessagesperpoll": case "maxMessagesPerPoll": return target.getConfiguration().getMaxMessagesPerPoll(); case "pollstrategy": case "pollStrategy": return target.getPollStrategy(); case "preserveheaders": case "preserveHeaders": return target.getConfiguration().isPreserveHeaders(); case "projectid": case "projectId": return target.getConfiguration().getProjectId(); case "repeatcount": case "repeatCount": return target.getRepeatCount(); case "runlogginglevel": case "runLoggingLevel": return target.getRunLoggingLevel(); case "scheduledexecutorservice": case "scheduledExecutorService": return target.getScheduledExecutorService(); case "scheduler": return target.getScheduler(); case "schedulerproperties": case "schedulerProperties": return target.getSchedulerProperties(); case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle(); case "startscheduler": case "startScheduler": return target.isStartScheduler(); case "timeunit": case "timeUnit": return target.getTimeUnit(); case "timeout": return target.getConfiguration().getTimeout(); case "token": return target.getConfiguration().getToken(); case "usefixeddelay": case "useFixedDelay": return target.isUseFixedDelay(); case "visibilitydelay": case "visibilityDelay": return target.getConfiguration().getVisibilityDelay(); case "wait": return target.getConfiguration().getWait(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "schedulerproperties": case "schedulerProperties": return java.lang.Object.class; default: return null; } } }
IronMQEndpointConfigurer
java
quarkusio__quarkus
extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/ServiceBindingConfigSource.java
{ "start": 143, "end": 349 }
class ____ extends MapBackedConfigSource { public ServiceBindingConfigSource(String name, Map<String, String> propertyMap) { super(name, propertyMap, 270, false); } }
ServiceBindingConfigSource
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/helpers/AbstractLogger.java
{ "start": 1652, "end": 13622 }
class ____ implements Logger, Serializable { private static final long serialVersionUID = -2529255052481744503L; protected String name; public String getName() { return name; } /** * Replace this instance with a homonymous (same name) logger returned * by LoggerFactory. Note that this method is only called during * deserialization. * * <p> * This approach will work well if the desired ILoggerFactory is the one * referenced by {@link org.slf4j.LoggerFactory} However, if the user manages its logger hierarchy * through a different (non-static) mechanism, e.g. dependency injection, then * this approach would be mostly counterproductive. * * @return logger with same name as returned by LoggerFactory * @throws ObjectStreamException */ protected Object readResolve() throws ObjectStreamException { // using getName() instead of this.name works even for // NOPLogger return LoggerFactory.getLogger(getName()); } @Override public void trace(String msg) { if (isTraceEnabled()) { handle_0ArgsCall(Level.TRACE, null, msg, null); } } @Override public void trace(String format, Object arg) { if (isTraceEnabled()) { handle_1ArgsCall(Level.TRACE, null, format, arg); } } @Override public void trace(String format, Object arg1, Object arg2) { if (isTraceEnabled()) { handle2ArgsCall(Level.TRACE, null, format, arg1, arg2); } } @Override public void trace(String format, Object... arguments) { if (isTraceEnabled()) { handleArgArrayCall(Level.TRACE, null, format, arguments); } } @Override public void trace(String msg, Throwable t) { if (isTraceEnabled()) { handle_0ArgsCall(Level.TRACE, null, msg, t); } } @Override public void trace(Marker marker, String msg) { if (isTraceEnabled(marker)) { handle_0ArgsCall(Level.TRACE, marker, msg, null); } } @Override public void trace(Marker marker, String format, Object arg) { if (isTraceEnabled(marker)) { handle_1ArgsCall(Level.TRACE, marker, format, arg); } } @Override public void trace(Marker marker, String format, Object arg1, Object arg2) { if (isTraceEnabled(marker)) { handle2ArgsCall(Level.TRACE, marker, format, arg1, arg2); } } @Override public void trace(Marker marker, String format, Object... argArray) { if (isTraceEnabled(marker)) { handleArgArrayCall(Level.TRACE, marker, format, argArray); } } public void trace(Marker marker, String msg, Throwable t) { if (isTraceEnabled(marker)) { handle_0ArgsCall(Level.TRACE, marker, msg, t); } } public void debug(String msg) { if (isDebugEnabled()) { handle_0ArgsCall(Level.DEBUG, null, msg, null); } } public void debug(String format, Object arg) { if (isDebugEnabled()) { handle_1ArgsCall(Level.DEBUG, null, format, arg); } } public void debug(String format, Object arg1, Object arg2) { if (isDebugEnabled()) { handle2ArgsCall(Level.DEBUG, null, format, arg1, arg2); } } public void debug(String format, Object... arguments) { if (isDebugEnabled()) { handleArgArrayCall(Level.DEBUG, null, format, arguments); } } public void debug(String msg, Throwable t) { if (isDebugEnabled()) { handle_0ArgsCall(Level.DEBUG, null, msg, t); } } public void debug(Marker marker, String msg) { if (isDebugEnabled(marker)) { handle_0ArgsCall(Level.DEBUG, marker, msg, null); } } public void debug(Marker marker, String format, Object arg) { if (isDebugEnabled(marker)) { handle_1ArgsCall(Level.DEBUG, marker, format, arg); } } public void debug(Marker marker, String format, Object arg1, Object arg2) { if (isDebugEnabled(marker)) { handle2ArgsCall(Level.DEBUG, marker, format, arg1, arg2); } } public void debug(Marker marker, String format, Object... arguments) { if (isDebugEnabled(marker)) { handleArgArrayCall(Level.DEBUG, marker, format, arguments); } } public void debug(Marker marker, String msg, Throwable t) { if (isDebugEnabled(marker)) { handle_0ArgsCall(Level.DEBUG, marker, msg, t); } } public void info(String msg) { if (isInfoEnabled()) { handle_0ArgsCall(Level.INFO, null, msg, null); } } public void info(String format, Object arg) { if (isInfoEnabled()) { handle_1ArgsCall(Level.INFO, null, format, arg); } } public void info(String format, Object arg1, Object arg2) { if (isInfoEnabled()) { handle2ArgsCall(Level.INFO, null, format, arg1, arg2); } } public void info(String format, Object... arguments) { if (isInfoEnabled()) { handleArgArrayCall(Level.INFO, null, format, arguments); } } public void info(String msg, Throwable t) { if (isInfoEnabled()) { handle_0ArgsCall(Level.INFO, null, msg, t); } } public void info(Marker marker, String msg) { if (isInfoEnabled(marker)) { handle_0ArgsCall(Level.INFO, marker, msg, null); } } public void info(Marker marker, String format, Object arg) { if (isInfoEnabled(marker)) { handle_1ArgsCall(Level.INFO, marker, format, arg); } } public void info(Marker marker, String format, Object arg1, Object arg2) { if (isInfoEnabled(marker)) { handle2ArgsCall(Level.INFO, marker, format, arg1, arg2); } } public void info(Marker marker, String format, Object... arguments) { if (isInfoEnabled(marker)) { handleArgArrayCall(Level.INFO, marker, format, arguments); } } public void info(Marker marker, String msg, Throwable t) { if (isInfoEnabled(marker)) { handle_0ArgsCall(Level.INFO, marker, msg, t); } } public void warn(String msg) { if (isWarnEnabled()) { handle_0ArgsCall(Level.WARN, null, msg, null); } } public void warn(String format, Object arg) { if (isWarnEnabled()) { handle_1ArgsCall(Level.WARN, null, format, arg); } } public void warn(String format, Object arg1, Object arg2) { if (isWarnEnabled()) { handle2ArgsCall(Level.WARN, null, format, arg1, arg2); } } public void warn(String format, Object... arguments) { if (isWarnEnabled()) { handleArgArrayCall(Level.WARN, null, format, arguments); } } public void warn(String msg, Throwable t) { if (isWarnEnabled()) { handle_0ArgsCall(Level.WARN, null, msg, t); } } public void warn(Marker marker, String msg) { if (isWarnEnabled(marker)) { handle_0ArgsCall(Level.WARN, marker, msg, null); } } public void warn(Marker marker, String format, Object arg) { if (isWarnEnabled(marker)) { handle_1ArgsCall(Level.WARN, marker, format, arg); } } public void warn(Marker marker, String format, Object arg1, Object arg2) { if (isWarnEnabled(marker)) { handle2ArgsCall(Level.WARN, marker, format, arg1, arg2); } } public void warn(Marker marker, String format, Object... arguments) { if (isWarnEnabled(marker)) { handleArgArrayCall(Level.WARN, marker, format, arguments); } } public void warn(Marker marker, String msg, Throwable t) { if (isWarnEnabled(marker)) { handle_0ArgsCall(Level.WARN, marker, msg, t); } } public void error(String msg) { if (isErrorEnabled()) { handle_0ArgsCall(Level.ERROR, null, msg, null); } } public void error(String format, Object arg) { if (isErrorEnabled()) { handle_1ArgsCall(Level.ERROR, null, format, arg); } } public void error(String format, Object arg1, Object arg2) { if (isErrorEnabled()) { handle2ArgsCall(Level.ERROR, null, format, arg1, arg2); } } public void error(String format, Object... arguments) { if (isErrorEnabled()) { handleArgArrayCall(Level.ERROR, null, format, arguments); } } public void error(String msg, Throwable t) { if (isErrorEnabled()) { handle_0ArgsCall(Level.ERROR, null, msg, t); } } public void error(Marker marker, String msg) { if (isErrorEnabled(marker)) { handle_0ArgsCall(Level.ERROR, marker, msg, null); } } public void error(Marker marker, String format, Object arg) { if (isErrorEnabled(marker)) { handle_1ArgsCall(Level.ERROR, marker, format, arg); } } public void error(Marker marker, String format, Object arg1, Object arg2) { if (isErrorEnabled(marker)) { handle2ArgsCall(Level.ERROR, marker, format, arg1, arg2); } } public void error(Marker marker, String format, Object... arguments) { if (isErrorEnabled(marker)) { handleArgArrayCall(Level.ERROR, marker, format, arguments); } } public void error(Marker marker, String msg, Throwable t) { if (isErrorEnabled(marker)) { handle_0ArgsCall(Level.ERROR, marker, msg, t); } } private void handle_0ArgsCall(Level level, Marker marker, String msg, Throwable t) { handleNormalizedLoggingCall(level, marker, msg, null, t); } private void handle_1ArgsCall(Level level, Marker marker, String msg, Object arg1) { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1 }, null); } private void handle2ArgsCall(Level level, Marker marker, String msg, Object arg1, Object arg2) { if (arg2 instanceof Throwable) { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1 }, (Throwable) arg2); } else { handleNormalizedLoggingCall(level, marker, msg, new Object[] { arg1, arg2 }, null); } } private void handleArgArrayCall(Level level, Marker marker, String msg, Object[] args) { Throwable throwableCandidate = MessageFormatter.getThrowableCandidate(args); if (throwableCandidate != null) { Object[] trimmedCopy = MessageFormatter.trimmedCopy(args); handleNormalizedLoggingCall(level, marker, msg, trimmedCopy, throwableCandidate); } else { handleNormalizedLoggingCall(level, marker, msg, args, null); } } abstract protected String getFullyQualifiedCallerName(); /** * Given various arguments passed as parameters, perform actual logging. * * <p>This method assumes that the separation of the args array into actual * objects and a throwable has been already operated. * * @param level the SLF4J level for this event * @param marker The marker to be used for this event, may be null. * @param messagePattern The message pattern which will be parsed and formatted * @param arguments the array of arguments to be formatted, may be null * @param throwable The exception whose stack trace should be logged, may be null */ abstract protected void handleNormalizedLoggingCall(Level level, Marker marker, String messagePattern, Object[] arguments, Throwable throwable); }
AbstractLogger
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/nullable/User.java
{ "start": 192, "end": 888 }
class ____ { private Long id; private String name; private String org; private String password; private int intVal; User() {} public User(String name, String org, String password) { this.name = name; this.org = org; this.password = password; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrg() { return org; } public void setOrg(String org) { this.org = org; } public void setPassword(String password) { this.password = password; } public int getIntVal() { return intVal; } public void setIntVal(int intVal) { this.intVal = intVal; } }
User
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/ConstantArgumentCount.java
{ "start": 1116, "end": 1195 }
class ____ inclusive. All indices are 0-based. */ @PublicEvolving public final
are
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/health/metadata/HealthMetadata.java
{ "start": 17578, "end": 21472 }
class ____ { private RelativeByteSizeValue highWatermark; private ByteSizeValue highMaxHeadroom; private RelativeByteSizeValue floodStageWatermark; private ByteSizeValue floodStageMaxHeadroom; private RelativeByteSizeValue frozenFloodStageWatermark; private ByteSizeValue frozenFloodStageMaxHeadroom; private Builder(Disk disk) { this.highWatermark = disk.highWatermark; this.highMaxHeadroom = disk.highMaxHeadroom; this.floodStageWatermark = disk.floodStageWatermark; this.floodStageMaxHeadroom = disk.floodStageMaxHeadroom; this.frozenFloodStageWatermark = disk.frozenFloodStageWatermark; this.frozenFloodStageMaxHeadroom = disk.frozenFloodStageMaxHeadroom; } private Builder() {} public Disk.Builder highWatermark(RelativeByteSizeValue highWatermark) { this.highWatermark = highWatermark; return this; } public Disk.Builder highWatermark(String highWatermark, String setting) { return highWatermark(RelativeByteSizeValue.parseRelativeByteSizeValue(highWatermark, setting)); } public Disk.Builder highMaxHeadroom(ByteSizeValue highMaxHeadroom) { this.highMaxHeadroom = highMaxHeadroom; return this; } public Disk.Builder highMaxHeadroom(String highMaxHeadroom, String setting) { return highMaxHeadroom(ByteSizeValue.parseBytesSizeValue(highMaxHeadroom, setting)); } public Disk.Builder floodStageWatermark(RelativeByteSizeValue floodStageWatermark) { this.floodStageWatermark = floodStageWatermark; return this; } public Disk.Builder floodStageWatermark(String floodStageWatermark, String setting) { return floodStageWatermark(RelativeByteSizeValue.parseRelativeByteSizeValue(floodStageWatermark, setting)); } public Disk.Builder floodStageMaxHeadroom(ByteSizeValue floodStageMaxHeadroom) { this.floodStageMaxHeadroom = floodStageMaxHeadroom; return this; } public Disk.Builder floodStageMaxHeadroom(String floodStageMaxHeadroom, String setting) { return floodStageMaxHeadroom(ByteSizeValue.parseBytesSizeValue(floodStageMaxHeadroom, setting)); } public Disk.Builder frozenFloodStageWatermark(RelativeByteSizeValue frozenFloodStageWatermark) { this.frozenFloodStageWatermark = frozenFloodStageWatermark; return this; } public Disk.Builder frozenFloodStageWatermark(String frozenFloodStageWatermark, String setting) { return frozenFloodStageWatermark(RelativeByteSizeValue.parseRelativeByteSizeValue(frozenFloodStageWatermark, setting)); } public Disk.Builder frozenFloodStageMaxHeadroom(ByteSizeValue frozenFloodStageMaxHeadroom) { this.frozenFloodStageMaxHeadroom = frozenFloodStageMaxHeadroom; return this; } public Disk.Builder frozenFloodStageMaxHeadroom(String frozenFloodStageMaxHeadroom, String setting) { return frozenFloodStageMaxHeadroom(ByteSizeValue.parseBytesSizeValue(frozenFloodStageMaxHeadroom, setting)); } public Disk build() { return new Disk( highWatermark, highMaxHeadroom, floodStageWatermark, floodStageMaxHeadroom, frozenFloodStageWatermark, frozenFloodStageMaxHeadroom ); } } } }
Builder
java
apache__camel
components/camel-jdbc/src/test/java/org/apache/camel/component/jdbc/JdbcRouteTest.java
{ "start": 1188, "end": 1448 }
class ____ testing the jdbc component. * <p> * <b>Don't</b> add new test methods; it's likely to break the sub-classes. * <p> * Sub-classes should override {@link #testJdbcRoutes()} unless they create routes that are semantically equivalent to * what this
for
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassNewInstanceTest.java
{ "start": 4917, "end": 5266 }
class ____ { void f() { try { getClass().newInstance(); } catch (ReflectiveOperationException e) { e.printStackTrace(); } } } """) .addOutputLines( "out/Test.java", """
Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/ServiceSupportTest.java
{ "start": 1025, "end": 1092 }
class ____ extends TestSupport { private static
ServiceSupportTest
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/type/ImageConfig.java
{ "start": 3047, "end": 3689 }
class ____ { private final ObjectNode copy; private Update(ImageConfig source) { this.copy = (ObjectNode) source.getNode().deepCopy(); } private ImageConfig run(Consumer<Update> update) { update.accept(this); return new ImageConfig(this.copy); } /** * Update the image config with an additional label. * @param label the label name * @param value the label value */ public void withLabel(String label, String value) { JsonNode labels = this.copy.at("/Labels"); if (labels.isMissingNode()) { labels = this.copy.putObject("Labels"); } ((ObjectNode) labels).put(label, value); } } }
Update
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/scanning/ClassFilter.java
{ "start": 1945, "end": 2577 }
class ____"); } // Cannot use Preconditions due to package cycle @Contract("null, _ -> fail; !null, _ -> param1") private static <T> T checkNotNull(@Nullable T input, String title) { if (input == null) { throw new PreconditionViolationException(title + " must not be null"); } return input; } /** * Test the given name using the stored name predicate. * * @param name the name to test; never {@code null} * @return {@code true} if the input name matches the predicate, otherwise * {@code false} */ public boolean match(String name) { return namePredicate.test(name); } /** * Test the given
predicate
java
apache__kafka
server-common/src/main/java/org/apache/kafka/timeline/SnapshottableHashTable.java
{ "start": 4949, "end": 6621 }
class ____<T extends SnapshottableHashTable.ElementWithStartEpoch> implements Delta { private final int size; private BaseHashTable<T> deltaTable; HashTier(int size) { this.size = size; } @SuppressWarnings("unchecked") @Override public void mergeFrom(long epoch, Delta source) { HashTier<T> other = (HashTier<T>) source; // As an optimization, the deltaTable might not exist for a new key // as there is no previous value if (other.deltaTable != null) { List<T> list = new ArrayList<>(); Object[] otherElements = other.deltaTable.baseElements(); for (int slot = 0; slot < otherElements.length; slot++) { BaseHashTable.unpackSlot(list, otherElements, slot); for (T element : list) { // When merging in a later hash tier, we want to keep only the elements // that were present at our epoch. if (element.startEpoch() <= epoch) { if (deltaTable == null) { deltaTable = new BaseHashTable<>(1); } deltaTable.baseAddOrReplace(element); } } } } } } /** * Iterate over the values that currently exist in the hash table. * <p> * You can use this iterator even if you are making changes to the map. * The changes may or may not be visible while you are iterating. */
HashTier
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java
{ "start": 4355, "end": 5574 }
enum ____ { NOT_MUTED, MUTED, MUTED_AND_RESPONSE_PENDING, MUTED_AND_THROTTLED, MUTED_AND_THROTTLED_AND_RESPONSE_PENDING } /** Socket server events that will change the mute state: * <ul> * <li> REQUEST_RECEIVED: A request has been received from the client. </li> * <li> RESPONSE_SENT: A response has been sent out to the client (ack != 0) or SocketServer has heard back from * the API layer (acks = 0) </li> * <li> THROTTLE_STARTED: Throttling started due to quota violation. </li> * <li> THROTTLE_ENDED: Throttling ended. </li> * </ul> * * Valid transitions on each event are: * <ul> * <li> REQUEST_RECEIVED: MUTED => MUTED_AND_RESPONSE_PENDING </li> * <li> RESPONSE_SENT: MUTED_AND_RESPONSE_PENDING => MUTED, MUTED_AND_THROTTLED_AND_RESPONSE_PENDING => MUTED_AND_THROTTLED </li> * <li> THROTTLE_STARTED: MUTED_AND_RESPONSE_PENDING => MUTED_AND_THROTTLED_AND_RESPONSE_PENDING </li> * <li> THROTTLE_ENDED: MUTED_AND_THROTTLED => MUTED, MUTED_AND_THROTTLED_AND_RESPONSE_PENDING => MUTED_AND_RESPONSE_PENDING </li> * </ul> */ public
ChannelMuteState
java
apache__camel
components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcProducer.java
{ "start": 1167, "end": 5285 }
class ____ extends DefaultProducer { public static final String[] COMMANDS = new String[] { "AWAY", "INVITE", "ISON", "JOIN", "KICK", "LIST", "NAMES", "PRIVMSG", "MODE", "NICK", "NOTICE", "PART", "PONG", "QUIT", "TOPIC", "WHO", "WHOIS", "WHOWAS", "USERHOST" }; private static final Logger LOG = LoggerFactory.getLogger(IrcProducer.class); private transient IRCConnection connection; private IRCEventAdapter listener = new FilteredIRCEventAdapter(); public IrcProducer(IrcEndpoint endpoint) { super(endpoint); } @Override public IrcEndpoint getEndpoint() { return (IrcEndpoint) super.getEndpoint(); } @Override public void process(Exchange exchange) throws Exception { final String msg = exchange.getIn().getBody(String.class); final String sendTo = exchange.getIn().getHeader(IrcConstants.IRC_SEND_TO, String.class); if (connection == null || !connection.isConnected()) { reconnect(); } if (connection == null || !connection.isConnected()) { throw new RuntimeCamelException("Lost connection" + (connection == null ? "" : " to " + connection.getHost())); } if (msg != null) { if (isMessageACommand(msg)) { LOG.debug("Sending command: {}", msg); connection.send(msg); } else if (sendTo != null) { LOG.debug("Sending to: {} message: {}", sendTo, msg); connection.doPrivmsg(sendTo, msg); } else { for (IrcChannel channel : getEndpoint().getConfiguration().getChannelList()) { LOG.debug("Sending to: {} message: {}", channel, msg); connection.doPrivmsg(channel.getName(), msg); } } } } @Override protected void doStart() throws Exception { super.doStart(); reconnect(); } protected void reconnect() { // create new connection if (connection == null || connection.isConnected()) { connection = getEndpoint().getComponent().getIRCConnection(getEndpoint().getConfiguration()); } else { // reconnecting if (LOG.isDebugEnabled()) { LOG.debug("Reconnecting to {}:{}", getEndpoint().getConfiguration().getHostname(), getEndpoint().getConfiguration().getNickname()); } getEndpoint().getComponent().closeConnection(connection); connection = getEndpoint().getComponent().getIRCConnection(getEndpoint().getConfiguration()); } connection.addIRCEventListener(listener); LOG.debug("Sleeping for {} seconds before sending commands.", getEndpoint().getConfiguration().getCommandTimeout() / 1000); // sleep for a few seconds as the server sometimes takes a moment to fully connect, print banners, etc after connection established try { Thread.sleep(getEndpoint().getConfiguration().getCommandTimeout()); } catch (InterruptedException ex) { LOG.info("Interrupted while sleeping before sending commands"); Thread.currentThread().interrupt(); } getEndpoint().joinChannels(); } @Override protected void doStop() throws Exception { if (connection != null) { for (IrcChannel channel : getEndpoint().getConfiguration().getChannelList()) { LOG.debug("Parting: {}", channel); connection.doPart(channel.getName()); } connection.removeIRCEventListener(listener); } super.doStop(); } protected boolean isMessageACommand(String msg) { for (String command : COMMANDS) { if (msg.startsWith(command)) { return true; } } return false; } public IRCEventAdapter getListener() { return listener; } public void setListener(IRCEventAdapter listener) { this.listener = listener; }
IrcProducer
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/a/CompilerTest.java
{ "start": 173, "end": 1370 }
class ____ extends TestCase { public void test_for_compiler() throws Exception { byte[] bytes; { Model model = new Model(); model.id = 123; bytes = toBytes(model); } perf(bytes); for (int i = 0; i < 10; ++i) { long start = System.currentTimeMillis(); perf(bytes); long millis = System.currentTimeMillis() - start; System.out.println("millis : " + millis); } } private void perf(byte[] bytes) throws IOException, ClassNotFoundException { for (int i = 0; i < 1000; ++i) { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); Model model = (Model) in.readObject(); assertEquals(123, model.id); } } private byte[] toBytes(Model model) throws IOException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(model); out.flush(); byte[] bytes = byteOut.toByteArray(); out.close(); return bytes; } public static
CompilerTest
java
quarkusio__quarkus
test-framework/kubernetes-client/src/main/java/io/quarkus/test/kubernetes/client/AbstractKubernetesTestResource.java
{ "start": 315, "end": 2335 }
class ____<T, C extends KubernetesClient> implements QuarkusTestResourceLifecycleManager { protected T server; @Override public Map<String, String> start() { final Map<String, String> systemProps = new HashMap<>(); systemProps.put(Config.KUBERNETES_TRUST_CERT_SYSTEM_PROPERTY, "true"); systemProps.put("quarkus.tls.trust-all", "true"); systemProps.put(Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false"); systemProps.put(Config.KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY, "false"); systemProps.put(Config.KUBERNETES_NAMESPACE_SYSTEM_PROPERTY, "test"); systemProps.put(Config.KUBERNETES_HTTP2_DISABLE, "true"); server = createServer(); initServer(); systemProps.put(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, getClient().getConfiguration().getMasterUrl()); configureServer(); //these actually need to be system properties //as they are read directly as system props, and not from Quarkus config for (Map.Entry<String, String> entry : systemProps.entrySet()) { System.setProperty(entry.getKey(), entry.getValue()); } return systemProps; } protected abstract C getClient(); /** * Can be used by subclasses in order to * setup the mock server before the Quarkus application starts */ protected void configureServer() { } protected void initServer() { } protected abstract T createServer(); protected boolean useHttps() { return Boolean.getBoolean("quarkus.kubernetes-client.test.https"); } @Override public void inject(TestInjector testInjector) { testInjector.injectIntoFields(server, new TestInjector.AnnotatedAndMatchesType(getInjectionAnnotation(), getInjectedClass())); } protected abstract Class<?> getInjectedClass(); protected abstract Class<? extends Annotation> getInjectionAnnotation(); }
AbstractKubernetesTestResource
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CaffeineLoadCacheEndpointBuilderFactory.java
{ "start": 19668, "end": 21960 }
interface ____ { /** * Caffeine LoadCache (camel-caffeine) * Perform caching operations using Caffeine Cache with an attached * CacheLoader. * * Category: cache,clustering * Since: 2.20 * Maven coordinates: org.apache.camel:camel-caffeine * * @return the dsl builder for the headers' name. */ default CaffeineLoadCacheHeaderNameBuilder caffeineLoadcache() { return CaffeineLoadCacheHeaderNameBuilder.INSTANCE; } /** * Caffeine LoadCache (camel-caffeine) * Perform caching operations using Caffeine Cache with an attached * CacheLoader. * * Category: cache,clustering * Since: 2.20 * Maven coordinates: org.apache.camel:camel-caffeine * * Syntax: <code>caffeine-loadcache:cacheName</code> * * Path parameter: cacheName (required) * the cache name * * @param path cacheName * @return the dsl builder */ default CaffeineLoadCacheEndpointBuilder caffeineLoadcache(String path) { return CaffeineLoadCacheEndpointBuilderFactory.endpointBuilder("caffeine-loadcache", path); } /** * Caffeine LoadCache (camel-caffeine) * Perform caching operations using Caffeine Cache with an attached * CacheLoader. * * Category: cache,clustering * Since: 2.20 * Maven coordinates: org.apache.camel:camel-caffeine * * Syntax: <code>caffeine-loadcache:cacheName</code> * * Path parameter: cacheName (required) * the cache name * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path cacheName * @return the dsl builder */ default CaffeineLoadCacheEndpointBuilder caffeineLoadcache(String componentName, String path) { return CaffeineLoadCacheEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Caffeine LoadCache component. */ public static
CaffeineLoadCacheBuilders
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/ansi/AnsiOutputEnabledValue.java
{ "start": 848, "end": 991 }
class ____ { private AnsiOutputEnabledValue() { } public static Enabled get() { return AnsiOutput.getEnabled(); } }
AnsiOutputEnabledValue
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TrafficController.java
{ "start": 4397, "end": 7975 }
class ____ dev %s"; /** Delete a qdisc and all its children - classes/filters etc */ private static final String FORMAT_WIPE_STATE = "qdisc del dev %s parent root"; private final Configuration conf; //Used to store the set of classids in use for container classes private final BitSet classIdSet; private final PrivilegedOperationExecutor privilegedOperationExecutor; private String tmpDirPath; private String device; private int rootBandwidthMbit; private int yarnBandwidthMbit; private int defaultClassBandwidthMbit; TrafficController(Configuration conf, PrivilegedOperationExecutor exec) { this.conf = conf; this.classIdSet = new BitSet(MAX_CONTAINER_CLASSES); this.privilegedOperationExecutor = exec; } /** * Bootstrap tc configuration */ public void bootstrap(String device, int rootBandwidthMbit, int yarnBandwidthMbit) throws ResourceHandlerException { if (device == null) { throw new ResourceHandlerException("device cannot be null!"); } String tmpDirBase = conf.get("hadoop.tmp.dir"); if (tmpDirBase == null) { throw new ResourceHandlerException("hadoop.tmp.dir not set!"); } tmpDirPath = tmpDirBase + "/nm-tc-rules"; File tmpDir = new File(tmpDirPath); if (!(tmpDir.exists() || tmpDir.mkdirs())) { LOG.warn("Unable to create directory: " + tmpDirPath); throw new ResourceHandlerException("Unable to create directory: " + tmpDirPath); } this.device = device; this.rootBandwidthMbit = rootBandwidthMbit; this.yarnBandwidthMbit = yarnBandwidthMbit; defaultClassBandwidthMbit = (rootBandwidthMbit - yarnBandwidthMbit) <= 0 ? rootBandwidthMbit : (rootBandwidthMbit - yarnBandwidthMbit); boolean recoveryEnabled = conf.getBoolean(YarnConfiguration .NM_RECOVERY_ENABLED, YarnConfiguration.DEFAULT_NM_RECOVERY_ENABLED); String state = null; if (!recoveryEnabled) { LOG.info("NM recovery is not enabled. We'll wipe tc state before proceeding."); } else { //NM recovery enabled - run a state check state = readState(); if (checkIfAlreadyBootstrapped(state)) { LOG.info("TC configuration is already in place. Not wiping state."); //We already have the list of existing container classes, if any //that were created after bootstrapping reacquireContainerClasses(state); return; } else { LOG.info("TC configuration is incomplete. Wiping tc state before proceeding"); } } wipeState(); //start over in case preview bootstrap was incomplete initializeState(); } private void initializeState() throws ResourceHandlerException { LOG.info("Initializing tc state."); BatchBuilder builder = new BatchBuilder(PrivilegedOperation. OperationType.TC_MODIFY_STATE) .addRootQDisc() .addCGroupFilter() .addClassToRootQDisc(rootBandwidthMbit) .addDefaultClass(defaultClassBandwidthMbit, rootBandwidthMbit) //yarn bandwidth is capped with rate = ceil .addYARNRootClass(yarnBandwidthMbit, yarnBandwidthMbit); PrivilegedOperation op = builder.commitBatchToTempFile(); try { privilegedOperationExecutor.executePrivilegedOperation(op, false); } catch (PrivilegedOperationException e) { LOG.warn("Failed to bootstrap outbound bandwidth configuration"); throw new ResourceHandlerException( "Failed to bootstrap outbound bandwidth configuration", e); } } /** * Function to check if the
show
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java
{ "start": 17383, "end": 17757 }
class ____ { @Test void types() { Class<?> dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class); assertThat(dateClass).isEqualTo(Date.class); boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class); assertThat(trueValue).isTrue(); } } @Nested
Types
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CaseStatementDiscriminatorMappingImpl.java
{ "start": 7605, "end": 10023 }
class ____ implements SelfRenderingExpression { private final TableGroup entityTableGroup; CaseSearchedExpression caseSearchedExpression; public CaseStatementDiscriminatorExpression(TableGroup entityTableGroup) { this.entityTableGroup = entityTableGroup; } public List<TableReference> getUsedTableReferences() { final ArrayList<TableReference> usedTableReferences = new ArrayList<>( tableDiscriminatorDetailsMap.size() ); tableDiscriminatorDetailsMap.forEach( (tableName, tableDiscriminatorDetails) -> { final var tableReference = entityTableGroup.getTableReference( entityTableGroup.getNavigablePath(), tableName, false ); if ( tableReference != null ) { usedTableReferences.add( tableReference ); } } ); return usedTableReferences; } @Override public void renderToSql( SqlAppender sqlAppender, SqlAstTranslator<?> walker, SessionFactoryImplementor sessionFactory) { if ( caseSearchedExpression == null ) { // todo (6.0): possible optimization is to omit cases for table reference joins, that touch a super class, where a subclass is inner joined due to pruning caseSearchedExpression = new CaseSearchedExpression( CaseStatementDiscriminatorMappingImpl.this ); tableDiscriminatorDetailsMap.forEach( (tableName, tableDiscriminatorDetails) -> { final var tableReference = entityTableGroup.getTableReference( entityTableGroup.getNavigablePath(), tableName, false ); if ( tableReference == null ) { // assume this is because it is a table that is not part of the processing entity's sub-hierarchy return; } final Predicate predicate = new NullnessPredicate( new ColumnReference( tableReference, tableDiscriminatorDetails.getCheckColumnName(), false, null, getJdbcMapping() ), true ); caseSearchedExpression.when( predicate, new QueryLiteral<>( tableDiscriminatorDetails.getDiscriminatorValue(), getUnderlyingJdbcMapping() ) ); } ); } caseSearchedExpression.accept( walker ); } @Override public JdbcMappingContainer getExpressionType() { return CaseStatementDiscriminatorMappingImpl.this; } } }
CaseStatementDiscriminatorExpression
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingPhysicalSlotRequestBulkChecker.java
{ "start": 1209, "end": 1784 }
class ____ implements PhysicalSlotRequestBulkChecker { private PhysicalSlotRequestBulk bulk; private Duration timeout; @Override public void start(ComponentMainThreadExecutor mainThreadExecutor) {} @Override public void schedulePendingRequestBulkTimeoutCheck( PhysicalSlotRequestBulk bulk, Duration timeout) { this.bulk = bulk; this.timeout = timeout; } PhysicalSlotRequestBulk getBulk() { return bulk; } Duration getTimeout() { return timeout; } }
TestingPhysicalSlotRequestBulkChecker
java
apache__camel
components/camel-opentelemetry/src/test/java/org/apache/camel/opentelemetry/TwoServiceTest.java
{ "start": 1009, "end": 2509 }
class ____ extends CamelOpenTelemetryTestSupport { private static SpanTestData[] testdata = { new SpanTestData().setLabel("ServiceB server").setUri("direct://ServiceB").setOperation("ServiceB") .setParentId(1), new SpanTestData().setLabel("ServiceB server").setUri("direct://ServiceB").setOperation("ServiceB") .setParentId(2) .setKind(SpanKind.CLIENT), new SpanTestData().setLabel("ServiceA server").setUri("direct://ServiceA").setOperation("ServiceA") .setParentId(3), new SpanTestData().setLabel("ServiceA server").setUri("direct://ServiceA").setOperation("ServiceA") .setKind(SpanKind.CLIENT) }; TwoServiceTest() { super(testdata); } @Test void testRoute() { template.requestBody("direct:ServiceA", "Hello"); verify(); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:ServiceA") .log("ServiceA has been called") .delay(simple("${random(1000,2000)}")) .to("direct:ServiceB"); from("direct:ServiceB") .log("ServiceB has been called") .delay(simple("${random(0,500)}")); } }; } }
TwoServiceTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java
{ "start": 19733, "end": 19966 }
class ____ { } @Configuration @ComponentScan(basePackages = "example.scannable_scoped", scopeResolver = MyScopeMetadataResolver.class) @ComponentScan(basePackages = "example.scannable_implicitbasepackage")
ComponentScanWithScopeResolver
java
spring-projects__spring-boot
module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveHealthEndpointWebExtension.java
{ "start": 1853, "end": 2552 }
class ____ { private final ReactiveHealthEndpointWebExtension delegate; public CloudFoundryReactiveHealthEndpointWebExtension(ReactiveHealthEndpointWebExtension delegate) { this.delegate = delegate; } @ReadOperation public Mono<WebEndpointResponse<? extends HealthDescriptor>> health(ApiVersion apiVersion) { return this.delegate.health(apiVersion, null, SecurityContext.NONE, true); } @ReadOperation public Mono<WebEndpointResponse<? extends HealthDescriptor>> health(ApiVersion apiVersion, @Selector(match = Match.ALL_REMAINING) String... path) { return this.delegate.health(apiVersion, null, SecurityContext.NONE, true, path); } }
CloudFoundryReactiveHealthEndpointWebExtension
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/test/java/org/apache/flink/testutils/junit/RetryOnExceptionExtensionTest.java
{ "start": 6148, "end": 6452 }
class ____ extends Throwable {} static Stream<Throwable> retryTestProvider() { return Stream.of( new RetryTestError(), new RetryTestException(), new RetryTestRuntimeException(), new RetryTestThrowable()); } }
RetryTestThrowable
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/StateStore.java
{ "start": 2535, "end": 3145 }
interface ____ { /** * The name of this store. * @return the storage name */ String name(); /** * Initializes this state store. * <p> * The implementation of this function must register the root store in the stateStoreContext via the * {@link StateStoreContext#register(StateStore, StateRestoreCallback, CommitCallback)} function, where the * first {@link StateStore} parameter should always be the passed-in {@code root} object, and * the second parameter should be an object of user's implementation * of the {@link StateRestoreCallback}
StateStore
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/project-with-extension/library/src/main/java/org/acme/LibraryBean.java
{ "start": 99, "end": 286 }
class ____ { private final CommonTransitiveBean bean; public LibraryBean(CommonTransitiveBean bean) { this.bean = java.util.Objects.requireNonNull(bean); } }
LibraryBean
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/aot/hint/PrePostAuthorizeHintsRegistrarTests.java
{ "start": 8670, "end": 8734 }
class ____ { boolean bar() { return true; } } static
Foo
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/annotation-processor-multi-module/application/src/test/java/org/acme/quarkus/sample/HelloResourceTest.java
{ "start": 237, "end": 468 }
class ____ { @Test public void testHelloEndpoint() { given() .when().get("/hello") .then() .statusCode(200) .body(containsString("seatNumber")); } }
HelloResourceTest
java
apache__flink
flink-state-backends/flink-statebackend-changelog/src/test/java/org/apache/flink/state/changelog/KvStateChangeLoggerImplTest.java
{ "start": 1451, "end": 3203 }
class ____ extends StateChangeLoggerTestBase<String> { @Override protected StateChangeLogger<String, String> getLogger( TestingStateChangelogWriter writer, InternalKeyContextImpl<String> keyContext) { StringSerializer keySerializer = new StringSerializer(); StringSerializer nsSerializer = new StringSerializer(); StringSerializer valueSerializer = new StringSerializer(); RegisteredKeyValueStateBackendMetaInfo<String, String> metaInfo = new RegisteredKeyValueStateBackendMetaInfo<>( VALUE, "test", nsSerializer, valueSerializer); return new KvStateChangeLoggerImpl<>( keySerializer, nsSerializer, valueSerializer, keyContext, writer, metaInfo, StateTtlConfig.DISABLED, "default", Short.MIN_VALUE); } @Override protected String getNamespace(String element) { return element; } @Override protected Optional<Tuple2<Integer, StateChangeOperation>> log( StateChangeOperation op, String element, StateChangeLogger<String, String> logger, InternalKeyContextImpl<String> keyContext) throws IOException { if (op == MERGE_NS) { keyContext.setCurrentKey(element); ((KvStateChangeLogger<String, String>) logger) .namespacesMerged(element, Collections.emptyList()); return Optional.of(Tuple2.of(keyContext.getCurrentKeyGroupIndex(), op)); } else { return super.log(op, element, logger, keyContext); } } }
KvStateChangeLoggerImplTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/Lookup.java
{ "start": 1520, "end": 6107 }
class ____ extends UnaryPlan implements SurrogateLogicalPlan, TelemetryAware, SortAgnostic { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(LogicalPlan.class, "Lookup", Lookup::new); private final Expression tableName; /** * References to the input fields to match against the {@link #localRelation}. */ private final List<Attribute> matchFields; // initialized during the analysis phase for output and validation // afterward, it is converted into a Join (BinaryPlan) hence why here it is not a child private final LocalRelation localRelation; private List<Attribute> lazyOutput; public Lookup( Source source, LogicalPlan child, Expression tableName, List<Attribute> matchFields, @Nullable LocalRelation localRelation ) { super(source, child); this.tableName = tableName; this.matchFields = matchFields; this.localRelation = localRelation; } public Lookup(StreamInput in) throws IOException { super(Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(LogicalPlan.class)); this.tableName = in.readNamedWriteable(Expression.class); this.matchFields = in.readNamedWriteableCollectionAsList(Attribute.class); this.localRelation = in.readBoolean() ? new LocalRelation(in) : null; } @Override public void writeTo(StreamOutput out) throws IOException { source().writeTo(out); out.writeNamedWriteable(child()); out.writeNamedWriteable(tableName); out.writeNamedWriteableCollection(matchFields); if (localRelation == null) { out.writeBoolean(false); } else { out.writeBoolean(true); localRelation.writeTo(out); } } @Override public String getWriteableName() { return ENTRY.name; } public Expression tableName() { return tableName; } public List<Attribute> matchFields() { return matchFields; } public LocalRelation localRelation() { return localRelation; } @Override public LogicalPlan surrogate() { // left join between the main relation and the local, lookup relation return new Join(source(), child(), localRelation, joinConfig()); } public JoinConfig joinConfig() { List<Attribute> leftFields = new ArrayList<>(matchFields.size()); List<Attribute> rightFields = new ArrayList<>(matchFields.size()); List<Attribute> rhsOutput = Join.makeReference(localRelation.output()); for (Attribute lhs : matchFields) { for (Attribute rhs : rhsOutput) { if (lhs.name().equals(rhs.name())) { leftFields.add(lhs); rightFields.add(rhs); break; } } } return new JoinConfig(JoinTypes.LEFT, leftFields, rightFields, null); } @Override public boolean expressionsResolved() { return tableName.resolved() && Resolvables.resolved(matchFields) && localRelation != null; } @Override public UnaryPlan replaceChild(LogicalPlan newChild) { return new Lookup(source(), newChild, tableName, matchFields, localRelation); } @Override protected NodeInfo<? extends LogicalPlan> info() { return NodeInfo.create(this, Lookup::new, child(), tableName, matchFields, localRelation); } @Override public List<Attribute> output() { if (lazyOutput == null) { if (localRelation == null) { throw new IllegalStateException("Cannot determine output of LOOKUP with unresolved table"); } lazyOutput = Expressions.asAttributes(Join.computeOutputExpressions(child().output(), localRelation.output(), joinConfig())); } return lazyOutput; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (super.equals(o) == false) { return false; } Lookup lookup = (Lookup) o; return Objects.equals(tableName, lookup.tableName) && Objects.equals(matchFields, lookup.matchFields) && Objects.equals(localRelation, lookup.localRelation); } @Override public int hashCode() { return Objects.hash(super.hashCode(), tableName, matchFields, localRelation); } }
Lookup
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECBlockGroup.java
{ "start": 1028, "end": 2057 }
class ____ { private ECBlock[] dataBlocks; private ECBlock[] parityBlocks; /** * A constructor specifying data blocks and parity blocks. * @param dataBlocks data blocks in the group * @param parityBlocks parity blocks in the group */ public ECBlockGroup(ECBlock[] dataBlocks, ECBlock[] parityBlocks) { this.dataBlocks = dataBlocks; this.parityBlocks = parityBlocks; } /** * Get data blocks * @return data blocks */ public ECBlock[] getDataBlocks() { return dataBlocks; } /** * Get parity blocks * @return parity blocks */ public ECBlock[] getParityBlocks() { return parityBlocks; } /** * Get erased blocks count * @return erased count of blocks */ public int getErasedCount() { int erasedCount = 0; for (ECBlock dataBlock : dataBlocks) { if (dataBlock.isErased()) erasedCount++; } for (ECBlock parityBlock : parityBlocks) { if (parityBlock.isErased()) erasedCount++; } return erasedCount; } }
ECBlockGroup
java
apache__camel
components/camel-http-base/src/main/java/org/apache/camel/http/base/cookie/BaseCookieHandler.java
{ "start": 1174, "end": 1929 }
class ____ implements CookieHandler { @Override public void storeCookies(Exchange exchange, URI uri, Map<String, List<String>> headerMap) throws IOException { getCookieManager(exchange).put(uri, headerMap); } @Override public Map<String, List<String>> loadCookies(Exchange exchange, URI uri) throws IOException { // the map is not used, so we do not need to fetch the headers from the // exchange return getCookieManager(exchange).get(uri, Collections.emptyMap()); } @Override public CookieStore getCookieStore(Exchange exchange) { return getCookieManager(exchange).getCookieStore(); } protected abstract CookieManager getCookieManager(Exchange exchange); }
BaseCookieHandler
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/AsyncTests.java
{ "start": 4218, "end": 6417 }
class ____ { @GetMapping(params = "callable") Callable<Person> getCallable() { return () -> new Person("Joe"); } @GetMapping(params = "streaming") StreamingResponseBody getStreaming() { return os -> os.write("name=Joe".getBytes(StandardCharsets.UTF_8)); } @GetMapping(params = "streamingSlow") StreamingResponseBody getStreamingSlow() { return os -> { os.write("name=Joe".getBytes()); try { Thread.sleep(200); os.write("&someBoolean=true".getBytes(StandardCharsets.UTF_8)); } catch (InterruptedException e) { /* no-op */ } }; } @GetMapping(params = "streamingJson") ResponseEntity<StreamingResponseBody> getStreamingJson() { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON) .body(os -> os.write("{\"name\":\"Joe\",\"someDouble\":0.5}".getBytes(StandardCharsets.UTF_8))); } @GetMapping(params = "deferredResult") DeferredResult<Person> getDeferredResult() { DeferredResult<Person> result = new DeferredResult<>(); delay(100, () -> result.setResult(new Person("Joe"))); return result; } @GetMapping(params = "deferredResultWithImmediateValue") DeferredResult<Person> getDeferredResultWithImmediateValue() { DeferredResult<Person> result = new DeferredResult<>(); result.setResult(new Person("Joe")); return result; } @GetMapping(params = "deferredResultWithDelayedError") DeferredResult<Person> getDeferredResultWithDelayedError() { DeferredResult<Person> result = new DeferredResult<>(); delay(100, () -> result.setErrorResult(new RuntimeException("Delayed Error"))); return result; } @GetMapping(params = "completableFutureWithImmediateValue") CompletableFuture<Person> getCompletableFutureWithImmediateValue() { CompletableFuture<Person> future = new CompletableFuture<>(); future.complete(new Person("Joe")); return future; } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) String errorHandler(Exception ex) { return ex.getMessage(); } private void delay(long millis, Runnable task) { Mono.delay(Duration.ofMillis(millis)).doOnTerminate(task).subscribe(); } } }
AsyncController
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/testdata/input/AsVarargsTemplateExample.java
{ "start": 806, "end": 1163 }
class ____ { public void example() { System.out.println( Stream.of(IntStream.of(1), IntStream.of(2)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum()); // unchanged, it's not using the varargs overload System.out.println( Stream.of(IntStream.of(1)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum()); } }
AsVarargsTemplateExample
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/ast/HqlEntityGraphTest.java
{ "start": 3783, "end": 18315 }
class ____ implements SessionFactoryScopeAware { private SessionFactoryScope scope; @Override public void injectSessionFactoryScope(SessionFactoryScope scope) { this.scope = scope; } @ParameterizedTest @EnumSource( GraphSemantic.class ) void testBasicSemantics(GraphSemantic graphSemantic) { scope.inTransaction( session -> { final RootGraphImplementor<Cat> eg = session.createEntityGraph( Cat.class ); final SelectStatement sqlAst = buildSqlSelectAst( Cat.class, "select c from Cat c", eg, graphSemantic, session ); // Check the from-clause assertEmptyJoinedGroup( sqlAst ); // Check the domain-result graph assertDomainResult(sqlAst, Cat.class, fetch -> { if (graphSemantic == GraphSemantic.LOAD) { assertThat(fetch, instanceOf(BiDirectionalFetch.class)); } else { assertThat(fetch, instanceOf(EntityFetch.class)); final EntityFetch entityFetch = (EntityFetch) fetch; assertThat(entityFetch.getFetchedMapping().getFetchableName(), is("owner")); assertThat(entityFetch.getReferencedModePart().getJavaType().getJavaTypeClass(), assignableTo(Person.class)); assertThat(entityFetch, instanceOf(EntityDelayedFetchImpl.class)); } } ); } ); } @ParameterizedTest @EnumSource( GraphSemantic.class ) void testSemanticsWithSubgraph(GraphSemantic graphSemantic) { scope.inTransaction( session -> { final RootGraphImplementor<Cat> eg = session.createEntityGraph( Cat.class ); eg.addSubgraph( "owner", Person.class ); final SelectStatement sqlAst = buildSqlSelectAst( Cat.class, "select c from Cat as c", eg, graphSemantic, session ); // Check the from-clause assertEntityValuedJoinedGroup( sqlAst, "owner", Person.class, this::assertPersonHomeAddressJoinedGroup ); // Check the domain-result graph assertDomainResult( sqlAst, Cat.class, fetch -> { assertThat( fetch, instanceOf( EntityFetch.class ) ); final EntityFetch entityFetch = (EntityFetch) fetch; assertThat( entityFetch.getFetchedMapping().getFetchableName(), is( "owner" ) ); assertThat( entityFetch.getReferencedModePart().getJavaType().getJavaTypeClass(), assignableTo( Person.class ) ); if ( graphSemantic == GraphSemantic.LOAD ) { assertThat( entityFetch, instanceOf( EntityFetchJoinedImpl.class ) ); final EntityResult entityResult = ( (EntityFetchJoinedImpl) entityFetch ).getEntityResult(); final Map<String, Class<? extends Fetch>> fetchClassByAttributeName = entityResult.getFetches().stream().collect( Collectors.toMap( aFetch -> aFetch.getFetchedMapping().getPartName(), Fetch::getClass ) ); final Map<String, Class<? extends Fetch>> expectedFetchClassByAttributeName = new HashMap<>(); expectedFetchClassByAttributeName.put( "pets", DelayedCollectionFetch.class ); expectedFetchClassByAttributeName.put( "homeAddress", EmbeddableFetchImpl.class ); expectedFetchClassByAttributeName.put( "company", EntityDelayedFetchImpl.class ); assertThat( fetchClassByAttributeName, is( expectedFetchClassByAttributeName ) ); } } ); } ); } @Test void testFetchSemanticsWithDeepSubgraph() { scope.inTransaction( session -> { final RootGraphImplementor<Cat> eg = session.createEntityGraph( Cat.class ); eg.addSubgraph( "owner", Person.class ).addSubgraph( "company", ExpressCompany.class ); final SelectStatement sqlAst = buildSqlSelectAst( Cat.class, "select c from Cat as c", eg, GraphSemantic.FETCH, session ); // Check the from-clause assertEntityValuedJoinedGroup( sqlAst, "owner", Person.class, tableGroup -> { List<TableGroupJoin> tableGroupJoins = tableGroup.getTableGroupJoins(); Map<String, Class<? extends TableGroup>> tableGroupByName = tableGroupJoins.stream() .map( TableGroupJoin::getJoinedGroup ) .collect( Collectors.toMap( tg -> tg.getModelPart().getPartName(), TableGroup::getClass ) ); Map<String, Class<? extends TableGroup> > expectedTableGroupByName = new HashMap<>(); expectedTableGroupByName.put( "homeAddress", StandardVirtualTableGroup.class ); expectedTableGroupByName.put( "company", LazyTableGroup.class ); assertThat( tableGroupByName, is( expectedTableGroupByName ) ); } ); // Check the domain-result graph assertDomainResult( sqlAst, Cat.class, fetch -> { assertThat( fetch, instanceOf( EntityFetch.class ) ); final EntityFetch entityFetch = (EntityFetch) fetch; assertThat( entityFetch.getFetchedMapping().getFetchableName(), is( "owner" ) ); assertThat( entityFetch.getReferencedModePart().getJavaType().getJavaTypeClass(), assignableTo( Person.class ) ); assertThat( entityFetch, instanceOf( EntityFetchJoinedImpl.class ) ); final EntityResult ownerEntityResult = ( (EntityFetchJoinedImpl) entityFetch ).getEntityResult(); final Map<String, Class<? extends Fetch>> fetchClassByAttributeName = ownerEntityResult.getFetches() .stream().collect( Collectors.toMap( aFetch -> aFetch.getFetchedMapping().getPartName(), Fetch::getClass ) ); final Map<String, Class<? extends Fetch>> expectedFetchClassByAttributeName = new HashMap<>(); expectedFetchClassByAttributeName.put( "homeAddress", EmbeddableFetchImpl.class ); expectedFetchClassByAttributeName.put( "pets", DelayedCollectionFetch.class ); expectedFetchClassByAttributeName.put( "company", EntityFetchJoinedImpl.class ); assertThat( fetchClassByAttributeName, is( expectedFetchClassByAttributeName ) ); Fetchable fetchable = getFetchable( "company", Person.class ); final Fetch companyFetch = ownerEntityResult.findFetch( fetchable ); assertThat( companyFetch, notNullValue() ); final EntityResult companyEntityResult = ( (EntityFetchJoinedImpl) companyFetch).getEntityResult(); assertThat( companyEntityResult.getFetches().size(), is( 1 ) ); final Fetch shipAddressesFetch = companyEntityResult.getFetches().iterator().next(); assertThat( shipAddressesFetch.getFetchedMapping().getPartName(), is( "shipAddresses" ) ); assertThat( shipAddressesFetch, instanceOf( DelayedCollectionFetch.class ) ); } ); } ); } private Fetchable getFetchable(String attributeName, Class entityClass) { EntityPersister person = scope.getSessionFactory() .getRuntimeMetamodels() .getMappingMetamodel() .findEntityDescriptor( entityClass.getName() ); AttributeMappingsList attributeMappings = person.getAttributeMappings(); Fetchable fetchable = null; for ( int i = 0; i < attributeMappings.size(); i++ ) { AttributeMapping mapping = attributeMappings.get( i ); if ( mapping.getAttributeName().equals( attributeName ) ) { fetchable = mapping; } } return fetchable; } @ParameterizedTest @EnumSource( GraphSemantic.class ) void testBasicElementCollections(GraphSemantic graphSemantic) { scope.inTransaction( session -> { final RootGraphImplementor<Dog> eg = session.createEntityGraph( Dog.class ); eg.addAttributeNodes( "favorites" ); final SelectStatement sqlAst = buildSqlSelectAst( Dog.class, "select d from Dog as d", eg, graphSemantic, session ); // Check the from-clause assertPluralAttributeJoinedGroup( sqlAst, "favorites", tableGroup -> {} ); } ); } @ParameterizedTest @EnumSource( GraphSemantic.class ) void testEmbeddedCollection(GraphSemantic graphSemantic) { scope.inTransaction( session -> { final RootGraphImplementor<ExpressCompany> eg = session.createEntityGraph( ExpressCompany.class ); eg.addAttributeNodes( "shipAddresses" ); final SelectStatement sqlAst = buildSqlSelectAst( ExpressCompany.class, "select company from ExpressCompany as company", eg, graphSemantic, session ); // Check the from-clause assertPluralAttributeJoinedGroup( sqlAst, "shipAddresses", tableGroup -> { if ( graphSemantic == GraphSemantic.LOAD ) { assertThat( tableGroup.getTableGroupJoins(), hasSize( 1 ) ); assertThat( tableGroup.getNestedTableGroupJoins(), isEmpty() ); final TableGroup compositeTableGroup = tableGroup.getTableGroupJoins() .iterator() .next() .getJoinedGroup(); assertThat( compositeTableGroup, instanceOf( StandardVirtualTableGroup.class ) ); assertThat( compositeTableGroup.getNestedTableGroupJoins(), isEmpty() ); assertThat( compositeTableGroup.getTableGroupJoins(), hasSize( 1 ) ); final TableGroup joinedGroup = compositeTableGroup.getTableGroupJoins().get( 0 ).getJoinedGroup(); assertThat( joinedGroup.isInitialized(), is( false ) ); } else { assertThat( tableGroup.getTableGroupJoins(), hasSize( 1 ) ); assertThat( tableGroup.getNestedTableGroupJoins(), isEmpty() ); final TableGroup compositeTableGroup = CollectionUtils.getOnlyElement( tableGroup.getTableGroupJoins() ).getJoinedGroup(); assertThat( compositeTableGroup, instanceOf( StandardVirtualTableGroup.class ) ); assertThat( compositeTableGroup.getNestedTableGroupJoins(), isEmpty() ); assertThat( compositeTableGroup.getTableGroupJoins(), hasSize( 1 ) ); final TableGroup joinedGroup = compositeTableGroup.getTableGroupJoins().get( 0 ).getJoinedGroup(); assertThat( joinedGroup.isInitialized(), is( false ) ); } } ); } ); } // util methods for verifying 'from-clause' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private void assertEmptyJoinedGroup(SelectStatement sqlAst) { final FromClause fromClause = sqlAst.getQuerySpec().getFromClause(); assertThat( fromClause.getRoots(), hasSize( 1 ) ); final TableGroup rootTableGroup = fromClause.getRoots().get( 0 ); assertThat( rootTableGroup.getTableGroupJoins(), hasSize( 1 ) ); final TableGroup tableGroup = rootTableGroup.getTableGroupJoins().get( 0 ).getJoinedGroup(); assertThat( tableGroup.isInitialized(), is( false ) ); } private void assertEntityValuedJoinedGroup(SelectStatement sqlAst, String expectedAttributeName, Class<?> expectedEntityJpaClass, Consumer<TableGroup> tableGroupConsumer) { final FromClause fromClause = sqlAst.getQuerySpec().getFromClause(); assertThat( fromClause.getRoots(), hasSize( 1 ) ); final TableGroup rootTableGroup = fromClause.getRoots().get( 0 ); assertThat( rootTableGroup.getTableGroupJoins(), hasSize( 1 ) ); final TableGroup joinedGroup = rootTableGroup.getTableGroupJoins().iterator().next().getJoinedGroup(); assertThat( joinedGroup.getModelPart().getPartName(), is( expectedAttributeName ) ); assertThat( joinedGroup.getModelPart().getJavaType().getJavaTypeClass(), assignableTo( expectedEntityJpaClass ) ); assertThat( joinedGroup.getModelPart(), instanceOf( EntityValuedModelPart.class ) ); tableGroupConsumer.accept( joinedGroup ); } private void assertPluralAttributeJoinedGroup(SelectStatement sqlAst, String expectedPluralAttributeName, Consumer<TableGroup> tableGroupConsumer) { final FromClause fromClause = sqlAst.getQuerySpec().getFromClause(); assertThat( fromClause.getRoots(), hasSize( 1 ) ); final TableGroup root = fromClause.getRoots().get( 0 ); assertThat( root.getTableGroupJoins(), hasSize( 1 ) ); final TableGroup joinedGroup = root.getTableGroupJoins().get( 0 ).getJoinedGroup(); assertThat( joinedGroup.getModelPart().getPartName(), is( expectedPluralAttributeName ) ); assertThat( joinedGroup.getModelPart(), instanceOf( PluralAttributeMapping.class ) ); tableGroupConsumer.accept( joinedGroup ); } private void assertPersonHomeAddressJoinedGroup(TableGroup tableGroup) { assertThat( tableGroup.getTableGroupJoins(), hasSize( 2 ) ); final TableGroup company = tableGroup.getTableGroupJoins().get( 0 ).getJoinedGroup(); assertThat( company.getModelPart().getPartName(), is( "company" ) ); assertThat( company.getModelPart(), instanceOf( ToOneAttributeMapping.class ) ); assertThat( company, instanceOf( LazyTableGroup.class ) ); assertThat( company.isInitialized(), is( false ) ); final TableGroup homeAddress = tableGroup.getTableGroupJoins().get( 1 ).getJoinedGroup(); assertThat( homeAddress.getModelPart().getPartName(), is( "homeAddress" ) ); assertThat( homeAddress.getModelPart(), instanceOf( EmbeddedAttributeMapping.class ) ); assertThat( homeAddress, instanceOf( StandardVirtualTableGroup.class ) ); } // util methods for verifying 'domain-result' graph ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ private void assertDomainResult(SelectStatement sqlAst, Class<?> expectedEntityJpaClass, Consumer<Fetch> fetchConsumer) { assertThat( sqlAst.getDomainResultDescriptors(), hasSize( 1 ) ); final DomainResult domainResult = sqlAst.getDomainResultDescriptors().get( 0 ); assertThat( domainResult, instanceOf( EntityResult.class ) ); final EntityResult entityResult = (EntityResult) domainResult; assertThat( entityResult.getReferencedModePart().getJavaType().getJavaTypeClass(), assignableTo( expectedEntityJpaClass ) ); assertThat( entityResult.getFetches().size(), is( 1 ) ); final Fetch fetch = entityResult.getFetches().iterator().next(); fetchConsumer.accept(fetch); } private <T> SelectStatement buildSqlSelectAst( Class<T> entityType, String hql, RootGraphImplementor<T> entityGraph, GraphSemantic mode, SessionImplementor session) { final LoadQueryInfluencers loadQueryInfluencers = new LoadQueryInfluencers( session.getSessionFactory() ); final Query<T> query = session.createQuery( hql, entityType ); final SqmQueryImplementor<String> hqlQuery = (SqmQueryImplementor<String>) query; hqlQuery.applyGraph( entityGraph, mode ); final SqmSelectStatement<String> sqmStatement = (SqmSelectStatement<String>) hqlQuery.getSqmStatement(); final StandardSqmTranslator<SelectStatement> sqmConverter = new StandardSqmTranslator<>( sqmStatement, hqlQuery.getQueryOptions(), ( (SqmQueryImpl<?>) hqlQuery ).getDomainParameterXref(), hqlQuery.getParameterBindings(), loadQueryInfluencers, session.getSessionFactory().getSqlTranslationEngine(), true ); final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate(); return sqmInterpretation.getSqlAst(); } @Entity(name = "Dog") public static
HqlEntityGraphTest
java
google__guice
core/test/com/googlecode/guice/BytecodeGenTest.java
{ "start": 10490, "end": 10593 }
class ____ { String sayHi() { return "HI"; } } protected static
PublicClassPackageMethod
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/OutputStreamManager.java
{ "start": 1509, "end": 12609 }
class ____ extends AbstractManager implements ByteBufferDestination { protected final Layout<?> layout; protected ByteBuffer byteBuffer; private volatile OutputStream outputStream; private boolean skipFooter; protected OutputStreamManager( final OutputStream os, final String streamName, final Layout<?> layout, final boolean writeHeader) { this(os, streamName, layout, writeHeader, Constants.ENCODER_BYTE_BUFFER_SIZE); } protected OutputStreamManager( final OutputStream os, final String streamName, final Layout<?> layout, final boolean writeHeader, final int bufferSize) { this(os, streamName, layout, writeHeader, ByteBuffer.wrap(new byte[bufferSize])); } /** * @since 2.6 * @deprecated */ @Deprecated protected OutputStreamManager( final OutputStream os, final String streamName, final Layout<?> layout, final boolean writeHeader, final ByteBuffer byteBuffer) { super(null, streamName); this.outputStream = os; this.layout = layout; if (writeHeader) { writeHeader(os); } this.byteBuffer = Objects.requireNonNull(byteBuffer, "byteBuffer"); } /** * @since 2.7 */ protected OutputStreamManager( final LoggerContext loggerContext, final OutputStream os, final String streamName, final boolean createOnDemand, final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer byteBuffer) { super(loggerContext, streamName); if (createOnDemand && os != null) { LOGGER.error( "Invalid OutputStreamManager configuration for '{}': You cannot both set the OutputStream and request on-demand.", streamName); } this.layout = layout; this.byteBuffer = Objects.requireNonNull(byteBuffer, "byteBuffer"); this.outputStream = os; if (writeHeader) { writeHeader(os); } } /** * Creates a Manager. * * @param name The name of the stream to manage. * @param data The data to pass to the Manager. * @param factory The factory to use to create the Manager. * @param <T> The type of the OutputStreamManager. * @return An OutputStreamManager. */ public static <T> OutputStreamManager getManager( final String name, final T data, final ManagerFactory<? extends OutputStreamManager, T> factory) { return AbstractManager.getManager(name, factory, data); } @SuppressWarnings("unused") protected OutputStream createOutputStream() throws IOException { throw new IllegalStateException(getClass().getCanonicalName() + " must implement createOutputStream()"); } /** * Indicate whether the footer should be skipped or not. * @param skipFooter true if the footer should be skipped. */ public void skipFooter(final boolean skipFooter) { this.skipFooter = skipFooter; } /** * Default hook to write footer during close. */ @Override public boolean releaseSub(final long timeout, final TimeUnit timeUnit) { writeFooter(); return closeOutputStream(); } protected void writeHeader(final OutputStream os) { if (layout != null && os != null) { final byte[] header = layout.getHeader(); if (header != null) { try { os.write(header, 0, header.length); } catch (final IOException e) { logError("Unable to write header", e); } } } } /** * Writes the footer. */ protected void writeFooter() { if (layout == null || skipFooter) { return; } final byte[] footer = layout.getFooter(); if (footer != null) { write(footer); } } /** * Returns the status of the stream. * @return true if the stream is open, false if it is not. */ public boolean isOpen() { return getCount() > 0; } public boolean hasOutputStream() { return outputStream != null; } protected OutputStream getOutputStream() throws IOException { if (outputStream == null) { outputStream = createOutputStream(); } return outputStream; } protected void setOutputStream(final OutputStream os) { this.outputStream = os; } /** * Some output streams synchronize writes while others do not. * @param bytes The serialized Log event. * @throws AppenderLoggingException if an error occurs. */ protected void write(final byte[] bytes) { write(bytes, 0, bytes.length, false); } /** * Some output streams synchronize writes while others do not. * @param bytes The serialized Log event. * @param immediateFlush If true, flushes after writing. * @throws AppenderLoggingException if an error occurs. */ protected void write(final byte[] bytes, final boolean immediateFlush) { write(bytes, 0, bytes.length, immediateFlush); } @Override public void writeBytes(final byte[] data, final int offset, final int length) { write(data, offset, length, false); } /** * Some output streams synchronize writes while others do not. Synchronizing here insures that * log events won't be intertwined. * @param bytes The serialized Log event. * @param offset The offset into the byte array. * @param length The number of bytes to write. * @throws AppenderLoggingException if an error occurs. */ protected void write(final byte[] bytes, final int offset, final int length) { writeBytes(bytes, offset, length); } /** * Some output streams synchronize writes while others do not. Synchronizing here insures that * log events won't be intertwined. * @param bytes The serialized Log event. * @param offset The offset into the byte array. * @param length The number of bytes to write. * @param immediateFlush flushes immediately after writing. * @throws AppenderLoggingException if an error occurs. */ protected synchronized void write( final byte[] bytes, final int offset, final int length, final boolean immediateFlush) { if (immediateFlush && byteBuffer.position() == 0) { writeToDestination(bytes, offset, length); flushDestination(); return; } if (length >= byteBuffer.capacity()) { // if request length exceeds buffer capacity, flush the buffer and write the data directly flush(); writeToDestination(bytes, offset, length); } else { if (length > byteBuffer.remaining()) { flush(); } byteBuffer.put(bytes, offset, length); } if (immediateFlush) { flush(); } } /** * Writes the specified section of the specified byte array to the stream. * * @param bytes the array containing data * @param offset from where to write * @param length how many bytes to write * @since 2.6 */ protected synchronized void writeToDestination(final byte[] bytes, final int offset, final int length) { try { getOutputStream().write(bytes, offset, length); } catch (final IOException ex) { throw new AppenderLoggingException("Error writing to stream " + getName(), ex); } } /** * Calls {@code flush()} on the underlying output stream. * @since 2.6 */ protected synchronized void flushDestination() { final OutputStream stream = outputStream; // access volatile field only once per method if (stream != null) { try { stream.flush(); } catch (final IOException ex) { throw new AppenderLoggingException("Error flushing stream " + getName(), ex); } } } /** * Drains the ByteBufferDestination's buffer into the destination. By default this calls * {@link OutputStreamManager#write(byte[], int, int, boolean)} with the buffer contents. * The underlying stream is not {@linkplain OutputStream#flush() flushed}. * * @see #flushDestination() * @since 2.6 */ protected synchronized void flushBuffer(final ByteBuffer buf) { ((Buffer) buf).flip(); try { if (buf.remaining() > 0) { writeToDestination(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining()); } } finally { buf.clear(); } } /** * Flushes any buffers. */ public synchronized void flush() { flushBuffer(byteBuffer); flushDestination(); } protected synchronized boolean closeOutputStream() { flush(); final OutputStream stream = outputStream; // access volatile field only once per method if (stream == null || stream == System.out || stream == System.err) { return true; } try { stream.close(); LOGGER.debug("OutputStream closed"); } catch (final IOException ex) { logError("Unable to close stream", ex); return false; } return true; } /** * Returns this {@code ByteBufferDestination}'s buffer. * @return the buffer * @since 2.6 */ @Override public ByteBuffer getByteBuffer() { return byteBuffer; } /** * Drains the ByteBufferDestination's buffer into the destination. By default this calls * {@link #flushBuffer(ByteBuffer)} with the specified buffer. Subclasses may override. * <p> * Do not call this method lightly! For some subclasses this is a very expensive operation. For example, * {@link MemoryMappedFileManager} will assume this method was called because the end of the mapped region * was reached during a text encoding operation and will {@linkplain MemoryMappedFileManager#remap() remap} its * buffer. * </p><p> * To just flush the buffered contents to the underlying stream, call * {@link #flushBuffer(ByteBuffer)} directly instead. * </p> * * @param buf the buffer whose contents to write the destination * @return the specified buffer * @since 2.6 */ @Override public ByteBuffer drain(final ByteBuffer buf) { flushBuffer(buf); return buf; } @Override public void writeBytes(final ByteBuffer data) { if (data.remaining() == 0) { return; } synchronized (this) { ByteBufferDestinationHelper.writeToUnsynchronized(data, this); } } }
OutputStreamManager
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/utils/AssociatedRecords.java
{ "start": 6091, "end": 6737 }
class ____ implements IterableIterator<RowData> { private final List<OuterRecord> records; private int index = 0; private RecordsIterable(List<OuterRecord> records) { this.records = records; } @Override public Iterator<RowData> iterator() { index = 0; return this; } @Override public boolean hasNext() { return index < records.size(); } @Override public RowData next() { RowData row = records.get(index).record; index++; return row; } } }
RecordsIterable
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/security/authenticator/TestDigestLoginModule.java
{ "start": 1512, "end": 1586 }
class ____ extends PlainLoginModule { public static
TestDigestLoginModule
java
apache__camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/ConferenceEndpointConfigurationConfigurer.java
{ "start": 733, "end": 3718 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("ApiName", org.apache.camel.component.twilio.internal.TwilioApiName.class); map.put("MethodName", java.lang.String.class); map.put("PathAccountSid", java.lang.String.class); map.put("PathSid", java.lang.String.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.twilio.ConferenceEndpointConfiguration target = (org.apache.camel.component.twilio.ConferenceEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "pathaccountsid": case "pathAccountSid": target.setPathAccountSid(property(camelContext, java.lang.String.class, value)); return true; case "pathsid": case "pathSid": target.setPathSid(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return org.apache.camel.component.twilio.internal.TwilioApiName.class; case "methodname": case "methodName": return java.lang.String.class; case "pathaccountsid": case "pathAccountSid": return java.lang.String.class; case "pathsid": case "pathSid": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.twilio.ConferenceEndpointConfiguration target = (org.apache.camel.component.twilio.ConferenceEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return target.getApiName(); case "methodname": case "methodName": return target.getMethodName(); case "pathaccountsid": case "pathAccountSid": return target.getPathAccountSid(); case "pathsid": case "pathSid": return target.getPathSid(); default: return null; } } }
ConferenceEndpointConfigurationConfigurer
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
{ "start": 9232, "end": 10207 }
interface ____ { CompletionStage<Integer> s(); } @Test public void returnsCompletedFuture_forFuture() throws Exception { ReturnFuture m = mock(ReturnFuture.class); Future<String> fut = m.f(); assertNotNull(fut); assertTrue(fut.isDone()); assertNull(fut.get()); } @Test public void returnsCompletedFuture_forCompletableFuture() { ReturnCompletableFuture m = mock(ReturnCompletableFuture.class); CompletableFuture<Void> fut = m.v(); assertNotNull(fut); assertTrue(fut.isDone()); assertDoesNotThrow(fut::join); } @Test public void returnsCompletedFuture_forCompletionStage() { ReturnCompletionStage m = mock(ReturnCompletionStage.class); CompletionStage<Integer> st = m.s(); assertNotNull(st); assertTrue(st.toCompletableFuture().isDone()); assertNull(st.toCompletableFuture().join()); } }
ReturnCompletionStage
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/planner/EsPhysicalOperationProviders.java
{ "start": 21012, "end": 26851 }
class ____ extends ShardContext { private final int index; /** * In production, this will be a {@link SearchContext}, but we don't want to drag that huge * dependency here. */ private final Releasable releasable; private final SearchExecutionContext ctx; private final AliasFilter aliasFilter; private final String shardIdentifier; public DefaultShardContext(int index, Releasable releasable, SearchExecutionContext ctx, AliasFilter aliasFilter) { this.index = index; this.releasable = releasable; this.ctx = ctx; this.aliasFilter = aliasFilter; // Build the shardIdentifier once up front so we can reuse references to it in many places. this.shardIdentifier = this.ctx.getFullyQualifiedIndex().getName() + ":" + this.ctx.getShardId(); } @Override public int index() { return index; } @Override public IndexSearcher searcher() { return ctx.searcher(); } @Override public Optional<SortAndFormats> buildSort(List<SortBuilder<?>> sorts) throws IOException { return SortBuilder.buildSort(sorts, ctx, false); } @Override public String shardIdentifier() { return shardIdentifier; } @Override public SourceLoader newSourceLoader(Set<String> sourcePaths) { var filter = sourcePaths != null ? new SourceFilter(sourcePaths.toArray(new String[0]), null) : null; // Apply vector exclusion logic similar to ShardGetService var fetchSourceContext = filter != null ? FetchSourceContext.of(true, null, filter.getIncludes(), filter.getExcludes()) : null; var result = maybeExcludeVectorFields(ctx.getMappingLookup(), ctx.getIndexSettings(), fetchSourceContext, null); var vectorFilter = result.v2(); if (vectorFilter != null) { filter = vectorFilter; } return ctx.newSourceLoader(filter, false); } @Override public Query toQuery(QueryBuilder queryBuilder) { Query query = ctx.toQuery(queryBuilder).query(); if (ctx.nestedLookup() != NestedLookup.EMPTY && NestedHelper.mightMatchNestedDocs(query, ctx)) { // filter out nested documents query = new BooleanQuery.Builder().add(query, BooleanClause.Occur.MUST) .add(newNonNestedFilter(ctx.indexVersionCreated()), BooleanClause.Occur.FILTER) .build(); } if (aliasFilter != AliasFilter.EMPTY) { Query filterQuery = ctx.toQuery(aliasFilter.getQueryBuilder()).query(); query = new BooleanQuery.Builder().add(query, BooleanClause.Occur.MUST) .add(filterQuery, BooleanClause.Occur.FILTER) .build(); } return query; } @Override public BlockLoader blockLoader( String name, boolean asUnsupportedSource, MappedFieldType.FieldExtractPreference fieldExtractPreference, BlockLoaderFunctionConfig blockLoaderFunctionConfig ) { if (asUnsupportedSource) { return BlockLoader.CONSTANT_NULLS; } MappedFieldType fieldType = fieldType(name); if (fieldType == null) { // the field does not exist in this context return BlockLoader.CONSTANT_NULLS; } BlockLoader loader = fieldType.blockLoader(new MappedFieldType.BlockLoaderContext() { @Override public String indexName() { return ctx.getFullyQualifiedIndex().getName(); } @Override public IndexSettings indexSettings() { return ctx.getIndexSettings(); } @Override public MappedFieldType.FieldExtractPreference fieldExtractPreference() { return fieldExtractPreference; } @Override public SearchLookup lookup() { return ctx.lookup(); } @Override public Set<String> sourcePaths(String name) { return ctx.sourcePath(name); } @Override public String parentField(String field) { return ctx.parentPath(field); } @Override public FieldNamesFieldMapper.FieldNamesFieldType fieldNames() { return (FieldNamesFieldMapper.FieldNamesFieldType) ctx.lookup().fieldType(FieldNamesFieldMapper.NAME); } @Override public BlockLoaderFunctionConfig blockLoaderFunctionConfig() { return blockLoaderFunctionConfig; } }); if (loader == null) { HeaderWarning.addWarning("Field [{}] cannot be retrieved, it is unsupported or not indexed; returning null", name); return BlockLoader.CONSTANT_NULLS; } return loader; } @Override public @Nullable MappedFieldType fieldType(String name) { return ctx.getFieldType(name); } @Override public double storedFieldsSequentialProportion() { return EsqlPlugin.STORED_FIELDS_SEQUENTIAL_PROPORTION.get(ctx.getIndexSettings().getSettings()); } @Override public void close() { releasable.close(); } } private static
DefaultShardContext
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/path/extract/JSONPath_extract_0.java
{ "start": 123, "end": 787 }
class ____ extends TestCase { public void test_0() throws Exception { String json = "{\"id\":123,\"obj\":{\"id\":123}}"; assertEquals("{\"id\":123}" , JSONPath.extract(json, "$.obj") .toString()); } public void test_1() throws Exception { String json = "{\"f1\":1,\"f2\":2,\"f3\":3,\"f4\":4}"; assertEquals("2" , JSONPath.extract(json, "$.f2") .toString()); } public void test_2() throws Exception { assertEquals("{}" , JSONPath.extract("{}", "$") .toString()); } }
JSONPath_extract_0
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/utils/PasswordEncoderUtilTest.java
{ "start": 1328, "end": 2855 }
class ____ { /** * encode test. */ @Test void encode() { String str = PasswordEncoderUtil.encode("nacos"); String str2 = PasswordEncoderUtil.encode("nacos"); assertNotEquals(str2, str); } @Test void matches() { Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO"); assertTrue(result1); Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO"); assertFalse(result2); Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos")); assertTrue(matches); } @Test void enforcePasswordLength() { String raw72Password = StringUtils.repeat("A", AuthConstants.MAX_PASSWORD_LENGTH); String encodedPassword = PasswordEncoderUtil.encode(raw72Password); assertThrows(IllegalArgumentException.class, () -> PasswordEncoderUtil.encode(null)); String raw73Password = raw72Password.concat("A"); assertThrows(IllegalArgumentException.class, () -> PasswordEncoderUtil.encode(raw73Password)); assertTrue(new BCryptPasswordEncoder().matches(raw73Password, encodedPassword)); assertFalse(new SafeBcryptPasswordEncoder().matches(raw73Password, encodedPassword)); assertFalse(PasswordEncoderUtil.matches(raw73Password, encodedPassword)); } }
PasswordEncoderUtilTest
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/discovery/FilePositionTests.java
{ "start": 1114, "end": 3726 }
class ____ { @Test @DisplayName("factory method preconditions") void preconditions() { assertPreconditionViolationFor(() -> FilePosition.from(-1)); assertPreconditionViolationFor(() -> FilePosition.from(0, -1)); } @Test @DisplayName("create FilePosition from factory method with line number") void filePositionFromLine() { var filePosition = FilePosition.from(42); assertThat(filePosition.getLine()).isEqualTo(42); assertThat(filePosition.getColumn()).isEmpty(); } @Test @DisplayName("create FilePosition from factory method with line number and column number") void filePositionFromLineAndColumn() { var filePosition = FilePosition.from(42, 99); assertThat(filePosition.getLine()).isEqualTo(42); assertThat(filePosition.getColumn()).contains(99); } /** * @since 1.3 */ @ParameterizedTest @MethodSource void filePositionFromQuery(String query, int expectedLine, int expectedColumn) { var optionalFilePosition = FilePosition.fromQuery(query); if (optionalFilePosition.isPresent()) { var filePosition = optionalFilePosition.get(); assertThat(filePosition.getLine()).isEqualTo(expectedLine); assertThat(filePosition.getColumn().orElse(-1)).isEqualTo(expectedColumn); } else { assertEquals(-1, expectedColumn); assertEquals(-1, expectedLine); } } @SuppressWarnings("unused") static Stream<Arguments> filePositionFromQuery() { return Stream.of( // arguments(null, -1, -1), // arguments("?!", -1, -1), // arguments("line=ZZ", -1, -1), // arguments("line=42", 42, -1), // arguments("line=42&column=99", 42, 99), // arguments("line=42&column=ZZ", 42, -1), // arguments("line=42&abc=xyz&column=99", 42, 99), // arguments("1=3&foo=X&line=42&abc=xyz&column=99&enigma=393939", 42, 99), // // First one wins: arguments("line=42&line=555", 42, -1), // arguments("line=42&line=555&column=99&column=555", 42, 99) // ); } @Test @DisplayName("equals() and hashCode() with column number cached by Integer.valueOf()") void equalsAndHashCode() { var same = FilePosition.from(42, 99); var sameSame = FilePosition.from(42, 99); var different = FilePosition.from(1, 2); assertEqualsAndHashCode(same, sameSame, different); } @Test @DisplayName("equals() and hashCode() with column number not cached by Integer.valueOf()") void equalsAndHashCodeWithColumnNumberNotCachedByJavaLangIntegerDotValueOf() { var same = FilePosition.from(42, 99999); var sameSame = FilePosition.from(42, 99999); var different = FilePosition.from(1, 2); assertEqualsAndHashCode(same, sameSame, different); } }
FilePositionTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/ConcatWithMaybeEmptyTckTest.java
{ "start": 765, "end": 1042 }
class ____ extends BaseTck<Integer> { @Override public Publisher<Integer> createPublisher(long elements) { return Flowable.range(1, (int)elements) .concatWith(Maybe.<Integer>empty()) ; } }
ConcatWithMaybeEmptyTckTest