language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__camel
components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/StatementWrapper.java
{ "start": 1095, "end": 1471 }
interface ____ { void call(WrapperExecuteCallback cb) throws Exception; int[] executeBatch() throws SQLException; Integer getUpdateCount() throws SQLException; Object executeStatement() throws SQLException; void populateStatement(Object value, Exchange exchange) throws SQLException; void addBatch(Object value, Exchange exchange); }
StatementWrapper
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java
{ "start": 1993, "end": 5341 }
class ____ implements Filter { private static final Logger LOG = LoggerFactory.getLogger(RestCsrfPreventionFilter.class); public static final String HEADER_USER_AGENT = "User-Agent"; public static final String BROWSER_USER_AGENT_PARAM = "browser-useragents-regex"; public static final String CUSTOM_HEADER_PARAM = "custom-header"; public static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "methods-to-ignore"; static final String BROWSER_USER_AGENTS_DEFAULT = "^Mozilla.*,^Opera.*"; public static final String HEADER_DEFAULT = "X-XSRF-HEADER"; static final String METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE"; private String headerName = HEADER_DEFAULT; private Set<String> methodsToIgnore = null; private Set<Pattern> browserUserAgents; @Override public void init(FilterConfig filterConfig) throws ServletException { String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM); if (customHeader != null) { headerName = customHeader; } String customMethodsToIgnore = filterConfig.getInitParameter(CUSTOM_METHODS_TO_IGNORE_PARAM); if (customMethodsToIgnore != null) { parseMethodsToIgnore(customMethodsToIgnore); } else { parseMethodsToIgnore(METHODS_TO_IGNORE_DEFAULT); } String agents = filterConfig.getInitParameter(BROWSER_USER_AGENT_PARAM); if (agents == null) { agents = BROWSER_USER_AGENTS_DEFAULT; } parseBrowserUserAgents(agents); LOG.info("Adding cross-site request forgery (CSRF) protection, " + "headerName = {}, methodsToIgnore = {}, browserUserAgents = {}", headerName, methodsToIgnore, browserUserAgents); } void parseBrowserUserAgents(String userAgents) { String[] agentsArray = userAgents.split(","); browserUserAgents = new HashSet<>(); for (String patternString : agentsArray) { browserUserAgents.add(Pattern.compile(patternString)); } } void parseMethodsToIgnore(String mti) { String[] methods = mti.split(","); methodsToIgnore = new HashSet<>(); for (int i = 0; i < methods.length; i++) { methodsToIgnore.add(methods[i]); } } /** * This method interrogates the User-Agent String and returns whether it * refers to a browser. If its not a browser, then the requirement for the * CSRF header will not be enforced; if it is a browser, the requirement will * be enforced. * <p> * A User-Agent String is considered to be a browser if it matches * any of the regex patterns from browser-useragent-regex; the default * behavior is to consider everything a browser that matches the following: * "^Mozilla.*,^Opera.*". Subclasses can optionally override * this method to use different behavior. * * @param userAgent The User-Agent String, or null if there isn't one * @return true if the User-Agent String refers to a browser, false if not */ protected boolean isBrowser(String userAgent) { if (userAgent == null) { return false; } for (Pattern pattern : browserUserAgents) { Matcher matcher = pattern.matcher(userAgent); if (matcher.matches()) { return true; } } return false; } /** * Defines the minimal API requirements for the filter to execute its * filtering logic. This
RestCsrfPreventionFilter
java
google__auto
service/processor/src/test/resources/test/EnclosingGeneric.java
{ "start": 848, "end": 1004 }
class ____, but should be suppressed by the * {@code @SuppressWarnings} on the enclosing class. */ @AutoService(GenericService.class) public
reference
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/entrypoint/ClusterEntrypointTest.java
{ "start": 16417, "end": 18265 }
class ____ extends ClusterEntrypoint { private final HighAvailabilityServices haService; private final ResourceManagerFactory<ResourceID> resourceManagerFactory; private final DispatcherRunnerFactory dispatcherRunnerFactory; private TestingEntryPoint( Configuration configuration, HighAvailabilityServices haService, ResourceManagerFactory<ResourceID> resourceManagerFactory, DispatcherRunnerFactory dispatcherRunnerFactory) { super(configuration); SignalHandler.register(LOG); this.haService = haService; this.resourceManagerFactory = resourceManagerFactory; this.dispatcherRunnerFactory = dispatcherRunnerFactory; } @Override protected DispatcherResourceManagerComponentFactory createDispatcherResourceManagerComponentFactory(Configuration configuration) throws IOException { return new DefaultDispatcherResourceManagerComponentFactory( dispatcherRunnerFactory, resourceManagerFactory, SessionRestEndpointFactory.INSTANCE); } @Override protected ExecutionGraphInfoStore createSerializableExecutionGraphStore( Configuration configuration, ScheduledExecutor scheduledExecutor) { return new MemoryExecutionGraphInfoStore(); } @Override protected HighAvailabilityServices createHaServices( Configuration configuration, Executor executor, RpcSystemUtils rpcSystemUtils) { return haService; } @Override protected boolean supportsReactiveMode() { return false; } public static final
TestingEntryPoint
java
apache__rocketmq
tieredstore/src/test/java/org/apache/rocketmq/tieredstore/core/MessageStoreTopicFilterTest.java
{ "start": 1020, "end": 1582 }
class ____ { @Test public void filterTopicTest() { MessageStoreFilter topicFilter = new MessageStoreTopicFilter(new MessageStoreConfig()); Assert.assertTrue(topicFilter.filterTopic("")); Assert.assertTrue(topicFilter.filterTopic(TopicValidator.SYSTEM_TOPIC_PREFIX + "_Topic")); String topicName = "WhiteTopic"; Assert.assertFalse(topicFilter.filterTopic(topicName)); topicFilter.addTopicToBlackList(topicName); Assert.assertTrue(topicFilter.filterTopic(topicName)); } }
MessageStoreTopicFilterTest
java
apache__kafka
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
{ "start": 16949, "end": 19429 }
class ____ { String groupId = null; String groupInstanceId = null; String memberId = null; String protocolType = "consumer"; JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols = new JoinGroupRequestData.JoinGroupRequestProtocolCollection(0); int sessionTimeoutMs = 500; int rebalanceTimeoutMs = 500; String reason = null; JoinGroupRequestBuilder withGroupId(String groupId) { this.groupId = groupId; return this; } JoinGroupRequestBuilder withGroupInstanceId(String groupInstanceId) { this.groupInstanceId = groupInstanceId; return this; } JoinGroupRequestBuilder withMemberId(String memberId) { this.memberId = memberId; return this; } JoinGroupRequestBuilder withDefaultProtocolTypeAndProtocols() { this.protocols = toProtocols("range"); return this; } JoinGroupRequestBuilder withProtocolSuperset() { this.protocols = toProtocols("range", "roundrobin"); return this; } JoinGroupRequestBuilder withProtocolType(String protocolType) { this.protocolType = protocolType; return this; } JoinGroupRequestBuilder withProtocols(JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols) { this.protocols = protocols; return this; } JoinGroupRequestBuilder withRebalanceTimeoutMs(int rebalanceTimeoutMs) { this.rebalanceTimeoutMs = rebalanceTimeoutMs; return this; } JoinGroupRequestBuilder withSessionTimeoutMs(int sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; return this; } JoinGroupRequestBuilder withReason(String reason) { this.reason = reason; return this; } JoinGroupRequestData build() { return new JoinGroupRequestData() .setGroupId(groupId) .setGroupInstanceId(groupInstanceId) .setMemberId(memberId) .setProtocolType(protocolType) .setProtocols(protocols) .setRebalanceTimeoutMs(rebalanceTimeoutMs) .setSessionTimeoutMs(sessionTimeoutMs) .setReason(reason); } } public static
JoinGroupRequestBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MockitoDoSetupTest.java
{ "start": 3408, "end": 3720 }
class ____ { public int test(Test test) { Mockito.doReturn(1).when(test).test(null); Mockito.doThrow(new Exception()).when(test).test(null); return 1; } } """) .expectUnchanged() .doTest(); } }
Test
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/telemetry/endpoints/ontextmessage/MultiTextReceived_MultiTextResponse_Endpoint.java
{ "start": 273, "end": 518 }
class ____ { @OnTextMessage public Multi<String> onMessage(Multi<String> messages) { return messages.flatMap(msg -> Multi.createFrom().items("echo 0: " + msg, "echo 1: " + msg)); } }
MultiTextReceived_MultiTextResponse_Endpoint
java
grpc__grpc-java
testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java
{ "start": 2421, "end": 4366 }
class ____ { public final ImmutableMap<TagKey, TagValue> tags; public final ImmutableMap<Measure, Number> metrics; private MetricsRecord( ImmutableMap<TagKey, TagValue> tags, ImmutableMap<Measure, Number> metrics) { this.tags = tags; this.metrics = metrics; } /** * Returns the value of a metric, or {@code null} if not found. */ @Nullable public Double getMetric(Measure measure) { for (Map.Entry<Measure, Number> m : metrics.entrySet()) { if (m.getKey().equals(measure)) { Number value = m.getValue(); if (value instanceof Double) { return (Double) value; } else if (value instanceof Long) { return (double) (Long) value; } throw new AssertionError("Unexpected measure value type: " + value.getClass().getName()); } } return null; } /** * Returns the value of a metric converted to long, or throw if not found. */ public long getMetricAsLongOrFail(Measure measure) { Double doubleValue = getMetric(measure); checkNotNull(doubleValue, "Measure not found: %s", measure.getName()); long longValue = (long) (Math.abs(doubleValue) + 0.0001); if (doubleValue < 0) { longValue = -longValue; } return longValue; } @Override public String toString() { return "[tags=" + tags + ", metrics=" + metrics + "]"; } } /** * This tag will be propagated by {@link FakeTagger} on the wire. */ public static final TagKey EXTRA_TAG = TagKey.create("/rpc/test/extratag"); private static final String EXTRA_TAG_HEADER_VALUE_PREFIX = "extratag:"; /** * A {@link Tagger} implementation that saves metrics records to be accessible from {@link * #pollRecord()} and {@link #pollRecord(long, TimeUnit)}, until {@link #rolloverRecords} is * called. */ public static final
MetricsRecord
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/strategy/DefaultInputConsumableDecider.java
{ "start": 5126, "end": 5859 }
class ____ implements InputConsumableDecider.Factory { public static final InputConsumableDecider.Factory INSTANCE = new Factory(); // disable public instantiation. private Factory() {} @Override public InputConsumableDecider createInstance( SchedulingTopology schedulingTopology, Function<ExecutionVertexID, Boolean> scheduledVertexRetriever, Function<ExecutionVertexID, ExecutionState> executionStateRetriever) { return new DefaultInputConsumableDecider( scheduledVertexRetriever, schedulingTopology::getResultPartition, executionStateRetriever); } } }
Factory
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/pipeline/BucketScriptAggregatorTests.java
{ "start": 2406, "end": 7554 }
class ____ extends AggregatorTestCase { private final String SCRIPT_NAME = "script_name"; @Override protected ScriptService getMockScriptService() { MockScriptEngine scriptEngine = new MockScriptEngine( MockScriptEngine.NAME, Collections.singletonMap(SCRIPT_NAME, script -> script.get("the_avg")), Collections.emptyMap() ); Map<String, ScriptEngine> engines = Collections.singletonMap(scriptEngine.getType(), scriptEngine); return new ScriptService( Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS, () -> 1L, TestProjectResolvers.singleProject(randomProjectIdOrDefault()) ); } public void testScript() throws IOException { MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER); MappedFieldType fieldType1 = new KeywordFieldMapper.KeywordFieldType("the_field"); FiltersAggregationBuilder filters = new FiltersAggregationBuilder("placeholder", new MatchAllQueryBuilder()).subAggregation( new TermsAggregationBuilder("the_terms").userValueTypeHint(ValueType.STRING) .field("the_field") .subAggregation(new AvgAggregationBuilder("the_avg").field("number_field")) ) .subAggregation( new BucketScriptPipelineAggregationBuilder( "bucket_script", Collections.singletonMap("the_avg", "the_terms['test1']>the_avg.value"), new Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPT_NAME, Collections.emptyMap()) ) ); testCase(filters, new MatchAllDocsQuery(), iw -> { Document doc = new Document(); doc.add(new SortedSetDocValuesField("the_field", new BytesRef("test1"))); doc.add(new SortedNumericDocValuesField("number_field", 19)); iw.addDocument(doc); doc = new Document(); doc.add(new SortedSetDocValuesField("the_field", new BytesRef("test2"))); doc.add(new SortedNumericDocValuesField("number_field", 55)); iw.addDocument(doc); }, f -> { assertThat(((InternalSimpleValue) (f.getBuckets().get(0).getAggregations().get("bucket_script"))).value, equalTo(19.0)); }, fieldType, fieldType1 ); } public void testNonMultiBucketParent() { MappedFieldType fieldType = new NumberFieldMapper.NumberFieldType("number_field", NumberFieldMapper.NumberType.INTEGER); MappedFieldType fieldType1 = new KeywordFieldMapper.KeywordFieldType("the_field"); FilterAggregationBuilder filter = new FilterAggregationBuilder("placeholder", new MatchAllQueryBuilder()).subAggregation( new TermsAggregationBuilder("the_terms").userValueTypeHint(ValueType.STRING) .field("the_field") .subAggregation(new AvgAggregationBuilder("the_avg").field("number_field")) ) .subAggregation( new BucketScriptPipelineAggregationBuilder( "bucket_script", Collections.singletonMap("the_avg", "the_terms['test1']>the_avg.value"), new Script(ScriptType.INLINE, MockScriptEngine.NAME, SCRIPT_NAME, Collections.emptyMap()) ) ); assertThrows( "Expected a multi bucket aggregation but got [InternalFilter] for aggregation [bucket_script]", IllegalArgumentException.class, () -> testCase(filter, new MatchAllDocsQuery(), iw -> { Document doc = new Document(); doc.add(new SortedSetDocValuesField("the_field", new BytesRef("test1"))); doc.add(new SortedNumericDocValuesField("number_field", 19)); iw.addDocument(doc); doc = new Document(); doc.add(new SortedSetDocValuesField("the_field", new BytesRef("test2"))); doc.add(new SortedNumericDocValuesField("number_field", 55)); iw.addDocument(doc); }, f -> fail("This shouldn't be called"), fieldType, fieldType1) ); } private void testCase( AggregationBuilder aggregationBuilder, Query query, CheckedConsumer<RandomIndexWriter, IOException> buildIndex, Consumer<InternalFilters> verify, MappedFieldType... fieldType ) throws IOException { try (Directory directory = newDirectory()) { RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory); buildIndex.accept(indexWriter); indexWriter.close(); try (DirectoryReader indexReader = DirectoryReader.open(directory)) { InternalFilters filters; filters = searchAndReduce(indexReader, new AggTestConfig(aggregationBuilder, fieldType).withQuery(query)); verify.accept(filters); } } } }
BucketScriptAggregatorTests
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/ArtifactResolverException.java
{ "start": 954, "end": 1484 }
class ____ extends MavenException { private final ArtifactResolverResult result; /** * @param message the message for the exception * @param e the exception itself * @param result the resolution result containing detailed information */ public ArtifactResolverException(String message, Exception e, ArtifactResolverResult result) { super(message, e); this.result = result; } public ArtifactResolverResult getResult() { return result; } }
ArtifactResolverException
java
apache__camel
components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpAcknowledgementDeliveryExceptionTest.java
{ "start": 1105, "end": 3545 }
class ____ extends MllpExceptionTestSupport { static final String TEST_EXCEPTION_MESSAGE = "HL7 Acknowledgment Delivery Failed"; MllpAcknowledgementDeliveryException instance; /** * Description of test. * */ @Test public void testConstructorOne() { instance = new MllpAcknowledgementDeliveryException(HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertTrue(instance.getMessage().startsWith(TEST_EXCEPTION_MESSAGE)); assertArrayEquals(HL7_MESSAGE_BYTES, instance.hl7MessageBytes); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.hl7AcknowledgementBytes); } /** * Description of test. * */ @Test public void testConstructorTwo() { instance = new MllpAcknowledgementDeliveryException(HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, CAUSE, LOG_PHI_TRUE); assertSame(CAUSE, instance.getCause()); assertTrue(instance.getMessage().startsWith(TEST_EXCEPTION_MESSAGE)); assertArrayEquals(HL7_MESSAGE_BYTES, instance.hl7MessageBytes); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.hl7AcknowledgementBytes); } /** * Description of test. * */ @Test public void testConstructorThree() { final String alternateExceptionMessage = "Alternate Message"; instance = new MllpAcknowledgementDeliveryException( alternateExceptionMessage, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE); assertTrue(instance.getMessage().startsWith(alternateExceptionMessage)); assertArrayEquals(HL7_MESSAGE_BYTES, instance.hl7MessageBytes); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.hl7AcknowledgementBytes); } /** * Description of test. * */ @Test public void testConstructorFour() { final String alternateExceptionMessage = "Alternate Message"; instance = new MllpAcknowledgementDeliveryException( alternateExceptionMessage, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, CAUSE, LOG_PHI_TRUE); assertSame(CAUSE, instance.getCause()); assertTrue(instance.getMessage().startsWith(alternateExceptionMessage)); assertArrayEquals(HL7_MESSAGE_BYTES, instance.hl7MessageBytes); assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.hl7AcknowledgementBytes); } }
MllpAcknowledgementDeliveryExceptionTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
{ "start": 13282, "end": 14007 }
class ____ { public static int getMatchCount(CharSequence content, String regex) { int count = 0; Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); Matcher matcher = pattern.matcher(content); while (matcher.find()) { count++; } return count; } } """) .doTest(); } @Test public void negativeCase_staticBlock() { compilationHelper .addSourceLines( "in/Test.java", """ import com.google.errorprone.annotations.CompileTimeConstant; import java.util.regex.Pattern;
Test
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/BigIntegerAssertBaseTest.java
{ "start": 868, "end": 1478 }
class ____ extends ComparableAssertBaseTest<BigIntegerAssert, BigInteger> { protected static final String ONE_AS_STRING = "1"; protected BigIntegers bigIntegers; @Override protected BigIntegerAssert create_assertions() { return new BigIntegerAssert(ONE); } @Override protected void inject_internal_objects() { super.inject_internal_objects(); bigIntegers = mock(BigIntegers.class); assertions.bigIntegers = bigIntegers; } @Override protected Comparables getComparables(BigIntegerAssert someAssertions) { return someAssertions.bigIntegers; } }
BigIntegerAssertBaseTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/monitor/jvm/JvmGcMonitorServiceTests.java
{ "start": 875, "end": 7657 }
class ____ extends ESTestCase { public void testSlowGcLogging() { final Logger logger = mock(Logger.class); when(logger.isWarnEnabled()).thenReturn(true); when(logger.isInfoEnabled()).thenReturn(true); when(logger.isDebugEnabled()).thenReturn(true); final JvmGcMonitorService.JvmMonitor.Threshold threshold = randomFrom(JvmGcMonitorService.JvmMonitor.Threshold.values()); final String name = randomAlphaOfLength(16); final long seq = randomIntBetween(1, 1 << 30); final int elapsedValue = randomIntBetween(1, 1 << 10); final long totalCollectionCount = randomIntBetween(1, 16); final long currentCollectionCount = randomIntBetween(1, 16); final TimeValue totalCollectionTime = TimeValue.timeValueMillis(randomIntBetween(1, elapsedValue)); final TimeValue currentCollectionTime = TimeValue.timeValueMillis(randomIntBetween(1, elapsedValue)); final ByteSizeValue lastHeapUsed = ByteSizeValue.ofBytes(randomIntBetween(1, 1 << 10)); JvmStats lastJvmStats = mock(JvmStats.class); JvmStats.Mem lastMem = mock(JvmStats.Mem.class); when(lastMem.getHeapUsed()).thenReturn(lastHeapUsed); when(lastJvmStats.getMem()).thenReturn(lastMem); when(lastJvmStats.toString()).thenReturn("last"); final ByteSizeValue currentHeapUsed = ByteSizeValue.ofBytes(randomIntBetween(1, 1 << 10)); JvmStats currentJvmStats = mock(JvmStats.class); JvmStats.Mem currentMem = mock(JvmStats.Mem.class); when(currentMem.getHeapUsed()).thenReturn(currentHeapUsed); when(currentJvmStats.getMem()).thenReturn(currentMem); when(currentJvmStats.toString()).thenReturn("current"); JvmStats.GarbageCollector gc = mock(JvmStats.GarbageCollector.class); when(gc.getName()).thenReturn(name); when(gc.getCollectionCount()).thenReturn(totalCollectionCount); when(gc.getCollectionTime()).thenReturn(totalCollectionTime); final ByteSizeValue maxHeapUsed = ByteSizeValue.ofBytes(Math.max(lastHeapUsed.getBytes(), currentHeapUsed.getBytes()) + 1 << 10); JvmGcMonitorService.JvmMonitor.SlowGcEvent slowGcEvent = new JvmGcMonitorService.JvmMonitor.SlowGcEvent( gc, currentCollectionCount, currentCollectionTime, elapsedValue, lastJvmStats, currentJvmStats, maxHeapUsed ); JvmGcMonitorService.logSlowGc(logger, threshold, seq, slowGcEvent, (l, c) -> l.toString() + ", " + c.toString()); switch (threshold) { case WARN -> { verify(logger).isWarnEnabled(); verify(logger).warn( "[gc][{}][{}][{}] duration [{}], collections [{}]/[{}], total [{}]/[{}], memory [{}]->[{}]/[{}], all_pools {}", name, seq, totalCollectionCount, currentCollectionTime, currentCollectionCount, TimeValue.timeValueMillis(elapsedValue), currentCollectionTime, totalCollectionTime, lastHeapUsed, currentHeapUsed, maxHeapUsed, "last, current" ); } case INFO -> { verify(logger).isInfoEnabled(); verify(logger).info( "[gc][{}][{}][{}] duration [{}], collections [{}]/[{}], total [{}]/[{}], memory [{}]->[{}]/[{}], all_pools {}", name, seq, totalCollectionCount, currentCollectionTime, currentCollectionCount, TimeValue.timeValueMillis(elapsedValue), currentCollectionTime, totalCollectionTime, lastHeapUsed, currentHeapUsed, maxHeapUsed, "last, current" ); } case DEBUG -> { verify(logger).isDebugEnabled(); verify(logger).debug( "[gc][{}][{}][{}] duration [{}], collections [{}]/[{}], total [{}]/[{}], memory [{}]->[{}]/[{}], all_pools {}", name, seq, totalCollectionCount, currentCollectionTime, currentCollectionCount, TimeValue.timeValueMillis(elapsedValue), currentCollectionTime, totalCollectionTime, lastHeapUsed, currentHeapUsed, maxHeapUsed, "last, current" ); } } verifyNoMoreInteractions(logger); } public void testGcOverheadLogging() { final JvmGcMonitorService.JvmMonitor.Threshold threshold = randomFrom(JvmGcMonitorService.JvmMonitor.Threshold.values()); final int current = randomIntBetween(1, Integer.MAX_VALUE); final long elapsed = randomIntBetween(current, Integer.MAX_VALUE); final long seq = randomIntBetween(1, Integer.MAX_VALUE); final Logger logger = mock(Logger.class); when(logger.isWarnEnabled()).thenReturn(true); when(logger.isInfoEnabled()).thenReturn(true); when(logger.isDebugEnabled()).thenReturn(true); JvmGcMonitorService.logGcOverhead(logger, threshold, current, elapsed, seq); switch (threshold) { case WARN -> { verify(logger).isWarnEnabled(); verify(logger).warn( "[gc][{}] overhead, spent [{}] collecting in the last [{}]", seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed) ); } case INFO -> { verify(logger).isInfoEnabled(); verify(logger).info( "[gc][{}] overhead, spent [{}] collecting in the last [{}]", seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed) ); } case DEBUG -> { verify(logger).isDebugEnabled(); verify(logger).debug( "[gc][{}] overhead, spent [{}] collecting in the last [{}]", seq, TimeValue.timeValueMillis(current), TimeValue.timeValueMillis(elapsed) ); } } verifyNoMoreInteractions(logger); } }
JvmGcMonitorServiceTests
java
google__auto
common/src/main/java/com/google/auto/common/MoreTypes.java
{ "start": 27683, "end": 28447 }
class ____ extends CastingTypeVisitor<PrimitiveType> { private static final PrimitiveTypeVisitor INSTANCE = new PrimitiveTypeVisitor(); PrimitiveTypeVisitor() { super("primitive type"); } @Override public PrimitiveType visitPrimitive(PrimitiveType type, Void ignore) { return type; } } // // visitUnionType would go here, but isn't relevant for annotation processors // /** * Returns a {@link TypeVariable} if the {@link TypeMirror} represents a type variable or throws * an {@link IllegalArgumentException}. */ public static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable) { return maybeTypeVariable.accept(TypeVariableVisitor.INSTANCE, null); } private static final
PrimitiveTypeVisitor
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/abstractclass/ReferencedMapper.java
{ "start": 235, "end": 387 }
class ____ extends AbstractReferencedMapper { @Override public int holderToInt(Holder<String> holder) { return 42; } }
ReferencedMapper
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/UnnecessaryAnonymousClass.java
{ "start": 3098, "end": 3193 }
interface ____ directly and use a method reference instead.", severity = WARNING) public
method
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/TypeConvertible.java
{ "start": 7909, "end": 8018 }
class ____ that defines the "from" type (that is: Class&lt;F&gt;.class) * * @return the "from"
instance
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/ConstructorDetectorTest.java
{ "start": 3660, "end": 14397 }
class ____ { public String id; public String name; public Foo4860() { } public Foo4860(String id) { // should not be called as of Jackson 2.x throw new IllegalStateException("Should not auto-detect args-taking constructor"); } } private final ObjectMapper MAPPER_PROPS = mapperFor(ConstructorDetector.USE_PROPERTIES_BASED); private final ObjectMapper MAPPER_DELEGATING = mapperFor(ConstructorDetector.USE_DELEGATING); private final ObjectMapper MAPPER_DEFAULT = mapperFor(ConstructorDetector.DEFAULT); private final ObjectMapper MAPPER_EXPLICIT = mapperFor(ConstructorDetector.EXPLICIT_ONLY); private final ObjectMapper MAPPER_MUST_ANNOTATE = mapperFor(ConstructorDetector.DEFAULT .withRequireAnnotation(true)); /* /********************************************************************** /* Test methods, selecting from 1-arg constructors, properties-based /********************************************************************** */ @Test public void test1ArgDefaultsToPropertiesNonAnnotated() throws Exception { SingleArgNotAnnotated value = MAPPER_PROPS.readValue(a2q("{'value' : 137 }"), SingleArgNotAnnotated.class); assertEquals(137, value.v); } @Test public void test1ArgDefaultsToPropertiesNonAnnotatedDecimal() throws Exception { SingleArgNotAnnotated value = MAPPER_PROPS.readValue(a2q("{'value' : 137.0 }"), SingleArgNotAnnotated.class); assertEquals(137, value.v); } @Test public void test1ArgDefaultsToPropertiesByte() throws Exception { SingleArgByte value = MAPPER_PROPS.readValue(a2q("{'value' : -99 }"), SingleArgByte.class); assertEquals(-99, value.v); } @Test public void test1ArgDefaultsToPropertiesShort() throws Exception { SingleArgShort value = MAPPER_PROPS.readValue(a2q("{'value' : 137 }"), SingleArgShort.class); assertEquals(137, value.v); } @Test public void test1ArgDefaultsToPropertiesLong() throws Exception { String val = Long.toString(Long.MAX_VALUE); SingleArgLong value = MAPPER_PROPS.readValue(a2q("{'value' : " + val + " }"), SingleArgLong.class); assertEquals(Long.MAX_VALUE, value.v); } @Test public void test1ArgDefaultsToPropertiesFloat() throws Exception { SingleArgFloat value = MAPPER_PROPS.readValue(a2q("{'value' : 136.99 }"), SingleArgFloat.class); assertEquals(136.99f, value.v); } @Test public void test1ArgDefaultsToPropertiesDouble() throws Exception { SingleArgDouble value = MAPPER_PROPS.readValue(a2q("{'value' : 999999999999999999.99 }"), SingleArgDouble.class); assertEquals(999999999999999999.99, value.v); } @Test public void test1ArgDefaultsToPropertiesNoMode() throws Exception { SingleArgNoMode value = MAPPER_PROPS.readValue(a2q("{'value' : 137 }"), SingleArgNoMode.class); assertEquals(137, value.v); } // And specific test for original [databind#1498] @Test public void test1ArgDefaultsToPropertiesIssue1498() throws Exception { SingleArg1498 value = MAPPER_PROPS.readValue(a2q("{'bar' : 404 }"), SingleArg1498.class); assertEquals(404, value._bar); } // This was working already but verify @Test public void testMultiArgAsProperties() throws Exception { TwoArgsNotAnnotated value = MAPPER_PROPS.readValue(a2q("{'a' : 3, 'b':4 }"), TwoArgsNotAnnotated.class); assertEquals(3, value._a); assertEquals(4, value._b); } // 18-Sep-2020, tatu: For now there is a problematic case of multiple eligible // choices; not cleanly solvable for 2.12 @Test public void test1ArgDefaultsToPropsMultipleCtors() throws Exception { // 23-May-2024, tatu: Will fail differently with [databind#4515]; default // constructor available, implicit ones ignored try { MAPPER_PROPS.readerFor(SingleArg2CtorsNotAnnotated.class) .with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .readValue(a2q("{'value' : 137 }")); fail("Should not pass"); } catch (UnrecognizedPropertyException e) { verifyException(e, "\"value\""); } /* } catch (InvalidDefinitionException e) { verifyException(e, "Conflicting property-based creators"); } */ } /* /********************************************************************** /* Test methods, selecting from 1-arg constructors, delegating /********************************************************************** */ @Test public void test1ArgDefaultsToDelegatingNoAnnotation() throws Exception { // No annotation, should be fine? SingleArgNotAnnotated value = MAPPER_DELEGATING.readValue("1972", SingleArgNotAnnotated.class); assertEquals(1972, value.v); } @Test public void test1ArgDefaultsToDelegatingNoMode() throws Exception { // One with `@JsonCreator` no mode annotation (ok since indicated) SingleArgNoMode value = MAPPER_DELEGATING.readValue(" 2812 ", SingleArgNoMode.class); assertEquals(2812, value.v); } /* /********************************************************************** /* Test methods, selecting from 1-arg constructors, heuristic (pre-2.12) /********************************************************************** */ @Test public void test1ArgDefaultsToHeuristics() throws Exception { final ObjectMapper mapper = mapperFor(ConstructorDetector.DEFAULT); final String DOC = " 13117 "; // First: unannotated is ok, defaults to delegating SingleArgNotAnnotated v1 = mapper.readValue(DOC, SingleArgNotAnnotated.class); assertEquals(13117, v1.v); // and ditto for mode-less SingleArgNoMode v2 = mapper.readValue(DOC, SingleArgNoMode.class); assertEquals(13117, v2.v); } /* /********************************************************************** /* Test methods, selecting from 1-arg constructors, explicit fails /********************************************************************** */ // 15-Sep-2020, tatu: Tricky semantics... should this require turning // off of auto-detection? If there is 0-arg ctor, that is to be used /* public void test1ArgFailsNoAnnotation() throws Exception { // First: fail if nothing annotated (for 1-arg case) try { MAPPER_EXPLICIT.readValue(" 2812 ", SingleArgNotAnnotated.class); fail("Should not pass"); } catch (InvalidDefinitionException e) { verifyException(e, "foobar"); } } */ @Test public void test1ArgFailsNoMode() throws Exception { // Second: also fail also if no "mode" indicated try { MAPPER_EXPLICIT.readValue(" 2812 ", SingleArgNoMode.class); fail("Should not pass"); } catch (InvalidDefinitionException e) { verifyException(e, "no 'mode' defined"); verifyException(e, "SingleArgConstructor.REQUIRE_MODE"); } } @Test public void test1ArgRequiresAnnotation() throws Exception { // First: if there is a 0-arg ctor, fine, must use that SingleArgNotAnnotated value = MAPPER_MUST_ANNOTATE.readValue("{ }", SingleArgNotAnnotated.class); assertEquals(new SingleArgNotAnnotated().v, value.v); // But if no such ctor, will fail try { MAPPER_MUST_ANNOTATE.readValue(" { } ", SingleArg1498.class); fail("Should not pass"); } catch (InvalidDefinitionException e) { verifyException(e, "no Creators, like default constructor"); } } @Test public void testMultiArgRequiresAnnotation() throws Exception { try { MAPPER_MUST_ANNOTATE.readValue(" { } ", TwoArgsNotAnnotated.class); fail("Should not pass"); } catch (InvalidDefinitionException e) { verifyException(e, "no Creators, like default constructor"); } } // [databind#3241] @Test void nullHandlingCreator3241() throws Exception { ObjectMapper mapper = mapperBuilder() .constructorDetector(ConstructorDetector.USE_PROPERTIES_BASED) // new! .changeDefaultNullHandling(n -> n.withValueNulls(Nulls.FAIL)) .build(); try { mapper.readValue("{ \"field\": null }", Input3241.class); fail("InvalidNullException expected"); } catch (InvalidNullException e) { verifyException(e, "Invalid `null` value encountered"); } } // [databind#4860] @Test public void testDeserialization4860PropsBased() throws Exception { _test4680With(MAPPER_PROPS); } @Test public void testDeserialization4860Delegating() throws Exception { _test4680With(MAPPER_DELEGATING); } @Test public void testDeserialization4860Default() throws Exception { _test4680With(MAPPER_DEFAULT); } @Test public void testDeserialization4860Explicit() throws Exception { _test4680With(MAPPER_EXPLICIT); } private void _test4680With(ObjectMapper mapper) throws Exception { _test4680With(mapper, "{}", a2q("{'id':null,'name':null}")); _test4680With(mapper, a2q("{'id':'something'}"), a2q("{'id':'something','name':null}")); _test4680With(mapper, a2q("{'id':'something','name':'name'}"), a2q("{'id':'something','name':'name'}")); } private void _test4680With(ObjectMapper mapper, String input, String output) throws Exception { Foo4860 result = mapper.readValue(input, Foo4860.class); assertEquals(output, mapper.writeValueAsString(result)); } /* /********************************************************************** /* Helper methods /********************************************************************** */ private JsonMapper.Builder mapperBuilder() { return JsonMapper.builder() .annotationIntrospector(new ImplicitNameIntrospector()); } private ObjectMapper mapperFor(ConstructorDetector cd) { return mapperBuilder() .constructorDetector(cd) .build(); } }
Foo4860
java
apache__logging-log4j2
log4j-jakarta-web/src/main/java/org/apache/logging/log4j/web/ServletRequestThreadContext.java
{ "start": 1010, "end": 1741 }
class ____ { public static void put(final String key, final ServletRequest servletRequest) { put(key, "RemoteAddr", servletRequest.getRemoteAddr()); put(key, "RemoteHost", servletRequest.getRemoteHost()); put(key, "RemotePort", servletRequest.getRemotePort()); } public static void put(final String key, final String field, final Object value) { put(key + "." + field, Objects.toString(value)); } public static void put(final String key, final String value) { ThreadContext.put(key, value); } public static void put(final String key, final HttpServletRequest servletRequest) { put(key, (ServletRequest) servletRequest); } }
ServletRequestThreadContext
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/inheritfromconfig/multiple/CarMapperTest.java
{ "start": 670, "end": 2599 }
class ____ { @ProcessorTest public void testMapEntityToDto() { CarDto dto = CarMapper.MAPPER.mapTo( newCar() ); assertThat( dto.getDbId() ).isEqualTo( 9L ); assertThat( dto.getMaker() ).isEqualTo( "Nissan" ); assertThat( dto.getSeatCount() ).isEqualTo( 5 ); } @ProcessorTest public void testMapDtoToEntity() { CarEntity car = CarMapper.MAPPER.mapFrom( newCarDto() ); assertThat( car.getId() ).isEqualTo( 9L ); assertThat( car.getManufacturer() ).isEqualTo( "Nissan" ); assertThat( car.getNumberOfSeats() ).isEqualTo( 5 ); assertThat( car.getLastModifiedBy() ).isEqualTo( "restApiUser" ); assertThat( car.getCreationDate() ).isNull(); } @ProcessorTest public void testForwardMappingShouldTakePrecedence() { Car2Dto dto = new Car2Dto(); dto.setMaker( "mazda" ); dto.setSeatCount( 5 ); Car2Entity entity = CarMapper2.MAPPER.mapFrom( dto ); assertThat( entity.getManufacturer() ).isEqualTo( "ford" ); assertThat( entity.getNumberOfSeats( ) ).isEqualTo( 0 ); Car2Entity entity2 = new Car2Entity(); entity2.setManufacturer( "mazda" ); entity2.setNumberOfSeats( 5 ); Car2Dto dto2 = CarMapper2.MAPPER.mapTo( entity2 ); assertThat( dto2.getMaker() ).isEqualTo( "mazda" ); assertThat( dto2.getSeatCount() ).isEqualTo( 5 ); } private CarEntity newCar() { CarEntity car = new CarEntity(); car.setId( 9L ); car.setCreatedBy( "admin" ); car.setCreationDate( new Date() ); car.setManufacturer( "Nissan" ); car.setNumberOfSeats( 5 ); return car; } private CarDto newCarDto() { CarDto carDto = new CarDto(); carDto.setDbId( 9L ); carDto.setMaker( "Nissan" ); carDto.setSeatCount( 5 ); return carDto; } }
CarMapperTest
java
apache__camel
tooling/camel-tooling-maven/src/test/java/org/apache/camel/tooling/maven/MavenGavTest.java
{ "start": 1001, "end": 2574 }
class ____ { @Test void parseCoreGav() { MavenGav gav = MavenGav.parseGav("camel:core", "3.16.0"); assertEquals("org.apache.camel", gav.getGroupId()); assertEquals("camel-core", gav.getArtifactId()); assertEquals("3.16.0", gav.getVersion()); } @Test void parseCamelCoreGav() { MavenGav gav = MavenGav.parseGav("camel:camel-core"); assertEquals("org.apache.camel", gav.getGroupId()); assertEquals("camel-core", gav.getArtifactId()); assertNull(gav.getVersion()); } @Test void parseOtherGav() { MavenGav gav = MavenGav.parseGav("mvn:org.junit:junit-api:99.99"); assertEquals("org.junit", gav.getGroupId()); assertEquals("junit-api", gav.getArtifactId()); assertEquals("99.99", gav.getVersion()); } @Test void parseTestScopedGav() { MavenGav gav = MavenGav.parseGav("mvn@test:org.junit:junit-api:99.99"); assertEquals("org.junit", gav.getGroupId()); assertEquals("junit-api", gav.getArtifactId()); assertEquals("99.99", gav.getVersion()); assertEquals("test", gav.getScope()); } @Test void parseAgentGav() { MavenGav gav = MavenGav.parseGav("agent:io.opentelemetry.javaagent:opentelemetry-javaagent:1.31.0"); assertEquals("io.opentelemetry.javaagent", gav.getGroupId()); assertEquals("opentelemetry-javaagent", gav.getArtifactId()); assertEquals("1.31.0", gav.getVersion()); assertEquals("agent", gav.getPackaging()); } }
MavenGavTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/graph/spi/AppliedGraph.java
{ "start": 335, "end": 562 }
interface ____ { /** * The applied graph */ @Nullable RootGraphImplementor<?> getGraph(); /** * The semantic (fetch/load) under which the graph should be applied */ @Nullable GraphSemantic getSemantic(); }
AppliedGraph
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/BoxTasksManagerEndpointConfigurationConfigurer.java
{ "start": 732, "end": 11981 }
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("AccessTokenCache", com.box.sdk.IAccessTokenCache.class); map.put("Action", com.box.sdk.BoxTask.Action.class); map.put("ApiName", org.apache.camel.component.box.internal.BoxApiName.class); map.put("AssignTo", com.box.sdk.BoxUser.class); map.put("AuthenticationType", java.lang.String.class); map.put("ClientId", java.lang.String.class); map.put("ClientSecret", java.lang.String.class); map.put("DueAt", java.util.Date.class); map.put("EncryptionAlgorithm", com.box.sdk.EncryptionAlgorithm.class); map.put("EnterpriseId", java.lang.String.class); map.put("FileId", java.lang.String.class); map.put("HttpParams", java.util.Map.class); map.put("Info", com.box.sdk.BoxTask.Info.class); map.put("MaxCacheEntries", int.class); map.put("Message", java.lang.String.class); map.put("MethodName", java.lang.String.class); map.put("PrivateKeyFile", java.lang.String.class); map.put("PrivateKeyPassword", java.lang.String.class); map.put("PublicKeyId", java.lang.String.class); map.put("SslContextParameters", org.apache.camel.support.jsse.SSLContextParameters.class); map.put("TaskAssignmentId", java.lang.String.class); map.put("TaskId", java.lang.String.class); map.put("UserId", java.lang.String.class); map.put("UserName", java.lang.String.class); map.put("UserPassword", 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.box.BoxTasksManagerEndpointConfiguration target = (org.apache.camel.component.box.BoxTasksManagerEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstokencache": case "accessTokenCache": target.setAccessTokenCache(property(camelContext, com.box.sdk.IAccessTokenCache.class, value)); return true; case "action": target.setAction(property(camelContext, com.box.sdk.BoxTask.Action.class, value)); return true; case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.box.internal.BoxApiName.class, value)); return true; case "assignto": case "assignTo": target.setAssignTo(property(camelContext, com.box.sdk.BoxUser.class, value)); return true; case "authenticationtype": case "authenticationType": target.setAuthenticationType(property(camelContext, java.lang.String.class, value)); return true; case "clientid": case "clientId": target.setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": target.setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "dueat": case "dueAt": target.setDueAt(property(camelContext, java.util.Date.class, value)); return true; case "encryptionalgorithm": case "encryptionAlgorithm": target.setEncryptionAlgorithm(property(camelContext, com.box.sdk.EncryptionAlgorithm.class, value)); return true; case "enterpriseid": case "enterpriseId": target.setEnterpriseId(property(camelContext, java.lang.String.class, value)); return true; case "fileid": case "fileId": target.setFileId(property(camelContext, java.lang.String.class, value)); return true; case "httpparams": case "httpParams": target.setHttpParams(property(camelContext, java.util.Map.class, value)); return true; case "info": target.setInfo(property(camelContext, com.box.sdk.BoxTask.Info.class, value)); return true; case "maxcacheentries": case "maxCacheEntries": target.setMaxCacheEntries(property(camelContext, int.class, value)); return true; case "message": target.setMessage(property(camelContext, java.lang.String.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "privatekeyfile": case "privateKeyFile": target.setPrivateKeyFile(property(camelContext, java.lang.String.class, value)); return true; case "privatekeypassword": case "privateKeyPassword": target.setPrivateKeyPassword(property(camelContext, java.lang.String.class, value)); return true; case "publickeyid": case "publicKeyId": target.setPublicKeyId(property(camelContext, java.lang.String.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": target.setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "taskassignmentid": case "taskAssignmentId": target.setTaskAssignmentId(property(camelContext, java.lang.String.class, value)); return true; case "taskid": case "taskId": target.setTaskId(property(camelContext, java.lang.String.class, value)); return true; case "userid": case "userId": target.setUserId(property(camelContext, java.lang.String.class, value)); return true; case "username": case "userName": target.setUserName(property(camelContext, java.lang.String.class, value)); return true; case "userpassword": case "userPassword": target.setUserPassword(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 "accesstokencache": case "accessTokenCache": return com.box.sdk.IAccessTokenCache.class; case "action": return com.box.sdk.BoxTask.Action.class; case "apiname": case "apiName": return org.apache.camel.component.box.internal.BoxApiName.class; case "assignto": case "assignTo": return com.box.sdk.BoxUser.class; case "authenticationtype": case "authenticationType": return java.lang.String.class; case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "dueat": case "dueAt": return java.util.Date.class; case "encryptionalgorithm": case "encryptionAlgorithm": return com.box.sdk.EncryptionAlgorithm.class; case "enterpriseid": case "enterpriseId": return java.lang.String.class; case "fileid": case "fileId": return java.lang.String.class; case "httpparams": case "httpParams": return java.util.Map.class; case "info": return com.box.sdk.BoxTask.Info.class; case "maxcacheentries": case "maxCacheEntries": return int.class; case "message": return java.lang.String.class; case "methodname": case "methodName": return java.lang.String.class; case "privatekeyfile": case "privateKeyFile": return java.lang.String.class; case "privatekeypassword": case "privateKeyPassword": return java.lang.String.class; case "publickeyid": case "publicKeyId": return java.lang.String.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "taskassignmentid": case "taskAssignmentId": return java.lang.String.class; case "taskid": case "taskId": return java.lang.String.class; case "userid": case "userId": return java.lang.String.class; case "username": case "userName": return java.lang.String.class; case "userpassword": case "userPassword": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.box.BoxTasksManagerEndpointConfiguration target = (org.apache.camel.component.box.BoxTasksManagerEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstokencache": case "accessTokenCache": return target.getAccessTokenCache(); case "action": return target.getAction(); case "apiname": case "apiName": return target.getApiName(); case "assignto": case "assignTo": return target.getAssignTo(); case "authenticationtype": case "authenticationType": return target.getAuthenticationType(); case "clientid": case "clientId": return target.getClientId(); case "clientsecret": case "clientSecret": return target.getClientSecret(); case "dueat": case "dueAt": return target.getDueAt(); case "encryptionalgorithm": case "encryptionAlgorithm": return target.getEncryptionAlgorithm(); case "enterpriseid": case "enterpriseId": return target.getEnterpriseId(); case "fileid": case "fileId": return target.getFileId(); case "httpparams": case "httpParams": return target.getHttpParams(); case "info": return target.getInfo(); case "maxcacheentries": case "maxCacheEntries": return target.getMaxCacheEntries(); case "message": return target.getMessage(); case "methodname": case "methodName": return target.getMethodName(); case "privatekeyfile": case "privateKeyFile": return target.getPrivateKeyFile(); case "privatekeypassword": case "privateKeyPassword": return target.getPrivateKeyPassword(); case "publickeyid": case "publicKeyId": return target.getPublicKeyId(); case "sslcontextparameters": case "sslContextParameters": return target.getSslContextParameters(); case "taskassignmentid": case "taskAssignmentId": return target.getTaskAssignmentId(); case "taskid": case "taskId": return target.getTaskId(); case "userid": case "userId": return target.getUserId(); case "username": case "userName": return target.getUserName(); case "userpassword": case "userPassword": return target.getUserPassword(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "httpparams": case "httpParams": return java.lang.Object.class; default: return null; } } }
BoxTasksManagerEndpointConfigurationConfigurer
java
redisson__redisson
redisson/src/main/java/org/redisson/api/listener/LocalCacheUpdateListener.java
{ "start": 839, "end": 1073 }
interface ____<K, V> extends ObjectListener { /** * Invoked on event of map entry udpate * * @param key key to update * @param value new value */ void onUpdate(K key, V value); }
LocalCacheUpdateListener
java
apache__hadoop
hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/security/authentication/client/AuthenticationException.java
{ "start": 723, "end": 1399 }
class ____ extends Exception { static final long serialVersionUID = 0; /** * Creates an {@link AuthenticationException}. * * @param cause original exception. */ public AuthenticationException(Throwable cause) { super(cause); } /** * Creates an {@link AuthenticationException}. * * @param msg exception message. */ public AuthenticationException(String msg) { super(msg); } /** * Creates an {@link AuthenticationException}. * * @param msg exception message. * @param cause original exception. */ public AuthenticationException(String msg, Throwable cause) { super(msg, cause); } }
AuthenticationException
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/SnapshotTestHelper.java
{ "start": 9718, "end": 18330 }
class ____ { static Log4jRecorder record(org.slf4j.Logger logger) { return new Log4jRecorder(toLog4j(logger), getLayout()); } static org.apache.log4j.Logger toLog4j(org.slf4j.Logger logger) { return LogManager.getLogger(logger.getName()); } static Layout getLayout() { final org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger(); Appender a = root.getAppender("stdout"); if (a == null) { a = root.getAppender("console"); } return a == null? new PatternLayout() : a.getLayout(); } private final StringWriter stringWriter = new StringWriter(); private final WriterAppender appender; private final org.apache.log4j.Logger logger; private Log4jRecorder(org.apache.log4j.Logger logger, Layout layout) { this.appender = new WriterAppender(layout, stringWriter); this.logger = logger; this.logger.addAppender(this.appender); } public String getRecorded() { return stringWriter.toString(); } public void stop() { logger.removeAppender(appender); } public void clear() { stringWriter.getBuffer().setLength(0); } } private SnapshotTestHelper() { // Cannot be instantinatied } public static Path getSnapshotRoot(Path snapshottedDir, String snapshotName) { return new Path(snapshottedDir, HdfsConstants.DOT_SNAPSHOT_DIR + "/" + snapshotName); } public static Path getSnapshotPath(Path snapshottedDir, String snapshotName, String fileLocalName) { return new Path(getSnapshotRoot(snapshottedDir, snapshotName), fileLocalName); } /** * Create snapshot for a dir using a given snapshot name * * @param hdfs DistributedFileSystem instance * @param snapshotRoot The dir to be snapshotted * @param snapshotName The name of the snapshot * @return The path of the snapshot root */ public static Path createSnapshot(DistributedFileSystem hdfs, Path snapshotRoot, String snapshotName) throws Exception { LOG.info("createSnapshot " + snapshotName + " for " + snapshotRoot); assertTrue(hdfs.exists(snapshotRoot)); hdfs.allowSnapshot(snapshotRoot); hdfs.createSnapshot(snapshotRoot, snapshotName); // set quota to a large value for testing counts hdfs.setQuota(snapshotRoot, Long.MAX_VALUE-1, Long.MAX_VALUE-1); return SnapshotTestHelper.getSnapshotRoot(snapshotRoot, snapshotName); } /** * Check the functionality of a snapshot. * * @param hdfs DistributedFileSystem instance * @param snapshotRoot The root of the snapshot * @param snapshottedDir The snapshotted directory */ public static void checkSnapshotCreation(DistributedFileSystem hdfs, Path snapshotRoot, Path snapshottedDir) throws Exception { // Currently we only check if the snapshot was created successfully assertTrue(hdfs.exists(snapshotRoot)); // Compare the snapshot with the current dir FileStatus[] currentFiles = hdfs.listStatus(snapshottedDir); FileStatus[] snapshotFiles = hdfs.listStatus(snapshotRoot); assertEquals(currentFiles.length, snapshotFiles.length, "snapshottedDir=" + snapshottedDir + ", snapshotRoot=" + snapshotRoot); } /** * Compare two dumped trees that are stored in two files. The following is an * example of the dumped tree: * * <pre> * information of root * +- the first child of root (e.g., /foo) * +- the first child of /foo * ... * \- the last child of /foo (e.g., /foo/bar) * +- the first child of /foo/bar * ... * snapshots of /foo * +- snapshot s_1 * ... * \- snapshot s_n * +- second child of root * ... * \- last child of root * * The following information is dumped for each inode: * localName (className@hashCode) parent permission group user * * Specific information for different types of INode: * {@link INodeDirectory}:childrenSize * {@link INodeFile}: fileSize, block list. Check {@link BlockInfo#toString()} * and {@link BlockUnderConstructionFeature#toString()} for detailed information. * </pre> * @see INode#dumpTreeRecursively() */ public static void compareDumpedTreeInFile(File file1, File file2, boolean compareQuota) throws IOException { try { compareDumpedTreeInFile(file1, file2, compareQuota, false); } catch(Throwable t) { LOG.info("FAILED compareDumpedTreeInFile(" + file1 + ", " + file2 + ")", t); compareDumpedTreeInFile(file1, file2, compareQuota, true); } } private static void compareDumpedTreeInFile(File file1, File file2, boolean compareQuota, boolean print) throws IOException { if (print) { printFile(file1); printFile(file2); } BufferedReader reader1 = new BufferedReader(new FileReader(file1)); BufferedReader reader2 = new BufferedReader(new FileReader(file2)); try { String line1 = ""; String line2 = ""; while ((line1 = reader1.readLine()) != null && (line2 = reader2.readLine()) != null) { if (print) { System.out.println(); System.out.println("1) " + line1); System.out.println("2) " + line2); } // skip the hashCode part of the object string during the comparison, // also ignore the difference between INodeFile/INodeFileWithSnapshot line1 = line1.replaceAll("INodeFileWithSnapshot", "INodeFile"); line2 = line2.replaceAll("INodeFileWithSnapshot", "INodeFile"); line1 = line1.replaceAll("@[\\dabcdef]+", ""); line2 = line2.replaceAll("@[\\dabcdef]+", ""); // skip the replica field of the last block of an // INodeFileUnderConstruction line1 = line1.replaceAll("replicas=\\[.*\\]", "replicas=[]"); line2 = line2.replaceAll("replicas=\\[.*\\]", "replicas=[]"); if (!compareQuota) { line1 = line1.replaceAll("Quota\\[.*\\]", "Quota[]"); line2 = line2.replaceAll("Quota\\[.*\\]", "Quota[]"); } // skip the specific fields of BlockUnderConstructionFeature when the // node is an INodeFileSnapshot or INodeFileUnderConstructionSnapshot if (line1.contains("(INodeFileSnapshot)") || line1.contains("(INodeFileUnderConstructionSnapshot)")) { line1 = line1.replaceAll( "\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}", ""); line2 = line2.replaceAll( "\\{blockUCState=\\w+, primaryNodeIndex=[-\\d]+, replicas=\\[\\]\\}", ""); } assertEquals(line1.trim(), line2.trim()); } assertNull(reader1.readLine()); assertNull(reader2.readLine()); } finally { reader1.close(); reader2.close(); } } static void printFile(File f) throws IOException { System.out.println(); System.out.println("File: " + f); BufferedReader in = new BufferedReader(new FileReader(f)); try { for(String line; (line = in.readLine()) != null; ) { System.out.println(line); } } finally { in.close(); } } public static void dumpTree2File(FSDirectory fsdir, File f) throws IOException{ final PrintWriter out = new PrintWriter(new FileWriter(f, false), true); fsdir.getINode("/").dumpTreeRecursively(out, new StringBuilder(), Snapshot.CURRENT_STATE_ID); out.close(); } /** * Generate the path for a snapshot file. * * @param snapshotRoot of format * {@literal <snapshottble_dir>/.snapshot/<snapshot_name>} * @param file path to a file * @return The path of the snapshot of the file assuming the file has a * snapshot under the snapshot root of format * {@literal <snapshottble_dir>/.snapshot/<snapshot_name>/<path_to_file_inside_snapshot>} * . Null if the file is not under the directory associated with the * snapshot root. */ static Path getSnapshotFile(Path snapshotRoot, Path file) { Path rootParent = snapshotRoot.getParent(); if (rootParent != null && rootParent.getName().equals(".snapshot")) { Path snapshotDir = rootParent.getParent(); if (file.toString().contains(snapshotDir.toString()) && !file.equals(snapshotDir)) { String fileName = file.toString().substring( snapshotDir.toString().length() + 1); Path snapshotFile = new Path(snapshotRoot, fileName); return snapshotFile; } } return null; } /** * A
Log4jRecorder
java
apache__spark
common/network-common/src/test/java/org/apache/spark/network/ssl/SSLFactorySuite.java
{ "start": 1062, "end": 3502 }
class ____ { @Test public void testBuildWithJKSAndPEMWithPasswords() throws Exception { SSLFactory factory = new SSLFactory.Builder() .openSslEnabled(true) .requestedProtocol("TLSv1.3") .keyStore(new File(SslSampleConfigs.keyStorePath), "password") .privateKey(new File(SslSampleConfigs.privateKeyPath)) .privateKeyPassword("password") .keyPassword("password") .certChain(new File(SslSampleConfigs.certChainPath)) .trustStore( new File(SslSampleConfigs.trustStorePath), "password", true, 10000 ) .build(); factory.createSSLEngine(true, ByteBufAllocator.DEFAULT); } @Test public void testBuildWithJKSAndPEMWithOnlyJKSPassword() throws Exception { SSLFactory factory = new SSLFactory.Builder() .openSslEnabled(true) .requestedProtocol("TLSv1.3") .keyStore(new File(SslSampleConfigs.keyStorePath), "password") .privateKey(new File(SslSampleConfigs.unencryptedPrivateKeyPath)) .keyPassword("password") .certChain(new File(SslSampleConfigs.unencryptedCertChainPath)) .trustStore( new File(SslSampleConfigs.trustStorePath), "password", true, 10000 ) .build(); factory.createSSLEngine(true, ByteBufAllocator.DEFAULT); } @Test public void testBuildWithJKSKeyStorePassword() throws Exception { // if key password is null, fall back to keystore password SSLFactory factory = new SSLFactory.Builder() .requestedProtocol("TLSv1.3") .keyStore(new File(SslSampleConfigs.keyStorePath), "password") .trustStore( new File(SslSampleConfigs.trustStorePath), "password", true, 10000 ) .build(); factory.createSSLEngine(true, ByteBufAllocator.DEFAULT); } @Test public void testKeyAndKeystorePasswordsAreDistinct() throws Exception { assertThrows(RuntimeException.class, () -> { // Set the wrong password, validate we fail SSLFactory factory = new SSLFactory.Builder() .requestedProtocol("TLSv1.3") .keyStore(new File(SslSampleConfigs.keyStorePath), "password") .keyPassword("wrong") .trustStore( new File(SslSampleConfigs.trustStorePath), "password", true, 10000 ) .build(); factory.createSSLEngine(true, ByteBufAllocator.DEFAULT); }); } }
SSLFactorySuite
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated-src/org/elasticsearch/xpack/esql/expression/function/scalar/nulls/CoalesceBooleanEvaluator.java
{ "start": 1219, "end": 7153 }
class ____ implements EvalOperator.ExpressionEvaluator permits CoalesceBooleanEvaluator.CoalesceBooleanEagerEvaluator, // CoalesceBooleanEvaluator.CoalesceBooleanLazyEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(CoalesceBooleanEvaluator.class); static ExpressionEvaluator.Factory toEvaluator(EvaluatorMapper.ToEvaluator toEvaluator, List<Expression> children) { List<ExpressionEvaluator.Factory> childEvaluators = children.stream().map(toEvaluator::apply).toList(); if (childEvaluators.stream().allMatch(ExpressionEvaluator.Factory::eagerEvalSafeInLazy)) { return new ExpressionEvaluator.Factory() { @Override public ExpressionEvaluator get(DriverContext context) { return new CoalesceBooleanEagerEvaluator( // comment to make spotless happy about line breaks context, childEvaluators.stream().map(x -> x.get(context)).toList() ); } @Override public String toString() { return "CoalesceBooleanEagerEvaluator[values=" + childEvaluators + ']'; } }; } return new ExpressionEvaluator.Factory() { @Override public ExpressionEvaluator get(DriverContext context) { return new CoalesceBooleanLazyEvaluator( // comment to make spotless happy about line breaks context, childEvaluators.stream().map(x -> x.get(context)).toList() ); } @Override public String toString() { return "CoalesceBooleanLazyEvaluator[values=" + childEvaluators + ']'; } }; } protected final DriverContext driverContext; protected final List<EvalOperator.ExpressionEvaluator> evaluators; protected CoalesceBooleanEvaluator(DriverContext driverContext, List<EvalOperator.ExpressionEvaluator> evaluators) { this.driverContext = driverContext; this.evaluators = evaluators; } @Override public final BooleanBlock eval(Page page) { return entireBlock(page); } /** * Evaluate COALESCE for an entire {@link Block} for as long as we can, then shift to * {@link #perPosition} evaluation. * <p> * Entire Block evaluation is the "normal" way to run the compute engine, * just calling {@link EvalOperator.ExpressionEvaluator#eval}. It's much faster so we try * that first. For each evaluator, we {@linkplain EvalOperator.ExpressionEvaluator#eval} and: * </p> * <ul> * <li>If the {@linkplain Block} doesn't have any nulls we return it. COALESCE done.</li> * <li>If the {@linkplain Block} is only nulls we skip it and try the next evaluator.</li> * <li>If this is the last evaluator we just return it. COALESCE done.</li> * <li> * Otherwise, the {@linkplain Block} has mixed nulls and non-nulls so we drop * into a per position evaluator. * </li> * </ul> */ private BooleanBlock entireBlock(Page page) { int lastFullBlockIdx = 0; while (true) { BooleanBlock lastFullBlock = (BooleanBlock) evaluators.get(lastFullBlockIdx++).eval(page); if (lastFullBlockIdx == evaluators.size() || lastFullBlock.asVector() != null) { return lastFullBlock; } if (lastFullBlock.areAllValuesNull()) { // Result is all nulls and isn't the last result so we don't need any of it. lastFullBlock.close(); continue; } // The result has some nulls and some non-nulls. return perPosition(page, lastFullBlock, lastFullBlockIdx); } } /** * Evaluate each position of the incoming {@link Page} for COALESCE * independently. Our attempt to evaluate entire blocks has yielded * a block that contains some nulls and some non-nulls and we have * to fill in the nulls with the results of calling the remaining * evaluators. * <p> * This <strong>must not</strong> return warnings caused by * evaluating positions for which a previous evaluator returned * non-null. These are positions that, at least from the perspective * of a compute engine user, don't <strong>have</strong> to be * evaluated. Put another way, this must function as though * {@code COALESCE} were per-position lazy. It can manage that * any way it likes. * </p> */ protected abstract BooleanBlock perPosition(Page page, BooleanBlock lastFullBlock, int firstToEvaluate); @Override public final String toString() { return getClass().getSimpleName() + "[values=" + evaluators + ']'; } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; for (ExpressionEvaluator e : evaluators) { baseRamBytesUsed += e.baseRamBytesUsed(); } return baseRamBytesUsed; } @Override public final void close() { Releasables.closeExpectNoException(() -> Releasables.close(evaluators)); } /** * Evaluates {@code COALESCE} eagerly per position if entire-block evaluation fails. * First we evaluate all remaining evaluators, and then we pluck the first non-null * value from each one. This is <strong>much</strong> faster than * {@link CoalesceBooleanLazyEvaluator} but will include spurious warnings if any of the * evaluators make them so we only use it for evaluators that are * {@link Factory#eagerEvalSafeInLazy safe} to evaluate eagerly * in a lazy environment. */ static final
CoalesceBooleanEvaluator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/testutil/runner/ModifiableURLClassLoader.java
{ "start": 715, "end": 3176 }
class ____ extends URLClassLoader { private static final String ORG_MAPSTRUCT_AP_TEST = "org.mapstruct.ap.test."; private static final FilteringParentClassLoader DEFAULT_PARENT_CLASS_LOADER = new FilteringParentClassLoader( ORG_MAPSTRUCT_AP_TEST ); static { tryRegisterAsParallelCapable(); } private final ConcurrentMap<URL, URL> addedURLs = new ConcurrentHashMap<>(); ModifiableURLClassLoader(ClassLoader parent) { super( new URL[] { }, parent ); } ModifiableURLClassLoader() { this( DEFAULT_PARENT_CLASS_LOADER ); } @Override protected void addURL(URL url) { if ( addedURLs.putIfAbsent( url, url ) == null ) { super.addURL( url ); } } ModifiableURLClassLoader withOriginsOf(Collection<Class<?>> classes) { for ( Class<?> c : classes ) { withOriginOf( c ); } return this; } ModifiableURLClassLoader withOriginOf(Class<?> clazz) { String classFileName = clazz.getName().replace( ".", "/" ) + ".class"; URL classResource = clazz.getClassLoader().getResource( classFileName ); String fullyQualifiedUrl = classResource.toExternalForm(); String basePath = fullyQualifiedUrl.substring( 0, fullyQualifiedUrl.length() - classFileName.length() ); return withURL( basePath ); } ModifiableURLClassLoader withPaths(Collection<String> baseUrls) { for ( String url : baseUrls ) { withPath( url ); } return this; } ModifiableURLClassLoader withURL(String baseUrl) { try { addURL( new URL( baseUrl ) ); } catch ( MalformedURLException e ) { throw new RuntimeException( e ); } return this; } ModifiableURLClassLoader withPath(String path) { try { addURL( new File( path ).toURI().toURL() ); } catch ( MalformedURLException e ) { throw new RuntimeException( e ); } return this; } private static void tryRegisterAsParallelCapable() { try { ClassLoader.class.getMethod( "registerAsParallelCapable" ).invoke( null ); } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { return; // ignore } } }
ModifiableURLClassLoader
java
apache__camel
components/camel-google/camel-google-calendar/src/test/java/org/apache/camel/component/google/calendar/AbstractGoogleCalendarTestSupport.java
{ "start": 1566, "end": 4946 }
class ____ extends CamelTestSupport { private static final String TEST_OPTIONS_PROPERTIES = "/test-options.properties"; private static Properties properties; private Calendar calendar; static { properties = loadProperties(); } private static Properties loadProperties() { // read GoogleCalendar component configuration from // TEST_OPTIONS_PROPERTIES return TestSupport.loadExternalPropertiesQuietly(AbstractGoogleCalendarTestSupport.class, TEST_OPTIONS_PROPERTIES); } // Used by JUnit to determine whether or not to run the integration tests @SuppressWarnings("unused") private static boolean hasCredentials() { loadProperties(); return !properties.getProperty("clientId", "").isEmpty() && !properties.getProperty("clientSecret", "").isEmpty() && !properties.getProperty("accessToken", "").isEmpty() || !properties.getProperty("serviceAccountKey", "").isEmpty(); } @BeforeEach public void createTestCalendar() { Calendar calendar = new Calendar(); SecureRandom rand = new SecureRandom(); calendar.setSummary("camel-calendar-" + rand.nextInt()); calendar.setTimeZone("America/St_Johns"); this.calendar = requestBody("google-calendar://calendars/insert?inBody=content", calendar); } @AfterEach public void deleteTestCalendar() { try { if (calendar != null) { requestBody("google-calendar://calendars/delete?inBody=calendarId", getCalendar().getId()); setCalendar(null); } } catch (Exception e) { } } @Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); Map<String, Object> options = getTestOptions(); final GoogleCalendarConfiguration configuration = new GoogleCalendarConfiguration(); PropertyBindingSupport.bindProperties(context, configuration, options); // add GoogleCalendarComponent to Camel context final GoogleCalendarComponent component = new GoogleCalendarComponent(context); component.setConfiguration(configuration); context.addComponent("google-calendar", component); return context; } private Map<String, Object> getTestOptions() { Map<String, Object> options = new HashMap<>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { options.put(entry.getKey().toString(), entry.getValue()); } return options; } @SuppressWarnings("unchecked") protected <T> T requestBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers) throws CamelExecutionException { return (T) template().requestBodyAndHeaders(endpointUri, body, headers); } @SuppressWarnings("unchecked") protected <T> T requestBody(String endpoint, Object body) throws CamelExecutionException { return (T) template().requestBody(endpoint, body); } public Calendar getCalendar() { if (calendar == null) { createTestCalendar(); } return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } }
AbstractGoogleCalendarTestSupport
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/Handle.java
{ "start": 4235, "end": 4556 }
class ____ owns the field or method designated by this * handle (see {@link Type#getInternalName()}). * @param name the name of the field or method designated by this handle. * @param descriptor the descriptor of the field or method designated by this handle. * @param isInterface whether the owner is an
that
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/rescaling/RescalingHandlers.java
{ "start": 2478, "end": 3801 }
class ____ extends TriggerHandler< RestfulGateway, EmptyRequestBody, RescalingTriggerMessageParameters> { public RescalingTriggerHandler( GatewayRetriever<? extends RestfulGateway> leaderRetriever, Duration timeout, Map<String, String> responseHeaders) { super(leaderRetriever, timeout, responseHeaders, RescalingTriggerHeaders.getInstance()); } @Override public CompletableFuture<TriggerResponse> handleRequest( @Nonnull final HandlerRequest<EmptyRequestBody> request, @Nonnull final RestfulGateway gateway) throws RestHandlerException { throw featureDisabledException(); } @Override protected CompletableFuture<Acknowledge> triggerOperation( HandlerRequest<EmptyRequestBody> request, RestfulGateway gateway) { throw new UnsupportedOperationException(); } @Override protected AsynchronousJobOperationKey createOperationKey( HandlerRequest<EmptyRequestBody> request) { throw new UnsupportedOperationException(); } } /** Handler which reports the status of the rescaling operation. */ public
RescalingTriggerHandler
java
apache__camel
components/camel-jira/src/test/java/org/apache/camel/component/jira/JiraTestConstants.java
{ "start": 852, "end": 1227 }
interface ____ { String KEY = "TST"; String TEST_JIRA_URL = "https://somerepo.atlassian.net"; String PROJECT = "TST"; String USERNAME = "someguy"; String PASSWORD = "my_password"; String JIRA_CREDENTIALS = TEST_JIRA_URL + "&username=" + USERNAME + "&password=" + PASSWORD; String WATCHED_COMPONENTS = "Priority,Status,Resolution"; }
JiraTestConstants
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issue1463/TestIssue1463.java
{ "start": 339, "end": 916 }
class ____ { private Person wenshao; @Before public void setUp() { wenshao = new Person("wenshao", 18); } @Test public void testIssue1463() { String str = doubleDeserialization(wenshao); try { wenshao = JSON.parseObject(str, Person.class); } catch (Throwable ex) { Assert.assertEquals(ex.getCause() instanceof NullPointerException, false); } } private String doubleDeserialization(Person person) { return JSON.toJSONString(JSON.toJSONString(person)); } }
TestIssue1463
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/jdbc/QuarkusDBv8Delegate.java
{ "start": 218, "end": 926 }
class ____ extends org.quartz.impl.jdbcjobstore.DB2v8Delegate { /** * See the javadoc in {@link QuarkusObjectInputStream#resolveClass(ObjectStreamClass)} and * {@link DBDelegateUtils#getObjectFromInput(InputStream)} * on why this is needed */ @Override protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException { Blob blobLocator = rs.getBlob(colName); if (blobLocator == null || blobLocator.length() == 0) { return null; } InputStream binaryInput = blobLocator.getBinaryStream(); return DBDelegateUtils.getObjectFromInput(binaryInput); } }
QuarkusDBv8Delegate
java
apache__camel
components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvDataFormatResourceFactoryTest.java
{ "start": 1194, "end": 2228 }
class ____ extends CamelSpringTestSupport { @Test void marshalTest() throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:marshaled"); mock.expectedMessageCount(1); template.sendBody("direct:marshal", getData()); mock.assertIsSatisfied(); String body = mock.getReceivedExchanges().get(0).getIn().getBody(String.class); String[] lines = body.split("\r\n"); assertEquals(2, lines.length); assertEquals("A1,B1,C1", lines[0].trim()); assertEquals("A2,B2,C2", lines[1].trim()); } private List<List<String>> getData() { return Arrays.asList( Arrays.asList("A1", "B1", "C1"), Arrays.asList("A2", "B2", "C2")); } @Override protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/dataformat/csv/CsvDataFormatResourceFactoryTest-context.xml"); } }
CsvDataFormatResourceFactoryTest
java
apache__camel
components/camel-stream/src/main/java/org/apache/camel/component/stream/FileWatcherStrategy.java
{ "start": 6207, "end": 8243 }
class ____ implements Runnable { private final WatchService watcher; private final Path folder; private volatile boolean running; private OnChangeEvent changeEvent; public WatchFileChangesTask(WatchService watcher, Path folder, OnChangeEvent changeEvent) { this.watcher = watcher; this.folder = folder; this.changeEvent = changeEvent; } public boolean isRunning() { return running; } @Override public void run() { LOG.debug("FileWatcherStrategy is starting watching folder: {}", folder); // allow to run while starting Camel while (isStarting() || isRunAllowed()) { running = true; WatchKey key; try { LOG.trace("FileWatcherStrategy is polling for file changes in directory: {}", folder); // wait for a key to be available key = watcher.poll(pollTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } if (key != null) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent<Path> we = (WatchEvent<Path>) event; Path path = we.context(); File file = folder.resolve(path).toFile(); LOG.trace("Modified/Created/Deleted file: {}", file); changeEvent.onChange(file); } // the key must be reset after processed boolean valid = key.reset(); if (!valid) { break; } } } running = false; LOG.info("FileWatcherStrategy is stopping watching folder: {}", folder); } } }
WatchFileChangesTask
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/dancing/Sudoku.java
{ "start": 5469, "end": 5804 }
class ____ implements ColumnName { RowConstraint(int num, int row) { this.num = num; this.row = row; } int num; int row; public String toString() { return num + " in row " + row; } } /** * A constraint that each number can appear just once in a square. */ static private
RowConstraint
java
apache__camel
core/camel-console/src/main/java/org/apache/camel/impl/console/PropertiesDevConsole.java
{ "start": 1415, "end": 4669 }
class ____ extends AbstractDevConsole { public PropertiesDevConsole() { super("camel", "properties", "Properties", "Displays the properties loaded by Camel"); } @Override protected String doCallText(Map<String, Object> options) { StringBuilder sb = new StringBuilder(); PropertiesComponent pc = getCamelContext().getPropertiesComponent(); String loc = String.join(", ", pc.getLocations()); sb.append(String.format("Properties loaded from locations: %s", loc)); sb.append("\n"); Properties p = pc.loadProperties(); OrderedLocationProperties olp = null; if (p instanceof OrderedLocationProperties) { olp = (OrderedLocationProperties) p; } for (var entry : p.entrySet()) { String k = entry.getKey().toString(); Object v = entry.getValue(); loc = olp != null ? locationSummary(olp, k) : null; if (SensitiveUtils.containsSensitive(k)) { sb.append(String.format(" %s %s = xxxxxx%n", loc, k)); } else { sb.append(String.format(" %s %s = %s%n", loc, k, v)); } } sb.append("\n"); return sb.toString(); } @Override protected JsonObject doCallJson(Map<String, Object> options) { JsonObject root = new JsonObject(); PropertiesComponent pc = getCamelContext().getPropertiesComponent(); root.put("locations", pc.getLocations()); JsonArray arr = new JsonArray(); Properties p = pc.loadProperties(); OrderedLocationProperties olp = null; if (p instanceof OrderedLocationProperties) { olp = (OrderedLocationProperties) p; } for (var entry : p.entrySet()) { String k = entry.getKey().toString(); Object v = entry.getValue(); String loc = olp != null ? olp.getLocation(k) : null; String originalValue = null; String defaultValue = null; String source = null; var m = pc.getResolvedValue(k); if (m.isPresent()) { originalValue = m.get().originalValue(); defaultValue = m.get().defaultValue(); source = m.get().source(); v = m.get().value(); } JsonObject jo = new JsonObject(); jo.put("key", k); jo.put("value", v); if (originalValue != null) { jo.put("originalValue", originalValue); } if (defaultValue != null) { jo.put("defaultValue", defaultValue); } if (source != null) { jo.put("source", source); } if (loc != null) { jo.put("location", loc); jo.put("internal", isInternal(loc)); } arr.add(jo); } if (!arr.isEmpty()) { root.put("properties", arr); } return root; } private static boolean isInternal(String loc) { if (loc == null) { return false; } return "initial".equals(loc) || "override".equals(loc); } }
PropertiesDevConsole
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/comment/CommentTest.java
{ "start": 966, "end": 1850 }
class ____ { private static final String TABLE_NAME = "TestEntity"; private static final String TABLE_COMMENT = "I am table"; @Test @JiraKey(value = "HHH-4369") public void testComments() { StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistry(); Metadata metadata = new MetadataSources(ssr).addAnnotatedClass(TestEntity.class).buildMetadata(); Table table = StreamSupport.stream(metadata.getDatabase().getNamespaces().spliterator(), false) .flatMap(namespace -> namespace.getTables().stream()).filter(t -> t.getName().equals(TABLE_NAME)) .findFirst().orElse(null); assertThat(table.getComment(), is(TABLE_COMMENT)); for (Column col : table.getColumns()) { assertThat(col.getComment(), is("I am " + col.getName())); } } @Entity(name = "Person") @jakarta.persistence.Table(name = TABLE_NAME) @Comment(TABLE_COMMENT) public static
CommentTest
java
spring-projects__spring-security
ldap/src/main/java/org/springframework/security/ldap/authentication/LdapEncoder.java
{ "start": 987, "end": 2976 }
class ____ { private static final String[] NAME_ESCAPE_TABLE = new String[96]; static { // all below 0x20 (control chars) for (char c = 0; c < ' '; c++) { NAME_ESCAPE_TABLE[c] = "\\" + toTwoCharHex(c); } NAME_ESCAPE_TABLE['#'] = "\\#"; NAME_ESCAPE_TABLE[','] = "\\,"; NAME_ESCAPE_TABLE[';'] = "\\;"; NAME_ESCAPE_TABLE['='] = "\\="; NAME_ESCAPE_TABLE['+'] = "\\+"; NAME_ESCAPE_TABLE['<'] = "\\<"; NAME_ESCAPE_TABLE['>'] = "\\>"; NAME_ESCAPE_TABLE['\"'] = "\\\""; NAME_ESCAPE_TABLE['\\'] = "\\\\"; } /** * All static methods - not to be instantiated. */ private LdapEncoder() { } static String toTwoCharHex(char c) { String raw = Integer.toHexString(c).toUpperCase(Locale.ENGLISH); return (raw.length() > 1) ? raw : "0" + raw; } /** * LDAP Encodes a value for use with a DN. Escapes for LDAP, not JNDI! <br/> * Escapes:<br/> * ' ' [space] - "\ " [if first or last] <br/> * '#' [hash] - "\#" <br/> * ',' [comma] - "\," <br/> * ';' [semicolon] - "\;" <br/> * '= [equals] - "\=" <br/> * '+' [plus] - "\+" <br/> * '&lt;' [less than] - "\&lt;" <br/> * '&gt;' [greater than] - "\&gt;" <br/> * '"' [double quote] - "\"" <br/> * '\' [backslash] - "\\" <br/> * @param value the value to escape. * @return The escaped value. */ static String nameEncode(String value) { if (value == null) { return null; } StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length(); int last = length - 1; for (int i = 0; i < length; i++) { char c = value.charAt(i); // space first or last if (c == ' ' && (i == 0 || i == last)) { encodedValue.append("\\ "); continue; } // check in table for escapes if (c < NAME_ESCAPE_TABLE.length) { String esc = NAME_ESCAPE_TABLE[c]; if (esc != null) { encodedValue.append(esc); continue; } } // default: add the char encodedValue.append(c); } return encodedValue.toString(); } }
LdapEncoder
java
netty__netty
transport/src/test/java/io/netty/channel/SingleThreadIoEventLoopTest.java
{ "start": 1219, "end": 1695 }
class ____ extends TestIoHandler { TestIoHandler2(ThreadAwareExecutor executor) { super(executor); } } IoEventLoopGroup group = new SingleThreadIoEventLoop(null, Executors.defaultThreadFactory(), TestIoHandler::new); assertTrue(group.isIoType(TestIoHandler.class)); assertFalse(group.isIoType(TestIoHandler2.class)); group.shutdownGracefully(); } static final
TestIoHandler2
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/index/fielddata/ShapeValues.java
{ "start": 8989, "end": 10982 }
class ____ { public double top; public double bottom; public double negLeft; public double negRight; public double posLeft; public double posRight; public BoundingBox() {} private void reset(Extent extent, CoordinateEncoder coordinateEncoder) { this.top = coordinateEncoder.decodeY(extent.top); this.bottom = coordinateEncoder.decodeY(extent.bottom); if (extent.negLeft == Integer.MAX_VALUE && extent.negRight == Integer.MIN_VALUE) { this.negLeft = Double.POSITIVE_INFINITY; this.negRight = Double.NEGATIVE_INFINITY; } else { this.negLeft = coordinateEncoder.decodeX(extent.negLeft); this.negRight = coordinateEncoder.decodeX(extent.negRight); } if (extent.posLeft == Integer.MAX_VALUE && extent.posRight == Integer.MIN_VALUE) { this.posLeft = Double.POSITIVE_INFINITY; this.posRight = Double.NEGATIVE_INFINITY; } else { this.posLeft = coordinateEncoder.decodeX(extent.posLeft); this.posRight = coordinateEncoder.decodeX(extent.posRight); } } /** * @return the minimum y-coordinate of the extent */ public double minY() { return bottom; } /** * @return the maximum y-coordinate of the extent */ public double maxY() { return top; } /** * @return the absolute minimum x-coordinate of the extent, whether it is positive or negative. */ public double minX() { return Math.min(negLeft, posLeft); } /** * @return the absolute maximum x-coordinate of the extent, whether it is positive or negative. */ public double maxX() { return Math.max(negRight, posRight); } } }
BoundingBox
java
google__dagger
javatests/dagger/internal/codegen/ModuleValidationTest.java
{ "start": 19016, "end": 19270 }
interface ____ {", " fun getInt(): Int", " fun getString(): String", "}"); CompilerTests.daggerCompiler(component, objectModule, classModule) .compile(subject -> subject.hasErrorCount(0)); } }
TestComponent
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/parser/CharTypes.java
{ "start": 728, "end": 4985 }
class ____ { private static final boolean[] hexFlags = new boolean[256]; static { for (char c = 0; c < hexFlags.length; ++c) { if (c >= 'A' && c <= 'F') { hexFlags[c] = true; } else if (c >= 'a' && c <= 'f') { hexFlags[c] = true; } else if (c >= '0' && c <= '9') { hexFlags[c] = true; } } } public static boolean isHex(char c) { return c < 256 && hexFlags[c]; } public static boolean isDigit(char c) { return c >= '0' && c <= '9'; } private static final boolean[] firstIdentifierFlags = new boolean[256]; private static final boolean[] UNDERSCORE_LETTERS = new boolean[256]; static { // the Latin letter decimal values range between 192('À') and 255('ÿ') but exclude 215('×') and 247('÷'). for (char c = 0; c < firstIdentifierFlags.length; ++c) { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= 'À' && c <= 'ÿ' && c != '×' && c != '÷')) { firstIdentifierFlags[c] = true; } } firstIdentifierFlags['`'] = true; firstIdentifierFlags['_'] = true; firstIdentifierFlags['$'] = true; for (char c = 'A'; c <= 'Z'; ++c) { UNDERSCORE_LETTERS[c] = true; } for (char c = 'a'; c <= 'z'; ++c) { UNDERSCORE_LETTERS[c] = true; } UNDERSCORE_LETTERS['_'] = true; } public static boolean letterOrUnderScore(char c) { return (c & ~0xFF) == 0 && UNDERSCORE_LETTERS[c & 0xFF]; } public static boolean isFirstIdentifierChar(char c) { if (c <= firstIdentifierFlags.length) { return firstIdentifierFlags[c]; } return c != ' ' && c != ','; } private static final String[] stringCache = new String[256]; private static final boolean[] identifierFlags = new boolean[256]; static { for (char c = 0; c < identifierFlags.length; ++c) { if (c >= 'A' && c <= 'Z') { identifierFlags[c] = true; } else if (c >= 'a' && c <= 'z') { identifierFlags[c] = true; } else if (c >= '0' && c <= '9') { identifierFlags[c] = true; } } // identifierFlags['`'] = true; identifierFlags['_'] = true; identifierFlags['$'] = true; identifierFlags['#'] = true; for (int i = 0; i < identifierFlags.length; i++) { if (identifierFlags[i]) { char ch = (char) i; stringCache[i] = Character.toString(ch); } } } public static boolean isIdentifierChar(char c) { if (c <= identifierFlags.length) { return identifierFlags[c]; } return c != ' ' && c != ',' && c != ')' && c != '('; } public static String valueOf(char ch) { if (ch < stringCache.length) { return stringCache[ch]; } return null; } private static final boolean[] whitespaceFlags = new boolean[256]; static { for (int i = 0; i <= 32; ++i) { whitespaceFlags[i] = true; } whitespaceFlags[EOI] = false; for (int i = 0x7F; i <= 0xA0; ++i) { whitespaceFlags[i] = true; } whitespaceFlags[160] = true; // 特别处理 // whitespaceFlags[223] = true; // 特别处理, odps // whitespaceFlags[229] = true; // 特别处理, odps // whitespaceFlags[231] = true; // 特别处理, odps ç } /** * @return false if {@link LayoutCharacters#EOI} */ public static boolean isWhitespace(char c) { return (c <= whitespaceFlags.length && whitespaceFlags[c]) // || c == ' '; // Chinese space } public static String trim(String value) { int len = value.length(); int st = 0; while ((st < len) && (isWhitespace(value.charAt(st)))) { st++; } while ((st < len) && isWhitespace(value.charAt(len - 1))) { len--; } return ((st > 0) || (len < value.length())) ? value.substring(st, len) : value; } }
CharTypes
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java
{ "start": 13977, "end": 14534 }
class ____ { @Order(Ordered.HIGHEST_PRECEDENCE) @Bean SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) { http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) .authorizeExchange((authorize) -> authorize.anyExchange().denyAll()); return http.build(); } @Bean SecurityWebFilterChain httpSecurity(ServerHttpSecurity http) { return http.build(); } } @Configuration @EnableWebFluxSecurity @EnableWebFlux @Import(ReactiveAuthenticationTestConfiguration.class) static
MultiSecurityHttpConfig
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/search/AggregateArgs.java
{ "start": 12541, "end": 12963 }
class ____ implements Clause { private final String expr; private final String alias; public Apply(String expr, String alias) { this.expr = notNullOrBlank(expr, expr); this.alias = notNullOrBlank(alias, "alias"); } @Override public List<String> toArgs() { return List.of("APPLY", expr, "AS", alias); } } public static
Apply
java
grpc__grpc-java
interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java
{ "start": 10960, "end": 11520 }
class ____<RespT> extends SimpleForwardingClientCallListener<RespT> { private ClientHeadersCapture(Listener<RespT> delegate) { super(delegate); } @Override public void onHeaders(Metadata headers) { super.onHeaders(headers); Metadata headersCopy = new Metadata(); headersCopy.merge(headers); clientResponseHeaders = headersCopy; } } private static void assertEqualsString(String expected, byte[] actual) { assertEquals(expected, new String(actual, Charset.forName("US-ASCII"))); } }
ClientHeadersCapture
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/dependencies/patches/Utils.java
{ "start": 2966, "end": 7662 }
class ____ from the JAR Manifest; set this to true when patching a signed JAR, * otherwise the patched classes will fail to load at runtime due to mismatched signatures. * @see <a href="https://docs.oracle.com/javase/tutorial/deployment/jar/intro.html">Understanding Signing and Verification</a> */ public static void patchJar(File inputFile, File outputFile, Collection<PatcherInfo> patchers, boolean unsignJar) { var classPatchers = patchers.stream().collect(Collectors.toMap(PatcherInfo::jarEntryName, Function.identity())); var mismatchedClasses = new ArrayList<MismatchInfo>(); try (JarFile jarFile = new JarFile(inputFile); JarOutputStream jos = new JarOutputStream(new FileOutputStream(outputFile))) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); // Add the entry to the new JAR file jos.putNextEntry(new JarEntry(entryName)); var classPatcher = classPatchers.remove(entryName); if (classPatcher != null) { byte[] classToPatch = jarFile.getInputStream(entry).readAllBytes(); var classSha256 = SHA_256.digest(classToPatch); if (classPatcher.matches(classSha256)) { ClassReader classReader = new ClassReader(classToPatch); ClassWriter classWriter = new ClassWriter(classReader, COMPUTE_MAXS | COMPUTE_FRAMES); classReader.accept(classPatcher.createVisitor(classWriter), 0); jos.write(classWriter.toByteArray()); } else { mismatchedClasses.add( new MismatchInfo( classPatcher.jarEntryName(), HexFormat.of().formatHex(classPatcher.classSha256()), HexFormat.of().formatHex(classSha256) ) ); } } else { try (InputStream is = jarFile.getInputStream(entry)) { if (unsignJar && entryName.equals("META-INF/MANIFEST.MF")) { var manifest = new Manifest(is); for (var manifestEntry : manifest.getEntries().entrySet()) { var nonSignatureAttributes = new Attributes(); for (var attribute : manifestEntry.getValue().entrySet()) { if (attribute.getKey().toString().endsWith("Digest") == false) { nonSignatureAttributes.put(attribute.getKey(), attribute.getValue()); } } manifestEntry.setValue(nonSignatureAttributes); } manifest.write(jos); } else if (unsignJar == false || entryName.matches("META-INF/.*\\.SF") == false) { // Read the entry's data and write it to the new JAR is.transferTo(jos); } } } jos.closeEntry(); } } catch (IOException ex) { throw new RuntimeException(ex); } if (mismatchedClasses.isEmpty() == false) { throw new IllegalArgumentException( String.format( Locale.ROOT, """ Error patching JAR [%s]: SHA256 digest mismatch (%s). This JAR was updated to a version that contains different \ classes, for which this patcher was not designed. Please check if the patcher still \ applies correctly, and update the SHA256 digest(s).""", inputFile.getName(), mismatchedClasses.stream().map(MismatchInfo::toString).collect(Collectors.joining()) ) ); } if (classPatchers.isEmpty() == false) { throw new IllegalArgumentException( String.format( Locale.ROOT, "error patching [%s]: the jar does not contain [%s]", inputFile.getName(), String.join(", ", classPatchers.keySet()) ) ); } } }
signatures
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/session/SqlSessionFactoryBuilder.java
{ "start": 1104, "end": 3133 }
class ____ { public SqlSessionFactory build(Reader reader) { return build(reader, null, null); } public SqlSessionFactory build(Reader reader, String environment) { return build(reader, environment, null); } public SqlSessionFactory build(Reader reader, Properties properties) { return build(reader, null, properties); } public SqlSessionFactory build(Reader reader, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { if (reader != null) { reader.close(); } } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } } public SqlSessionFactory build(InputStream inputStream) { return build(inputStream, null, null); } public SqlSessionFactory build(InputStream inputStream, String environment) { return build(inputStream, environment, null); } public SqlSessionFactory build(InputStream inputStream, Properties properties) { return build(inputStream, null, properties); } public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } } public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); } }
SqlSessionFactoryBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/idgenerator/SequenceGeneratorsTest.java
{ "start": 2720, "end": 3124 }
class ____ { Long id; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCEGENERATOR") @SequenceGenerators({ @SequenceGenerator( name = "SEQUENCEGENERATOR", allocationSize = 3, initialValue = 5, sequenceName = "SEQUENCE_GENERATOR") }) public Long getId() { return id; } public void setId(Long id) { this.id = id; } } }
TestEntity
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-tos/src/test/java/org/apache/hadoop/fs/tosfs/object/tos/TestDelegationClientBuilder.java
{ "start": 3569, "end": 21428 }
class ____ { private static final String TEST_KEY = UUIDUtils.random(); private static final String TEST_DATA = "1234567890"; private static String envAccessKey; private static String envSecretKey; private static String envEndpoint; // Maximum retry times of the tos http client. public static final String MAX_RETRY_COUNT_KEY = "fs.tos.http.maxRetryCount"; @BeforeAll public static void before() { assumeTrue(TestEnv.checkTestEnabled()); envAccessKey = ParseUtils.envAsString(TOS.ENV_TOS_ACCESS_KEY_ID, false); envSecretKey = ParseUtils.envAsString(TOS.ENV_TOS_SECRET_ACCESS_KEY, false); envEndpoint = ParseUtils.envAsString(TOS.ENV_TOS_ENDPOINT, false); } @BeforeEach public void setUp() { TOSV2 tosSdkClientV2 = new TOSV2ClientBuilder().build(TestUtility.region(), TestUtility.endpoint(), new StaticCredentials(envAccessKey, envSecretKey)); try (ByteArrayInputStream stream = new ByteArrayInputStream(TEST_DATA.getBytes())) { PutObjectInput putObjectInput = new PutObjectInput().setBucket(TestUtility.bucket()).setKey(TEST_KEY).setContent(stream); tosSdkClientV2.putObject(putObjectInput); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testHeadApiRetry() throws IOException { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), "https://test.tos-cn-beijing.ivolces.com"); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, false); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key("test"), "ACCESS_KEY"); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key("test"), "SECRET_KEY"); DelegationClient tosV2 = new DelegationClientBuilder().bucket("test").conf(conf).build(); TOSV2 mockClient = mock(TOSV2.class); tosV2.setClient(mockClient); tosV2.setMaxRetryTimes(5); HeadObjectV2Input input = HeadObjectV2Input.builder().bucket("test").build(); when(tosV2.headObject(input)).thenThrow( new TosServerException(HttpStatus.INTERNAL_SERVER_ERROR), new TosServerException(HttpStatus.TOO_MANY_REQUESTS), new TosClientException("fake toe", new IOException("fake ioe")), new TosException(new SocketException("fake msg")), new TosException(new UnknownHostException("fake msg")), new TosException(new SSLException("fake msg")), new TosException(new InterruptedException("fake msg")), new TosException(new InterruptedException("fake msg"))) .thenReturn(new HeadObjectV2Output()); RuntimeException exception = assertThrows(RuntimeException.class, () -> tosV2.headObject(input)); assertTrue(exception instanceof TosException); assertTrue(exception.getCause() instanceof UnknownHostException); verify(tosV2.client(), times(5)).headObject(input); HeadObjectV2Input inputOneTime = HeadObjectV2Input.builder().bucket("inputOneTime").build(); HeadObjectV2Output output = new HeadObjectV2Output(); when(tosV2.headObject(inputOneTime)).thenReturn(output); HeadObjectV2Output headObject = tosV2.headObject(inputOneTime); assertEquals(headObject, output); verify(tosV2.client(), times(1)).headObject(inputOneTime); tosV2.close(); DelegationClient newClient = new DelegationClientBuilder().bucket("test").conf(conf).build(); mockClient = mock(TOSV2.class); newClient.setClient(mockClient); newClient.setMaxRetryTimes(5); when(newClient.headObject(input)).thenThrow( new TosClientException("fake toe", new EOFException("fake eof")), new TosServerException(HttpStatus.INTERNAL_SERVER_ERROR), new TosServerException(HttpStatus.TOO_MANY_REQUESTS)).thenReturn(new HeadObjectV2Output()); exception = assertThrows(RuntimeException.class, () -> newClient.headObject(input)); assertTrue(exception instanceof TosClientException); assertTrue(exception.getCause() instanceof EOFException); verify(newClient.client(), times(1)).headObject(input); newClient.close(); } @Test public void testEnableCrcCheck(TestInfo testInfo, TestReporter testReporter) throws IOException { String bucket = testInfo.getTestMethod().map(method -> method.getName()).orElse("Unknown"); Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), "https://test.tos-cn-beijing.ivolces.com"); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, true); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(bucket), "ACCESS_KEY"); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(bucket), "SECRET_KEY"); DelegationClient tosV2 = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); assertTrue(tosV2.config().isEnableCrc()); conf.setBoolean(TosKeys.FS_TOS_CRC_CHECK_ENABLED, false); tosV2 = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); assertFalse(tosV2.config().isEnableCrc()); tosV2.close(); } @Test public void testClientCache(TestInfo testInfo, TestReporter testReporter) throws IOException { String bucket = testInfo.getTestMethod().map(method -> method.getName()).orElse("Unknown"); Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), "https://test.tos-cn-beijing.ivolces.com"); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, false); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(bucket), "ACCESS_KEY_A"); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(bucket), "SECRET_KEY_A"); DelegationClient tosV2 = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); DelegationClient tosV2Cached = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); assertEquals(tosV2Cached, tosV2, "client must be load in cache"); assertEquals("ACCESS_KEY_A", tosV2.usedCredential().getAccessKeyId()); tosV2Cached.close(); String newBucket = "new-test-bucket"; conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(newBucket), "ACCESS_KEY_B"); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(newBucket), "SECRET_KEY_B"); DelegationClient changeBucketClient = new DelegationClientBuilder().bucket(newBucket).conf(conf).build(); assertNotEquals(changeBucketClient, tosV2, "client should be created entirely new"); assertEquals("ACCESS_KEY_B", changeBucketClient.usedCredential().getAccessKeyId()); changeBucketClient.close(); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, true); // disable cache: true DelegationClient tosV2NotCached = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); assertNotEquals(tosV2NotCached, tosV2, "client should be created entirely new"); assertEquals("ACCESS_KEY_A", tosV2NotCached.usedCredential().getAccessKeyId()); tosV2NotCached.close(); tosV2.close(); } @Test public void testOverwriteHttpConfig() throws IOException { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), "https://tos-cn-beijing.ivolces.com"); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key("test"), "ACCESS_KEY"); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key("test"), "SECRET_KEY"); conf.setInt(TosKeys.FS_TOS_HTTP_MAX_CONNECTIONS, 24); conf.setInt(MAX_RETRY_COUNT_KEY, 24); conf.setInt(TosKeys.FS_TOS_REQUEST_MAX_RETRY_TIMES, 24); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, true); DelegationClient tosV2 = new DelegationClientBuilder().bucket("test").conf(conf).build(); assertEquals("ACCESS_KEY", tosV2.usedCredential().getAccessKeyId()); assertEquals(24, tosV2.config().getTransportConfig().getMaxConnections(), "http max connection overwrite to 24 from 1024, must be 24"); assertEquals(DelegationClientBuilder.DISABLE_TOS_RETRY_VALUE, tosV2.config().getTransportConfig().getMaxRetryCount(), "tos maxRetryCount disabled, must be -1"); assertEquals(24, tosV2.maxRetryTimes(), "maxRetryTimes must be 24"); assertEquals("https://tos-cn-beijing.ivolces.com", tosV2.config().getEndpoint(), "endpoint must be equals to https://tos-cn-beijing.ivolces.com"); tosV2.close(); } @Test public void testDynamicRefreshAkSk() throws IOException { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), envEndpoint); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(TestUtility.bucket()), envAccessKey); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(TestUtility.bucket()), envSecretKey); conf.setInt(TosKeys.FS_TOS_HTTP_MAX_CONNECTIONS, 24); conf.setInt(MAX_RETRY_COUNT_KEY, 24); TOSV2 tosSdkClientV2 = new TOSV2ClientBuilder().build(TestUtility.region(), TestUtility.endpoint(), new StaticCredentials("a", "b")); DelegationClient delegationClientV2 = new DelegationClientBuilder().bucket(TestUtility.bucket()).conf(conf).build(); ListObjectsV2Input inputV2 = ListObjectsV2Input.builder().bucket(TestUtility.bucket()).prefix(TEST_KEY).marker("") .maxKeys(10).build(); assertThrows(TosServerException.class, () -> tosSdkClientV2.listObjects(inputV2)); tosSdkClientV2.changeCredentials(new StaticCredentials(envAccessKey, envSecretKey)); ListObjectsV2Output tosSdkOutput = tosSdkClientV2.listObjects(inputV2); ListObjectsV2Output delegateOutput = delegationClientV2.listObjects(inputV2); int nativeContentSize = tosSdkOutput.getContents() == null ? -1 : tosSdkOutput.getContents().size(); int delegateContentSize = delegateOutput.getContents() == null ? -1 : delegateOutput.getContents().size(); assertEquals(nativeContentSize, delegateContentSize, "delegation client must same as native client"); assertEquals(envAccessKey, delegationClientV2.usedCredential().getAccessKeyId()); delegationClientV2.close(); } @Test public void testCreateClientWithEnvironmentCredentials() throws IOException { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), envEndpoint); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, EnvironmentCredentialsProvider.NAME); DelegationClient tosV2 = new DelegationClientBuilder().bucket(TestUtility.bucket()).conf(conf).build(); Credential cred = tosV2.usedCredential(); String assertMsg = String.format("expect %s, but got %s", envAccessKey, cred.getAccessKeyId()); assertEquals(cred.getAccessKeyId(), envAccessKey, assertMsg); assertMsg = String.format("expect %s, but got %s", envSecretKey, cred.getAccessKeySecret()); assertEquals(cred.getAccessKeySecret(), envSecretKey, assertMsg); tosV2.close(); } @Test public void testCreateClientWithSimpleCredentials() throws IOException { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), envEndpoint); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(TestUtility.bucket()), envAccessKey); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(TestUtility.bucket()), envSecretKey); conf.setInt(TosKeys.FS_TOS_HTTP_MAX_CONNECTIONS, 24); conf.setInt(MAX_RETRY_COUNT_KEY, 24); ListObjectsV2Input input = ListObjectsV2Input.builder().bucket(TestUtility.bucket()).prefix(TEST_KEY).marker("") .maxKeys(10).build(); TOSV2 v2 = new TOSV2ClientBuilder().build(TestUtility.region(), TestUtility.endpoint(), new StaticCredentials(envAccessKey, envSecretKey)); ListObjectsV2Output outputV2 = v2.listObjects(input); DelegationClient tosV2 = new DelegationClientBuilder().bucket(TestUtility.bucket()).conf(conf).build(); ListObjectsV2Output output = tosV2.listObjects(input); assertEquals(outputV2.getContents().size(), output.getContents().size(), "delegation client must be same as native client"); tosV2.close(); } @Test public void testCachedConcurrently(TestInfo testInfo, TestReporter testReporter) { String bucketName = testInfo.getTestMethod().map(method -> method.getName()).orElse("Unknown"); Function<String, Configuration> commonConf = bucket -> { Configuration conf = new Configuration(); conf.set(ConfKeys.FS_OBJECT_STORAGE_ENDPOINT.key(TOS_SCHEME), envEndpoint); conf.set(TosKeys.FS_TOS_CREDENTIALS_PROVIDER, SimpleCredentialsProvider.NAME); conf.set(TosKeys.FS_TOS_BUCKET_ACCESS_KEY_ID.key(bucket), envAccessKey); conf.set(TosKeys.FS_TOS_BUCKET_SECRET_ACCESS_KEY.key(bucket), envSecretKey); return conf; }; // enable cache Function<String, Configuration> enableCachedConf = bucket -> { Configuration conf = commonConf.apply(bucket); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, false); return conf; }; ExecutorService es = ThreadPools.newWorkerPool("testCachedConcurrently", 32); int bucketCount = 5; int taskCount = 10000; AtomicInteger success = new AtomicInteger(0); AtomicInteger failure = new AtomicInteger(0); Tasks.foreach(IntStream.range(0, taskCount).boxed().map(i -> bucketName + (i % bucketCount))) .executeWith(es).run(bucket -> { try { Configuration conf = enableCachedConf.apply(bucket); DelegationClient client = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); client.close(); success.incrementAndGet(); } catch (Exception e) { failure.incrementAndGet(); } }); assertEquals(bucketCount, DelegationClientBuilder.CACHE.size()); assertEquals(taskCount, success.get()); assertEquals(0, failure.get()); // clear cache DelegationClientBuilder.CACHE.clear(); // disable cache Function<String, Configuration> disableCachedConf = bucket -> { Configuration conf = commonConf.apply(bucket); conf.setBoolean(TosKeys.FS_TOS_DISABLE_CLIENT_CACHE, true); return conf; }; success.set(0); failure.set(0); Tasks.foreach(IntStream.range(0, taskCount).boxed().map(i -> bucketName + (i % bucketCount))) .executeWith(es).run(bucket -> { try { Configuration conf = disableCachedConf.apply(bucket); DelegationClient client = new DelegationClientBuilder().bucket(bucket).conf(conf).build(); client.close(); success.incrementAndGet(); } catch (Exception e) { failure.incrementAndGet(); } }); assertTrue(DelegationClientBuilder.CACHE.isEmpty()); assertEquals(taskCount, success.get()); assertEquals(0, failure.get()); es.shutdown(); } @AfterEach public void deleteAllTestData() throws IOException { TOSV2 tosSdkClientV2 = new TOSV2ClientBuilder().build(TestUtility.region(), TestUtility.endpoint(), new StaticCredentials(envAccessKey, envSecretKey)); tosSdkClientV2.deleteObject( DeleteObjectInput.builder().bucket(TestUtility.bucket()).key(TEST_KEY).build()); tosSdkClientV2.close(); DelegationClientBuilder.CACHE.clear(); } @Test public void testRetryableException() { assertTrue(retryableException(new TosServerException(500))); assertTrue(retryableException(new TosServerException(501))); assertTrue(retryableException(new TosServerException(429))); assertFalse(retryableException(new TosServerException(404))); assertTrue(retryableException(new TosException(new SocketException()))); assertTrue(retryableException(new TosException(new UnknownHostException()))); assertTrue(retryableException(new TosException(new SSLException("fake ssl")))); assertTrue(retryableException(new TosException(new SocketTimeoutException()))); assertTrue(retryableException(new TosException(new InterruptedException()))); assertTrue(retryableException(new TosClientException("fake ioe", new IOException()))); assertFalse(retryableException(new TosClientException("fake eof", new EOFException()))); assertTrue(retryableException(new TosServerException(409))); assertTrue( retryableException(new TosServerException(409).setEc(TOSErrorCodes.PATH_LOCK_CONFLICT))); assertFalse( retryableException(new TosServerException(409).setEc(TOSErrorCodes.DELETE_NON_EMPTY_DIR))); assertFalse( retryableException(new TosServerException(409).setEc(TOSErrorCodes.LOCATED_UNDER_A_FILE))); assertFalse(retryableException( new TosServerException(409).setEc(TOSErrorCodes.COPY_BETWEEN_DIR_AND_FILE))); assertFalse(retryableException( new TosServerException(409).setEc(TOSErrorCodes.RENAME_TO_AN_EXISTED_DIR))); assertFalse( retryableException(new TosServerException(409).setEc(TOSErrorCodes.RENAME_TO_SUB_DIR))); assertFalse(retryableException( new TosServerException(409).setEc(TOSErrorCodes.RENAME_BETWEEN_DIR_AND_FILE))); } private boolean retryableException(TosException e) { return isRetryableException(e, Arrays.asList(TOSErrorCodes.FAST_FAILURE_CONFLICT_ERROR_CODES.split(","))); } }
TestDelegationClientBuilder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/search/function/ScoreFunction.java
{ "start": 2019, "end": 2414 }
class ____ override hashCode in the same * way that we force them to override equals. This also prevents false positives in CheckStyle's EqualsHashCode check. */ return Objects.hash(scoreCombiner, doHashCode()); } protected abstract int doHashCode(); protected ScoreFunction rewrite(IndexSearcher searcher) throws IOException { return this; } }
to
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmbEndpointBuilderFactory.java
{ "start": 121398, "end": 138445 }
interface ____ extends EndpointProducerBuilder { default SmbEndpointProducerBuilder basic() { return (SmbEndpointProducerBuilder) this; } /** * Used to specify if a null body is allowed during file writing. If set * to true then an empty file will be created, when set to false, and * attempting to send a null body to the file component, a * GenericFileWriteException of 'Cannot write null body to file.' will * be thrown. If the fileExist option is set to 'Override', then the * file will be truncated, and if set to append the file will remain * unchanged. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param allowNullBody the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder allowNullBody(boolean allowNullBody) { doSetProperty("allowNullBody", allowNullBody); return this; } /** * Used to specify if a null body is allowed during file writing. If set * to true then an empty file will be created, when set to false, and * attempting to send a null body to the file component, a * GenericFileWriteException of 'Cannot write null body to file.' will * be thrown. If the fileExist option is set to 'Override', then the * file will be truncated, and if set to append the file will remain * unchanged. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param allowNullBody the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder allowNullBody(String allowNullBody) { doSetProperty("allowNullBody", allowNullBody); return this; } /** * Whether or not to disconnect from remote SMB share right after a * Batch upload is complete. disconnectOnBatchComplete will only * disconnect the current connection to the SMB share. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param disconnectOnBatchComplete the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder disconnectOnBatchComplete(boolean disconnectOnBatchComplete) { doSetProperty("disconnectOnBatchComplete", disconnectOnBatchComplete); return this; } /** * Whether or not to disconnect from remote SMB share right after a * Batch upload is complete. disconnectOnBatchComplete will only * disconnect the current connection to the SMB share. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param disconnectOnBatchComplete the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder disconnectOnBatchComplete(String disconnectOnBatchComplete) { doSetProperty("disconnectOnBatchComplete", disconnectOnBatchComplete); return this; } /** * Whether or not to eagerly delete any existing target file. This * option only applies when you use fileExists=Override and the * tempFileName option as well. You can use this to disable (set it to * false) deleting the target file before the temp file is written. For * example you may write big files and want the target file to exists * during the temp file is being written. This ensure the target file is * only deleted until the very last moment, just before the temp file is * being renamed to the target filename. This option is also used to * control whether to delete any existing files when fileExist=Move is * enabled, and an existing file exists. If this option * copyAndDeleteOnRenameFails false, then an exception will be thrown if * an existing file existed, if its true, then the existing file is * deleted before the move operation. * * The option is a: <code>boolean</code> type. * * Default: true * Group: producer (advanced) * * @param eagerDeleteTargetFile the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder eagerDeleteTargetFile(boolean eagerDeleteTargetFile) { doSetProperty("eagerDeleteTargetFile", eagerDeleteTargetFile); return this; } /** * Whether or not to eagerly delete any existing target file. This * option only applies when you use fileExists=Override and the * tempFileName option as well. You can use this to disable (set it to * false) deleting the target file before the temp file is written. For * example you may write big files and want the target file to exists * during the temp file is being written. This ensure the target file is * only deleted until the very last moment, just before the temp file is * being renamed to the target filename. This option is also used to * control whether to delete any existing files when fileExist=Move is * enabled, and an existing file exists. If this option * copyAndDeleteOnRenameFails false, then an exception will be thrown if * an existing file existed, if its true, then the existing file is * deleted before the move operation. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: producer (advanced) * * @param eagerDeleteTargetFile the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder eagerDeleteTargetFile(String eagerDeleteTargetFile) { doSetProperty("eagerDeleteTargetFile", eagerDeleteTargetFile); return this; } /** * Will keep the last modified timestamp from the source file (if any). * Will use the FileConstants.FILE_LAST_MODIFIED header to located the * timestamp. This header can contain either a java.util.Date or long * with the timestamp. If the timestamp exists and the option is enabled * it will set this timestamp on the written file. Note: This option * only applies to the file producer. You cannot use this option with * any of the ftp producers. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param keepLastModified the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder keepLastModified(boolean keepLastModified) { doSetProperty("keepLastModified", keepLastModified); return this; } /** * Will keep the last modified timestamp from the source file (if any). * Will use the FileConstants.FILE_LAST_MODIFIED header to located the * timestamp. This header can contain either a java.util.Date or long * with the timestamp. If the timestamp exists and the option is enabled * it will set this timestamp on the written file. Note: This option * only applies to the file producer. You cannot use this option with * any of the ftp producers. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param keepLastModified the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder keepLastModified(String keepLastModified) { doSetProperty("keepLastModified", keepLastModified); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Strategy (Custom Strategy) used to move file with special naming * token to use when fileExist=Move is configured. By default, there is * an implementation used if no custom strategy is provided. * * The option is a: * <code>org.apache.camel.component.file.strategy.FileMoveExistingStrategy</code> type. * * Group: producer (advanced) * * @param moveExistingFileStrategy the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder moveExistingFileStrategy(org.apache.camel.component.file.strategy.FileMoveExistingStrategy moveExistingFileStrategy) { doSetProperty("moveExistingFileStrategy", moveExistingFileStrategy); return this; } /** * Strategy (Custom Strategy) used to move file with special naming * token to use when fileExist=Move is configured. By default, there is * an implementation used if no custom strategy is provided. * * The option will be converted to a * <code>org.apache.camel.component.file.strategy.FileMoveExistingStrategy</code> type. * * Group: producer (advanced) * * @param moveExistingFileStrategy the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder moveExistingFileStrategy(String moveExistingFileStrategy) { doSetProperty("moveExistingFileStrategy", moveExistingFileStrategy); return this; } /** * Automatically create missing directories in the file's pathname. For * the file consumer, that means creating the starting directory. For * the file producer, it means the directory the files should be written * to. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param autoCreate the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder autoCreate(boolean autoCreate) { doSetProperty("autoCreate", autoCreate); return this; } /** * Automatically create missing directories in the file's pathname. For * the file consumer, that means creating the starting directory. For * the file producer, it means the directory the files should be written * to. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param autoCreate the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder autoCreate(String autoCreate) { doSetProperty("autoCreate", autoCreate); return this; } /** * Maximum number of messages to keep in memory available for browsing. * Use 0 for unlimited. * * The option is a: <code>int</code> type. * * Default: 100 * Group: advanced * * @param browseLimit the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder browseLimit(int browseLimit) { doSetProperty("browseLimit", browseLimit); return this; } /** * Maximum number of messages to keep in memory available for browsing. * Use 0 for unlimited. * * The option will be converted to a <code>int</code> type. * * Default: 100 * Group: advanced * * @param browseLimit the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder browseLimit(String browseLimit) { doSetProperty("browseLimit", browseLimit); return this; } /** * Buffer size in bytes used for writing files (or in case of FTP for * downloading and uploading files). * * The option is a: <code>int</code> type. * * Default: 131072 * Group: advanced * * @param bufferSize the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder bufferSize(int bufferSize) { doSetProperty("bufferSize", bufferSize); return this; } /** * Buffer size in bytes used for writing files (or in case of FTP for * downloading and uploading files). * * The option will be converted to a <code>int</code> type. * * Default: 131072 * Group: advanced * * @param bufferSize the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder bufferSize(String bufferSize) { doSetProperty("bufferSize", bufferSize); return this; } /** * An optional SMB client configuration, can be used to configure client * specific configurations, like timeouts. * * The option is a: <code>com.hierynomus.smbj.SmbConfig</code> type. * * Group: advanced * * @param smbConfig the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder smbConfig(com.hierynomus.smbj.SmbConfig smbConfig) { doSetProperty("smbConfig", smbConfig); return this; } /** * An optional SMB client configuration, can be used to configure client * specific configurations, like timeouts. * * The option will be converted to a * <code>com.hierynomus.smbj.SmbConfig</code> type. * * Group: advanced * * @param smbConfig the value to set * @return the dsl builder */ default AdvancedSmbEndpointProducerBuilder smbConfig(String smbConfig) { doSetProperty("smbConfig", smbConfig); return this; } } /** * Builder for endpoint for the SMB component. */ public
AdvancedSmbEndpointProducerBuilder
java
apache__camel
components/camel-aws/camel-aws2-sns/src/main/java/org/apache/camel/component/aws2/sns/Sns2Configuration.java
{ "start": 1172, "end": 14923 }
class ____ implements Cloneable { private String topicArn; // Common properties private String topicName; @UriParam(label = "advanced") @Metadata(autowired = true) private SnsClient amazonSNSClient; @UriParam(label = "security", secret = true) private String accessKey; @UriParam(label = "security", secret = true) private String secretKey; @UriParam(label = "security", secret = true) private String sessionToken; @UriParam(label = "proxy", enums = "HTTP,HTTPS", defaultValue = "HTTPS") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam(label = "proxy") private String proxyHost; @UriParam(label = "proxy") private Integer proxyPort; @UriParam private String queueArn; @UriParam private boolean subscribeSNStoSQS; @UriParam private String kmsMasterKeyId; @UriParam private boolean serverSideEncryptionEnabled; @UriParam private boolean autoCreateTopic; @UriParam private boolean overrideEndpoint; @UriParam private String uriEndpointOverride; // Producer-only properties @UriParam private String subject; @UriParam @Metadata(supportFileReference = true) private String policy; @UriParam private String messageStructure; @UriParam(enums = "ap-south-2,ap-south-1,eu-south-1,eu-south-2,us-gov-east-1,me-central-1,il-central-1,ca-central-1,eu-central-1,us-iso-west-1,eu-central-2,eu-isoe-west-1,us-west-1,us-west-2,af-south-1,eu-north-1,eu-west-3,eu-west-2,eu-west-1,ap-northeast-3,ap-northeast-2,ap-northeast-1,me-south-1,sa-east-1,ap-east-1,cn-north-1,ca-west-1,us-gov-west-1,ap-southeast-1,ap-southeast-2,us-iso-east-1,ap-southeast-3,ap-southeast-4,us-east-1,us-east-2,cn-northwest-1,us-isob-east-1,aws-global,aws-cn-global,aws-us-gov-global,aws-iso-global,aws-iso-b-global") private String region; @UriParam(label = "security") private boolean trustAllCertificates; @UriParam(label = "security") private boolean useDefaultCredentialsProvider; @UriParam(label = "security") private boolean useProfileCredentialsProvider; @UriParam(label = "security") private boolean useSessionCredentials; @UriParam(label = "security") private String profileCredentialsName; @UriParam(label = "producer", javaType = "java.lang.String", enums = "useConstant,useExchangeId,usePropertyValue") private MessageGroupIdStrategy messageGroupIdStrategy; @UriParam(label = "producer", javaType = "java.lang.String", defaultValue = "useExchangeId", enums = "useExchangeId,useContentBasedDeduplication") private MessageDeduplicationIdStrategy messageDeduplicationIdStrategy = new ExchangeIdMessageDeduplicationIdStrategy(); @UriParam private boolean batchEnabled; public String getSubject() { return subject; } /** * The subject which is used if the message header 'CamelAwsSnsSubject' is not present. */ public void setSubject(String subject) { this.subject = subject; } public String getTopicArn() { return topicArn; } /** * The Amazon Resource Name (ARN) assigned to the created topic. */ public void setTopicArn(String topicArn) { this.topicArn = topicArn; } public String getAccessKey() { return accessKey; } /** * Amazon AWS Access Key */ public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } /** * Amazon AWS Secret Key */ public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getSessionToken() { return sessionToken; } /** * Amazon AWS Session Token used when the user needs to assume an IAM role */ public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public SnsClient getAmazonSNSClient() { return amazonSNSClient; } /** * To use the AmazonSNS as the client */ public void setAmazonSNSClient(SnsClient amazonSNSClient) { this.amazonSNSClient = amazonSNSClient; } public String getTopicName() { return topicName; } /** * The name of the topic */ public void setTopicName(String topicName) { this.topicName = topicName; } public String getPolicy() { return policy; } /** * The policy for this topic. Is loaded by default from classpath, but you can prefix with "classpath:", "file:", or * "http:" to load the resource from different systems. */ public void setPolicy(String policy) { this.policy = policy; } public String getMessageStructure() { return messageStructure; } /** * The message structure to use such as json */ public void setMessageStructure(String messageStructure) { this.messageStructure = messageStructure; } public Protocol getProxyProtocol() { return proxyProtocol; } /** * To define a proxy protocol when instantiating the SNS client */ public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } /** * To define a proxy host when instantiating the SNS client */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } /** * To define a proxy port when instantiating the SNS client */ public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public String getRegion() { return region; } /** * The region in which the SNS client needs to work. When using this parameter, the configuration will expect the * lowercase name of the region (for example, ap-east-1) You'll need to use the name Region.EU_WEST_1.id() */ public void setRegion(String region) { this.region = region; } public String getQueueArn() { return queueArn; } /** * The ARN endpoint to subscribe to */ public void setQueueArn(String queueArn) { this.queueArn = queueArn; } public boolean isSubscribeSNStoSQS() { return subscribeSNStoSQS; } /** * Define if the subscription between SNS Topic and SQS must be done or not */ public void setSubscribeSNStoSQS(boolean subscribeSNStoSQS) { this.subscribeSNStoSQS = subscribeSNStoSQS; } public String getKmsMasterKeyId() { return kmsMasterKeyId; } /** * The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. */ public void setKmsMasterKeyId(String kmsMasterKeyId) { this.kmsMasterKeyId = kmsMasterKeyId; } public boolean isServerSideEncryptionEnabled() { return serverSideEncryptionEnabled; } /** * Define if Server Side Encryption is enabled or not on the topic */ public void setServerSideEncryptionEnabled(boolean serverSideEncryptionEnabled) { this.serverSideEncryptionEnabled = serverSideEncryptionEnabled; } public boolean isAutoCreateTopic() { return autoCreateTopic; } /** * Setting the auto-creation of the topic */ public void setAutoCreateTopic(boolean autoCreateTopic) { this.autoCreateTopic = autoCreateTopic; } public boolean isTrustAllCertificates() { return trustAllCertificates; } /** * If we want to trust all certificates in case of overriding the endpoint */ public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public boolean isUseDefaultCredentialsProvider() { return useDefaultCredentialsProvider; } /** * Set whether the SNS client should expect to load credentials on an AWS infra instance or to expect static * credentials to be passed in. */ public void setUseDefaultCredentialsProvider(boolean useDefaultCredentialsProvider) { this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; } /** * Set whether the SNS client should expect to load credentials through a profile credentials provider. */ public void setUseProfileCredentialsProvider(boolean useProfileCredentialsProvider) { this.useProfileCredentialsProvider = useProfileCredentialsProvider; } public boolean isUseProfileCredentialsProvider() { return useProfileCredentialsProvider; } public boolean isUseSessionCredentials() { return useSessionCredentials; } /** * Set whether the SNS client should expect to use Session Credentials. This is useful in a situation in which the * user needs to assume an IAM role for doing operations in SNS. */ public void setUseSessionCredentials(boolean useSessionCredentials) { this.useSessionCredentials = useSessionCredentials; } public String getProfileCredentialsName() { return profileCredentialsName; } /** * If using a profile credentials provider, this parameter will set the profile name */ public void setProfileCredentialsName(String profileCredentialsName) { this.profileCredentialsName = profileCredentialsName; } /** * Only for FIFO Topic. Strategy for setting the messageGroupId on the message. It can be one of the following * options: *useConstant*, *useExchangeId*, *usePropertyValue*. For the *usePropertyValue* option, the value of * property "CamelAwsSnsMessageGroupId" will be used. */ public void setMessageGroupIdStrategy(String strategy) { if ("useConstant".equalsIgnoreCase(strategy)) { messageGroupIdStrategy = new ConstantMessageGroupIdStrategy(); } else if ("useExchangeId".equalsIgnoreCase(strategy)) { messageGroupIdStrategy = new ExchangeIdMessageGroupIdStrategy(); } else if ("usePropertyValue".equalsIgnoreCase(strategy)) { messageGroupIdStrategy = new PropertyValueMessageGroupIdStrategy(); } else { throw new IllegalArgumentException("Unrecognised MessageGroupIdStrategy: " + strategy); } } public void setMessageGroupIdStrategy(MessageGroupIdStrategy messageGroupIdStrategy) { this.messageGroupIdStrategy = messageGroupIdStrategy; } public MessageGroupIdStrategy getMessageGroupIdStrategy() { return messageGroupIdStrategy; } public MessageDeduplicationIdStrategy getMessageDeduplicationIdStrategy() { return messageDeduplicationIdStrategy; } /** * Only for FIFO Topic. Strategy for setting the messageDeduplicationId on the message. It can be one of the * following options: *useExchangeId*, *useContentBasedDeduplication*. For the *useContentBasedDeduplication* * option, no messageDeduplicationId will be set on the message. */ public void setMessageDeduplicationIdStrategy(String strategy) { if ("useExchangeId".equalsIgnoreCase(strategy)) { messageDeduplicationIdStrategy = new ExchangeIdMessageDeduplicationIdStrategy(); } else if ("useContentBasedDeduplication".equalsIgnoreCase(strategy)) { messageDeduplicationIdStrategy = new NullMessageDeduplicationIdStrategy(); } else { throw new IllegalArgumentException("Unrecognised MessageDeduplicationIdStrategy: " + strategy); } } public void setMessageDeduplicationIdStrategy(MessageDeduplicationIdStrategy messageDeduplicationIdStrategy) { this.messageDeduplicationIdStrategy = messageDeduplicationIdStrategy; } public boolean isOverrideEndpoint() { return overrideEndpoint; } /** * Set the need for overriding the endpoint. This option needs to be used in combination with the * uriEndpointOverride option */ public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } /** * Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option */ public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } public boolean isBatchEnabled() { return batchEnabled; } /** * Define if we are publishing a single message or a batch */ public void setBatchEnabled(boolean batchEnabled) { this.batchEnabled = batchEnabled; } // ************************************************* // // ************************************************* public Sns2Configuration copy() { try { return (Sns2Configuration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } /** * Whether the topic is a FIFO topic */ boolean isFifoTopic() { // AWS docs suggest this is a valid derivation. // FIFO topic names must end with .fifo, and a standard topic cannot if (ObjectHelper.isNotEmpty(topicName)) { if (topicName.endsWith(".fifo")) { return true; } } if (ObjectHelper.isNotEmpty(topicArn)) { return topicArn.endsWith(".fifo"); } return false; } }
Sns2Configuration
java
elastic__elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/SubstringProcessorTests.java
{ "start": 949, "end": 6261 }
class ____ extends AbstractWireSerializingTestCase<SubstringFunctionProcessor> { @Override protected SubstringFunctionProcessor createTestInstance() { return new SubstringFunctionProcessor( new ConstantProcessor(randomRealisticUnicodeOfLengthBetween(0, 256)), new ConstantProcessor(randomInt(256)), new ConstantProcessor(randomInt(256)) ); } @Override protected SubstringFunctionProcessor mutateInstance(SubstringFunctionProcessor instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Reader<SubstringFunctionProcessor> instanceReader() { return SubstringFunctionProcessor::new; } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return new NamedWriteableRegistry(Processors.getNamedWriteables()); } public void testSubstringFunctionWithValidInput() { assertEquals("bar", new Substring(EMPTY, l("foobarbar"), l(4), l(3)).makePipe().asProcessor().process(null)); assertEquals("foo", new Substring(EMPTY, l("foobarbar"), l(1), l(3)).makePipe().asProcessor().process(null)); assertEquals("baz", new Substring(EMPTY, l("foobarbaz"), l(7), l(3)).makePipe().asProcessor().process(null)); assertEquals("f", new Substring(EMPTY, l('f'), l(1), l(1)).makePipe().asProcessor().process(null)); } public void testSubstringFunctionWithEdgeCases() { assertNull(new Substring(EMPTY, l("foobarbar"), l(1), l(null)).makePipe().asProcessor().process(null)); assertNull(new Substring(EMPTY, l("foobarbar"), l(null), l(3)).makePipe().asProcessor().process(null)); assertNull(new Substring(EMPTY, l(null), l(1), l(3)).makePipe().asProcessor().process(null)); assertNull(new Substring(EMPTY, l(null), l(null), l(null)).makePipe().asProcessor().process(null)); assertEquals("foo", new Substring(EMPTY, l("foobarbar"), l(-5), l(3)).makePipe().asProcessor().process(null)); assertEquals("barbar", new Substring(EMPTY, l("foobarbar"), l(4), l(30)).makePipe().asProcessor().process(null)); assertEquals("r", new Substring(EMPTY, l("foobarbar"), l(9), l(1)).makePipe().asProcessor().process(null)); assertEquals("", new Substring(EMPTY, l("foobarbar"), l(10), l(1)).makePipe().asProcessor().process(null)); assertEquals("", new Substring(EMPTY, l("foobarbar"), l(123), l(3)).makePipe().asProcessor().process(null)); } public void testSubstringFunctionInputsValidation() { Exception e = expectThrows( SqlIllegalArgumentException.class, () -> new Substring(EMPTY, l(5), l(1), l(3)).makePipe().asProcessor().process(null) ); assertEquals("A string/char is required; received [5]", e.getMessage()); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l(1), l("baz")).makePipe().asProcessor().process(null) ); assertEquals("A fixed point number is required for [length]; received [java.lang.String]", e.getMessage()); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l("bar"), l(3)).makePipe().asProcessor().process(null) ); assertEquals("A fixed point number is required for [start]; received [java.lang.String]", e.getMessage()); assertEquals("f", new Substring(EMPTY, l("foobarbar"), l(Integer.MIN_VALUE + 1), l(1)).makePipe().asProcessor().process(null)); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l(Integer.MIN_VALUE), l(1)).makePipe().asProcessor().process(null) ); assertEquals("[start] out of the allowed range [-2147483647, 2147483647], received [-2147483648]", e.getMessage()); assertEquals("", new Substring(EMPTY, l("foobarbar"), l(Integer.MAX_VALUE), l(1)).makePipe().asProcessor().process(null)); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l((long) Integer.MAX_VALUE + 1), l(1)).makePipe().asProcessor().process(null) ); assertEquals("[start] out of the allowed range [-2147483647, 2147483647], received [2147483648]", e.getMessage()); assertEquals("", new Substring(EMPTY, l("foobarbar"), l(1), l(0)).makePipe().asProcessor().process(null)); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l(1), l(-1)).makePipe().asProcessor().process(null) ); assertEquals("[length] out of the allowed range [0, 2147483647], received [-1]", e.getMessage()); assertEquals("foobarbar", new Substring(EMPTY, l("foobarbar"), l(1), l(Integer.MAX_VALUE)).makePipe().asProcessor().process(null)); e = expectThrows( InvalidArgumentException.class, () -> new Substring(EMPTY, l("foobarbar"), l(1), l((long) Integer.MAX_VALUE + 1)).makePipe().asProcessor().process(null) ); assertEquals("[length] out of the allowed range [0, 2147483647], received [2147483648]", e.getMessage()); } }
SubstringProcessorTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/schedulers/SchedulerLifecycleTest.java
{ "start": 923, "end": 4579 }
class ____ extends RxJavaTest { @Test public void shutdown() throws InterruptedException { tryOutSchedulers(); System.out.println("testShutdown >> Giving time threads to spin-up"); Thread.sleep(500); Set<Thread> rxThreads = new HashSet<>(); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("Rx")) { rxThreads.add(t); } } Schedulers.shutdown(); System.out.println("testShutdown >> Giving time to threads to stop"); Thread.sleep(500); StringBuilder b = new StringBuilder(); for (Thread t : rxThreads) { if (t.isAlive()) { b.append("Thread " + t + " failed to shutdown\r\n"); for (StackTraceElement ste : t.getStackTrace()) { b.append(" ").append(ste).append("\r\n"); } } } if (b.length() > 0) { System.out.print(b); System.out.println("testShutdown >> Restarting schedulers..."); Schedulers.start(); // restart them anyways fail("Rx Threads were still alive:\r\n" + b); } System.out.println("testShutdown >> Restarting schedulers..."); Schedulers.start(); tryOutSchedulers(); } private void tryOutSchedulers() throws InterruptedException { final CountDownLatch cdl = new CountDownLatch(4); final Runnable countAction = new Runnable() { @Override public void run() { cdl.countDown(); } }; CompositeDisposable cd = new CompositeDisposable(); try { Worker w1 = Schedulers.computation().createWorker(); cd.add(w1); w1.schedule(countAction); Worker w2 = Schedulers.io().createWorker(); cd.add(w2); w2.schedule(countAction); Worker w3 = Schedulers.newThread().createWorker(); cd.add(w3); w3.schedule(countAction); Worker w4 = Schedulers.single().createWorker(); cd.add(w4); w4.schedule(countAction); if (!cdl.await(3, TimeUnit.SECONDS)) { fail("countAction was not run by every worker"); } } finally { cd.dispose(); } } @Test public void startIdempotence() throws InterruptedException { tryOutSchedulers(); System.out.println("testStartIdempotence >> giving some time"); Thread.sleep(500); Set<Thread> rxThreadsBefore = new HashSet<>(); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("Rx")) { rxThreadsBefore.add(t); System.out.println("testStartIdempotence >> " + t); } } System.out.println("testStartIdempotence >> trying to start again"); Schedulers.start(); System.out.println("testStartIdempotence >> giving some time again"); Thread.sleep(500); Set<Thread> rxThreadsAfter = new HashSet<>(); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t.getName().startsWith("Rx")) { rxThreadsAfter.add(t); System.out.println("testStartIdempotence >>>> " + t); } } // cached threads may get dropped between the two checks rxThreadsAfter.removeAll(rxThreadsBefore); Assert.assertTrue("Some new threads appeared: " + rxThreadsAfter, rxThreadsAfter.isEmpty()); } }
SchedulerLifecycleTest
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client-jackson/deployment/src/test/java/io/quarkus/restclient/jackson/deployment/DateDto.java
{ "start": 91, "end": 390 }
class ____ { private ZonedDateTime date; public DateDto() { } public DateDto(ZonedDateTime date) { this.date = date; } public void setDate(ZonedDateTime date) { this.date = date; } public ZonedDateTime getDate() { return date; } }
DateDto
java
apache__camel
components/camel-jq/src/main/java/org/apache/camel/language/jq/JqFunctions.java
{ "start": 5374, "end": 7313 }
class ____ extends ExchangeAwareFunction { public static final String NAME = "header"; @Override protected void doApply( Scope scope, List<Expression> args, JsonNode in, Path path, PathOutput output, Version version, Exchange exchange) throws JsonQueryException { args.get(0).apply(scope, in, name -> { if (args.size() == 2) { args.get(1).apply(scope, in, defval -> { extract( exchange, name.asText(), defval.asText(), output); }); } else { extract( exchange, name.asText(), null, output); } }); } private void extract(Exchange exchange, String headerName, String headerValue, PathOutput output) throws JsonQueryException { String header = exchange.getMessage().getHeader(headerName, headerValue, String.class); if (header == null) { output.emit(NullNode.getInstance(), null); } else { output.emit(new TextNode(header), null); } } } /** * A function that allow to retrieve an {@link org.apache.camel.Message} property value as part of JQ expression * evaluation. * * As example, the following JQ expression sets the {@code .name} property to the value of the header named * {@code CommitterName}. * * <pre> * {@code * .name = property(\"CommitterName\")" * } * </pre> * */ public static
Header
java
grpc__grpc-java
opentelemetry/src/main/java/io/grpc/opentelemetry/GrpcOpenTelemetry.java
{ "start": 2478, "end": 13918 }
class ____ { private static final Supplier<Stopwatch> STOPWATCH_SUPPLIER = new Supplier<Stopwatch>() { @Override public Stopwatch get() { return Stopwatch.createUnstarted(); } }; @VisibleForTesting static boolean ENABLE_OTEL_TRACING = GrpcUtil.getFlag("GRPC_EXPERIMENTAL_ENABLE_OTEL_TRACING", false); private final OpenTelemetry openTelemetrySdk; private final MeterProvider meterProvider; private final Meter meter; private final Map<String, Boolean> enableMetrics; private final boolean disableDefault; private final OpenTelemetryMetricsResource resource; private final OpenTelemetryMetricsModule openTelemetryMetricsModule; private final OpenTelemetryTracingModule openTelemetryTracingModule; private final List<String> optionalLabels; private final MetricSink sink; public static Builder newBuilder() { return new Builder(); } private GrpcOpenTelemetry(Builder builder) { this.openTelemetrySdk = checkNotNull(builder.openTelemetrySdk, "openTelemetrySdk"); this.meterProvider = checkNotNull(openTelemetrySdk.getMeterProvider(), "meterProvider"); this.meter = this.meterProvider .meterBuilder(OpenTelemetryConstants.INSTRUMENTATION_SCOPE) .setInstrumentationVersion(IMPLEMENTATION_VERSION) .build(); this.enableMetrics = ImmutableMap.copyOf(builder.enableMetrics); this.disableDefault = builder.disableAll; this.resource = createMetricInstruments(meter, enableMetrics, disableDefault); this.optionalLabels = ImmutableList.copyOf(builder.optionalLabels); this.openTelemetryMetricsModule = new OpenTelemetryMetricsModule( STOPWATCH_SUPPLIER, resource, optionalLabels, builder.plugins); this.openTelemetryTracingModule = new OpenTelemetryTracingModule(openTelemetrySdk); this.sink = new OpenTelemetryMetricSink(meter, enableMetrics, disableDefault, optionalLabels); } @VisibleForTesting OpenTelemetry getOpenTelemetryInstance() { return this.openTelemetrySdk; } @VisibleForTesting MeterProvider getMeterProvider() { return this.meterProvider; } @VisibleForTesting Meter getMeter() { return this.meter; } @VisibleForTesting OpenTelemetryMetricsResource getResource() { return this.resource; } @VisibleForTesting Map<String, Boolean> getEnableMetrics() { return this.enableMetrics; } @VisibleForTesting List<String> getOptionalLabels() { return optionalLabels; } MetricSink getSink() { return sink; } @VisibleForTesting Tracer getTracer() { return this.openTelemetryTracingModule.getTracer(); } /** * Registers GrpcOpenTelemetry globally, applying its configuration to all subsequently created * gRPC channels and servers. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/10591") public void registerGlobal() { InternalConfiguratorRegistry.setConfigurators(Collections.singletonList( new InternalConfigurator() { @Override public void configureChannelBuilder(ManagedChannelBuilder<?> channelBuilder) { GrpcOpenTelemetry.this.configureChannelBuilder(channelBuilder); } @Override public void configureServerBuilder(ServerBuilder<?> serverBuilder) { GrpcOpenTelemetry.this.configureServerBuilder(serverBuilder); } })); } /** * Configures the given {@link ManagedChannelBuilder} with OpenTelemetry metrics instrumentation. */ public void configureChannelBuilder(ManagedChannelBuilder<?> builder) { InternalManagedChannelBuilder.addMetricSink(builder, sink); InternalManagedChannelBuilder.interceptWithTarget( builder, openTelemetryMetricsModule::getClientInterceptor); if (ENABLE_OTEL_TRACING) { builder.intercept(openTelemetryTracingModule.getClientInterceptor()); } } /** * Configures the given {@link ServerBuilder} with OpenTelemetry metrics instrumentation. * * @param serverBuilder the server builder to configure */ public void configureServerBuilder(ServerBuilder<?> serverBuilder) { /* To ensure baggage propagation to metrics, we need the tracing tracers to be initialised before metrics */ if (ENABLE_OTEL_TRACING) { serverBuilder.addStreamTracerFactory( openTelemetryTracingModule.getServerTracerFactory()); serverBuilder.intercept(openTelemetryTracingModule.getServerSpanPropagationInterceptor()); } serverBuilder.addStreamTracerFactory(openTelemetryMetricsModule.getServerTracerFactory()); } @VisibleForTesting static OpenTelemetryMetricsResource createMetricInstruments(Meter meter, Map<String, Boolean> enableMetrics, boolean disableDefault) { OpenTelemetryMetricsResource.Builder builder = OpenTelemetryMetricsResource.builder(); if (isMetricEnabled("grpc.client.call.duration", enableMetrics, disableDefault)) { builder.clientCallDurationCounter( meter.histogramBuilder("grpc.client.call.duration") .setUnit("s") .setDescription( "Time taken by gRPC to complete an RPC from application's perspective") .setExplicitBucketBoundariesAdvice(LATENCY_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.attempt.started", enableMetrics, disableDefault)) { builder.clientAttemptCountCounter( meter.counterBuilder("grpc.client.attempt.started") .setUnit("{attempt}") .setDescription("Number of client call attempts started") .build()); } if (isMetricEnabled("grpc.client.attempt.duration", enableMetrics, disableDefault)) { builder.clientAttemptDurationCounter( meter.histogramBuilder( "grpc.client.attempt.duration") .setUnit("s") .setDescription("Time taken to complete a client call attempt") .setExplicitBucketBoundariesAdvice(LATENCY_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.attempt.sent_total_compressed_message_size", enableMetrics, disableDefault)) { builder.clientTotalSentCompressedMessageSizeCounter( meter.histogramBuilder( "grpc.client.attempt.sent_total_compressed_message_size") .setUnit("By") .setDescription("Compressed message bytes sent per client call attempt") .ofLongs() .setExplicitBucketBoundariesAdvice(SIZE_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.attempt.rcvd_total_compressed_message_size", enableMetrics, disableDefault)) { builder.clientTotalReceivedCompressedMessageSizeCounter( meter.histogramBuilder( "grpc.client.attempt.rcvd_total_compressed_message_size") .setUnit("By") .setDescription("Compressed message bytes received per call attempt") .ofLongs() .setExplicitBucketBoundariesAdvice(SIZE_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.call.retries", enableMetrics, disableDefault)) { builder.clientCallRetriesCounter( meter.histogramBuilder( "grpc.client.call.retries") .setUnit("{retry}") .setDescription("Number of retries during the client call. " + "If there were no retries, 0 is not reported.") .ofLongs() .setExplicitBucketBoundariesAdvice(RETRY_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.call.transparent_retries", enableMetrics, disableDefault)) { builder.clientCallTransparentRetriesCounter( meter.histogramBuilder( "grpc.client.call.transparent_retries") .setUnit("{transparent_retry}") .setDescription("Number of transparent retries during the client call. " + "If there were no transparent retries, 0 is not reported.") .ofLongs() .setExplicitBucketBoundariesAdvice(TRANSPARENT_RETRY_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.call.hedges", enableMetrics, disableDefault)) { builder.clientCallHedgesCounter( meter.histogramBuilder( "grpc.client.call.hedges") .setUnit("{hedge}") .setDescription("Number of hedges during the client call. " + "If there were no hedges, 0 is not reported.") .ofLongs() .setExplicitBucketBoundariesAdvice(HEDGE_BUCKETS) .build()); } if (isMetricEnabled("grpc.client.call.retry_delay", enableMetrics, disableDefault)) { builder.clientCallRetryDelayCounter( meter.histogramBuilder( "grpc.client.call.retry_delay") .setUnit("s") .setDescription("Total time of delay while there is no active attempt during the " + "client call") .setExplicitBucketBoundariesAdvice(LATENCY_BUCKETS) .build()); } if (isMetricEnabled("grpc.server.call.started", enableMetrics, disableDefault)) { builder.serverCallCountCounter( meter.counterBuilder("grpc.server.call.started") .setUnit("{call}") .setDescription("Number of server calls started") .build()); } if (isMetricEnabled("grpc.server.call.duration", enableMetrics, disableDefault)) { builder.serverCallDurationCounter( meter.histogramBuilder("grpc.server.call.duration") .setUnit("s") .setDescription( "Time taken to complete a call from server transport's perspective") .setExplicitBucketBoundariesAdvice(LATENCY_BUCKETS) .build()); } if (isMetricEnabled("grpc.server.call.sent_total_compressed_message_size", enableMetrics, disableDefault)) { builder.serverTotalSentCompressedMessageSizeCounter( meter.histogramBuilder( "grpc.server.call.sent_total_compressed_message_size") .setUnit("By") .setDescription("Compressed message bytes sent per server call") .ofLongs() .setExplicitBucketBoundariesAdvice(SIZE_BUCKETS) .build()); } if (isMetricEnabled("grpc.server.call.rcvd_total_compressed_message_size", enableMetrics, disableDefault)) { builder.serverTotalReceivedCompressedMessageSizeCounter( meter.histogramBuilder( "grpc.server.call.rcvd_total_compressed_message_size") .setUnit("By") .setDescription("Compressed message bytes received per server call") .ofLongs() .setExplicitBucketBoundariesAdvice(SIZE_BUCKETS) .build()); } return builder.build(); } static boolean isMetricEnabled(String metricName, Map<String, Boolean> enableMetrics, boolean disableDefault) { Boolean explicitlyEnabled = enableMetrics.get(metricName); if (explicitlyEnabled != null) { return explicitlyEnabled; } return OpenTelemetryMetricsModule.DEFAULT_PER_CALL_METRICS_SET.contains(metricName) && !disableDefault; } /** * Builder for configuring {@link GrpcOpenTelemetry}. */ public static
GrpcOpenTelemetry
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/InstantiationIOException.java
{ "start": 1793, "end": 1848 }
enum ____ kinds of instantiation failure. */ public
of
java
square__moshi
examples/src/main/java/com/squareup/moshi/recipes/ByteStrings.java
{ "start": 1428, "end": 1940 }
class ____ extends JsonAdapter<ByteString> { @Override public ByteString fromJson(JsonReader reader) throws IOException { String base64 = reader.nextString(); return ByteString.decodeBase64(base64); } @Override public void toJson(JsonWriter writer, ByteString value) throws IOException { String string = value.base64(); writer.value(string); } } public static void main(String[] args) throws Exception { new ByteStrings().run(); } }
Base64ByteStringAdapter
java
spring-projects__spring-framework
spring-context/src/testFixtures/java/org/springframework/context/testfixture/jmx/export/Person.java
{ "start": 694, "end": 875 }
class ____ implements PersonMBean { private String name; @Override public String getName() { return name; } public void setName(String name) { this.name = name; } }
Person
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/connector/sink2/SupportsWriterState.java
{ "start": 1081, "end": 1504 }
interface ____ a {@link Sink} which supports a stateful {@link StatefulSinkWriter}. * * <p>The {@link Sink} needs to be serializable. All configuration should be validated eagerly. The * respective sink writers are transient and will only be created in the subtasks on the * taskmanagers. * * @param <InputT> The type of the sink's input * @param <WriterStateT> The type of the sink writer's state */ @Public public
for
java
apache__camel
components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/strategy/StrategyUtil.java
{ "start": 1058, "end": 3475 }
class ____ { private StrategyUtil() { } static <T> void ifNotEmpty(Map<String, Object> params, String key, Class<T> clazz, Consumer<T> consumer) { Object o = params.get(key); if (o != null) { consumer.accept(clazz.cast(o)); } } static void setup(GenericFileRenameExclusiveReadLockStrategy<?> readLockStrategy, Map<String, Object> params) { ifNotEmpty(params, "readLockTimeout", Long.class, readLockStrategy::setTimeout); ifNotEmpty(params, "readLockCheckInterval", Long.class, readLockStrategy::setCheckInterval); ifNotEmpty(params, "readLockMarkerFile", Boolean.class, readLockStrategy::setMarkerFiler); ifNotEmpty(params, "readLockLoggingLevel", LoggingLevel.class, readLockStrategy::setReadLockLoggingLevel); } static void setup(FtpChangedExclusiveReadLockStrategy readLockStrategy, Map<String, Object> params) { ifNotEmpty(params, "readLockTimeout", Long.class, readLockStrategy::setTimeout); ifNotEmpty(params, "readLockCheckInterval", Long.class, readLockStrategy::setCheckInterval); ifNotEmpty(params, "readLockMinLength", Long.class, readLockStrategy::setMinLength); ifNotEmpty(params, "readLockMinAge", Long.class, readLockStrategy::setMinAge); ifNotEmpty(params, "fastExistsCheck", Boolean.class, readLockStrategy::setFastExistsCheck); ifNotEmpty(params, "readLockMarkerFile", Boolean.class, readLockStrategy::setMarkerFiler); ifNotEmpty(params, "readLockLoggingLevel", LoggingLevel.class, readLockStrategy::setReadLockLoggingLevel); } static void setup(SftpChangedExclusiveReadLockStrategy readLockStrategy, Map<String, Object> params) { ifNotEmpty(params, "readLockTimeout", Long.class, readLockStrategy::setTimeout); ifNotEmpty(params, "readLockCheckInterval", Long.class, readLockStrategy::setCheckInterval); ifNotEmpty(params, "readLockMinLength", Long.class, readLockStrategy::setMinLength); ifNotEmpty(params, "readLockMinAge", Long.class, readLockStrategy::setMinAge); ifNotEmpty(params, "fastExistsCheck", Boolean.class, readLockStrategy::setFastExistsCheck); ifNotEmpty(params, "readLockMarkerFile", Boolean.class, readLockStrategy::setMarkerFiler); ifNotEmpty(params, "readLockLoggingLevel", LoggingLevel.class, readLockStrategy::setReadLockLoggingLevel); } }
StrategyUtil
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java
{ "start": 1705, "end": 1863 }
enum ____ { a, b, c, i } /** * Upper case version of SimpleEnum. * "i" is included for case tests, as it is special in turkey. */ private
SimpleEnum
java
google__guice
core/test/com/google/inject/ModuleTest.java
{ "start": 226, "end": 421 }
class ____ implements Module { @Override public void configure(Binder binder) { binder.bind(X.class); binder.install(new B()); binder.install(new C()); } } static
A
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java
{ "start": 11303, "end": 16615 }
class ____ implements BiConsumer<WebSocketSession, Throwable>, WebSocketHandler, TcpConnection<byte[]> { private final TcpConnectionHandler<byte[]> stompSession; private final StompWebSocketMessageCodec codec = new StompWebSocketMessageCodec(getInboundMessageSizeLimit(),getOutboundMessageSizeLimit()); private volatile @Nullable WebSocketSession session; private volatile long lastReadTime = -1; private volatile long lastWriteTime = -1; private @Nullable ScheduledFuture<?> readInactivityFuture; private @Nullable ScheduledFuture<?> writeInactivityFuture; public WebSocketTcpConnectionHandlerAdapter(TcpConnectionHandler<byte[]> stompSession) { Assert.notNull(stompSession, "TcpConnectionHandler must not be null"); this.stompSession = stompSession; } // CompletableFuture callback implementation: handshake outcome @Override public void accept(@Nullable WebSocketSession webSocketSession, @Nullable Throwable throwable) { if (throwable != null) { this.stompSession.afterConnectFailure(throwable); } } // WebSocketHandler implementation @Override public void afterConnectionEstablished(WebSocketSession session) { this.session = session; this.stompSession.afterConnected(this); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> webSocketMessage) { this.lastReadTime = (this.lastReadTime != -1 ? System.currentTimeMillis() : -1); List<Message<byte[]>> messages; try { messages = this.codec.decode(webSocketMessage); } catch (Throwable ex) { this.stompSession.handleFailure(ex); return; } for (Message<byte[]> message : messages) { this.stompSession.handleMessage(message); } } @Override public void handleTransportError(WebSocketSession session, Throwable ex) { this.stompSession.handleFailure(ex); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) { this.stompSession.afterConnectionClosed(); } @Override public boolean supportsPartialMessages() { return false; } // TcpConnection implementation @Override public CompletableFuture<Void> sendAsync(Message<byte[]> message) { updateLastWriteTime(); CompletableFuture<Void> future = new CompletableFuture<>(); try { WebSocketSession session = this.session; Assert.state(session != null, "No WebSocketSession available"); if (this.codec.hasSplittingEncoder()) { for (WebSocketMessage<?> outMessage : this.codec.encodeAndSplit(message, session.getClass())) { session.sendMessage(outMessage); } } else { session.sendMessage(this.codec.encode(message, session.getClass())); } future.complete(null); } catch (Throwable ex) { future.completeExceptionally(ex); } finally { updateLastWriteTime(); } return future; } private void updateLastWriteTime() { long lastWriteTime = this.lastWriteTime; if (lastWriteTime != -1) { this.lastWriteTime = System.currentTimeMillis(); } } @Override public void onReadInactivity(final Runnable runnable, final long duration) { Assert.state(getTaskScheduler() != null, "No TaskScheduler configured"); this.lastReadTime = System.currentTimeMillis(); Duration delay = Duration.ofMillis(duration / 2); this.readInactivityFuture = getTaskScheduler().scheduleWithFixedDelay(() -> { if (System.currentTimeMillis() - this.lastReadTime > duration) { try { runnable.run(); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("ReadInactivityTask failure", ex); } } } }, delay); } @Override public void onWriteInactivity(final Runnable runnable, final long duration) { Assert.state(getTaskScheduler() != null, "No TaskScheduler configured"); this.lastWriteTime = System.currentTimeMillis(); Duration delay = Duration.ofMillis(duration / 2); this.writeInactivityFuture = getTaskScheduler().scheduleWithFixedDelay(() -> { if (System.currentTimeMillis() - this.lastWriteTime > duration) { try { runnable.run(); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("WriteInactivityTask failure", ex); } } } }, delay); } @Override public void close() { cancelInactivityTasks(); WebSocketSession session = this.session; if (session != null) { try { session.close(); } catch (IOException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to close session: " + session.getId(), ex); } } } } private void cancelInactivityTasks() { ScheduledFuture<?> readFuture = this.readInactivityFuture; this.readInactivityFuture = null; cancelFuture(readFuture); ScheduledFuture<?> writeFuture = this.writeInactivityFuture; this.writeInactivityFuture = null; cancelFuture(writeFuture); this.lastReadTime = -1; this.lastWriteTime = -1; } private static void cancelFuture(@Nullable ScheduledFuture<?> future) { if (future != null) { try { future.cancel(true); } catch (Throwable ex) { // Ignore } } } } /** * Encode and decode STOMP WebSocket messages. */ private static
WebSocketTcpConnectionHandlerAdapter
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/testutils/MiniClusterResourceConfiguration.java
{ "start": 3131, "end": 5291 }
class ____ { private Configuration configuration = new Configuration(); private int numberTaskManagers = 1; private int numberSlotsPerTaskManager = 1; private Duration shutdownTimeout = configuration.get(RpcOptions.ASK_TIMEOUT_DURATION); private RpcServiceSharing rpcServiceSharing = RpcServiceSharing.SHARED; private MiniCluster.HaServices haServices = MiniCluster.HaServices.CONFIGURED; public Builder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Builder setNumberTaskManagers(int numberTaskManagers) { this.numberTaskManagers = numberTaskManagers; return this; } public Builder setNumberSlotsPerTaskManager(int numberSlotsPerTaskManager) { this.numberSlotsPerTaskManager = numberSlotsPerTaskManager; return this; } public Builder setShutdownTimeout(Duration shutdownTimeout) { this.shutdownTimeout = shutdownTimeout; return this; } public Builder setRpcServiceSharing(RpcServiceSharing rpcServiceSharing) { this.rpcServiceSharing = rpcServiceSharing; return this; } /** * Enables or disables {@link HaLeadershipControl} in {@link * MiniCluster#getHaLeadershipControl}. * * <p>{@link HaLeadershipControl} allows granting and revoking leadership of HA components. * Enabling this feature disables {@link HighAvailabilityOptions#HA_MODE} option. */ public Builder withHaLeadershipControl() { this.haServices = MiniCluster.HaServices.WITH_LEADERSHIP_CONTROL; return this; } public MiniClusterResourceConfiguration build() { return new MiniClusterResourceConfiguration( configuration, numberTaskManagers, numberSlotsPerTaskManager, shutdownTimeout, rpcServiceSharing, haServices); } } }
Builder
java
elastic__elasticsearch
modules/rank-eval/src/test/java/org/elasticsearch/index/rankeval/RatedDocumentTests.java
{ "start": 1262, "end": 4342 }
class ____ extends ESTestCase { public static RatedDocument createRatedDocument() { return new RatedDocument(randomAlphaOfLength(10), randomAlphaOfLength(10), randomInt()); } public void testXContentParsing() throws IOException { RatedDocument testItem = createRatedDocument(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); XContentBuilder shuffled = shuffleXContent(testItem.toXContent(builder, ToXContent.EMPTY_PARAMS)); try (XContentParser itemParser = createParser(shuffled)) { RatedDocument parsedItem = RatedDocument.fromXContent(itemParser); assertNotSame(testItem, parsedItem); assertEquals(testItem, parsedItem); assertEquals(testItem.hashCode(), parsedItem.hashCode()); } } public void testXContentParsingIsNotLenient() throws IOException { RatedDocument testItem = createRatedDocument(); XContentType xContentType = randomFrom(XContentType.values()); BytesReference originalBytes = toShuffledXContent(testItem, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean()); BytesReference withRandomFields = insertRandomFields(xContentType, originalBytes, null, random()); try (XContentParser parser = createParser(xContentType.xContent(), withRandomFields)) { XContentParseException exception = expectThrows(XContentParseException.class, () -> RatedDocument.fromXContent(parser)); assertThat(exception.getMessage(), containsString("[rated_document] unknown field")); } } public void testSerialization() throws IOException { RatedDocument original = createRatedDocument(); RatedDocument deserialized = ESTestCase.copyWriteable( original, new NamedWriteableRegistry(Collections.emptyList()), RatedDocument::new ); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } public void testEqualsAndHash() throws IOException { checkEqualsAndHashCode(createRatedDocument(), original -> { return new RatedDocument(original.getIndex(), original.getDocID(), original.getRating()); }, RatedDocumentTests::mutateTestItem); } private static RatedDocument mutateTestItem(RatedDocument original) { int rating = original.getRating(); String index = original.getIndex(); String docId = original.getDocID(); switch (randomIntBetween(0, 2)) { case 0 -> rating = randomValueOtherThan(rating, () -> randomInt()); case 1 -> index = randomValueOtherThan(index, () -> randomAlphaOfLength(10)); case 2 -> docId = randomValueOtherThan(docId, () -> randomAlphaOfLength(10)); default -> throw new IllegalStateException("The test should only allow two parameters mutated"); } return new RatedDocument(index, docId, rating); } }
RatedDocumentTests
java
processing__processing4
app/src/processing/app/laf/SwingUtilities2.java
{ "start": 1898, "end": 15475 }
class ____ { private static final int CHAR_BUFFER_SIZE = 100; private static final Object charsBufferLock = new Object(); private static char[] charsBuffer = new char[CHAR_BUFFER_SIZE]; public static final FontRenderContext DEFAULT_FRC = new FontRenderContext(null, false, false); /** * Fill the character buffer cache. Return the buffer length. */ private static int syncCharsBuffer(String s) { int length = s.length(); if ((charsBuffer == null) || (charsBuffer.length < length)) { charsBuffer = s.toCharArray(); } else { s.getChars(0, length, charsBuffer, 0); } return length; } /** * checks whether TextLayout is required to handle characters. * * @param text characters to be tested * @param start start * @param limit limit * @return {@code true} if TextLayout is required * {@code false} if TextLayout is not required */ public static final boolean isComplexLayout(char[] text, int start, int limit) { //return FontUtilities.isComplexText(text, start, limit); return false; } /** * Returns the FontMetrics for the current Font of the passed * in Graphics. This method is used when a Graphics * is available, typically when painting. If a Graphics is not * available the JComponent method of the same name should be used. * <p> * Callers should pass in a non-null JComponent, the exception * to this is if a JComponent is not readily available at the time of * painting. * <p> * This does not necessarily return the FontMetrics from the * Graphics. * * @param c JComponent requesting FontMetrics, may be null * @param g Graphics Graphics */ public static FontMetrics getFontMetrics(JComponent c, Graphics g) { return getFontMetrics(c, g, g.getFont()); } /** * Returns the FontMetrics for the specified Font. * This method is used when a Graphics is available, typically when * painting. If a Graphics is not available the JComponent method of * the same name should be used. * <p> * Callers should pass in a non-null JComonent, the exception * to this is if a JComponent is not readily available at the time of * painting. * <p> * This does not necessarily return the FontMetrics from the * Graphics. * * @param c JComponent requesting FontMetrics, may be null * @param c Graphics Graphics * @param font Font to get FontMetrics for */ @SuppressWarnings("deprecation") public static FontMetrics getFontMetrics(JComponent c, Graphics g, Font font) { if (c != null) { // Note: We assume that we're using the FontMetrics // from the widget to layout out text, otherwise we can get // mismatches when printing. return c.getFontMetrics(font); } return Toolkit.getDefaultToolkit().getFontMetrics(font); } /** * Returns the width of the passed in String. * If the passed String is {@code null}, returns zero. * * @param c JComponent that will display the string, may be null * @param fm FontMetrics used to measure the String width * @param string String to get the width of */ public static int stringWidth(JComponent c, FontMetrics fm, String string) { return (int) stringWidth(c, fm, string, false); } /** * Returns the width of the passed in String. * If the passed String is {@code null}, returns zero. * * @param c JComponent that will display the string, may be null * @param fm FontMetrics used to measure the String width * @param string String to get the width of * @param useFPAPI use floating point API */ public static float stringWidth(JComponent c, FontMetrics fm, String string, boolean useFPAPI){ if (string == null || string.isEmpty()) { return 0; } boolean needsTextLayout = ((c != null) && (c.getClientProperty(TextAttribute.NUMERIC_SHAPING) != null)); if (needsTextLayout) { synchronized(charsBufferLock) { int length = syncCharsBuffer(string); needsTextLayout = isComplexLayout(charsBuffer, 0, length); } } if (needsTextLayout) { TextLayout layout = createTextLayout(c, string, fm.getFont(), fm.getFontRenderContext()); return layout.getAdvance(); } else { return getFontStringWidth(string, fm, useFPAPI); } } public static float getFontStringWidth(String data, FontMetrics fm, boolean useFPAPI) { if (useFPAPI) { Rectangle2D bounds = fm.getFont() .getStringBounds(data, fm.getFontRenderContext()); return (float) bounds.getWidth(); } else { return fm.stringWidth(data); } } private static TextLayout createTextLayout(JComponent c, String s, Font f, FontRenderContext frc) { Object shaper = (c == null ? null : c.getClientProperty(TextAttribute.NUMERIC_SHAPING)); if (shaper == null) { return new TextLayout(s, f, frc); } else { Map<TextAttribute, Object> a = new HashMap<TextAttribute, Object>(); a.put(TextAttribute.FONT, f); a.put(TextAttribute.NUMERIC_SHAPING, shaper); return new TextLayout(s, a, frc); } } /** * Draws the string at the specified location. * * @param c JComponent that will display the string, may be null * @param g Graphics to draw the text to * @param text String to display * @param x X coordinate to draw the text at * @param y Y coordinate to draw the text at * @param useFPAPI use floating point API */ public static void drawString(JComponent c, Graphics g, String text, float x, float y, boolean useFPAPI) { // c may be null // All non-editable widgets that draw strings call into this // methods. By non-editable that means widgets like JLabel, JButton // but NOT JTextComponents. if ( text == null || text.length() <= 0 ) { //no need to paint empty strings return; } /* if (isPrinting(g)) { Graphics2D g2d = getGraphics2D(g); if (g2d != null) { String trimmedText = trimTrailingSpaces(text); if (!trimmedText.isEmpty()) { float screenWidth = (float) g2d.getFont().getStringBounds (trimmedText, getFontRenderContext(c)).getWidth(); TextLayout layout = createTextLayout(c, text, g2d.getFont(), g2d.getFontRenderContext()); // If text fits the screenWidth, then do not need to justify if (sun.swing.SwingUtilities2.stringWidth(c, g2d.getFontMetrics(), trimmedText) > screenWidth) { layout = layout.getJustifiedLayout(screenWidth); } // Use alternate print color if specified Color col = g2d.getColor(); if (col instanceof PrintColorUIResource) { g2d.setColor(((PrintColorUIResource)col).getPrintColor()); } layout.draw(g2d, x, y); g2d.setColor(col); } return; } } */ // If we get here we're not printing if (g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D)g; boolean needsTextLayout = ((c != null) && (c.getClientProperty(TextAttribute.NUMERIC_SHAPING) != null)); if (needsTextLayout) { synchronized(charsBufferLock) { int length = syncCharsBuffer(text); needsTextLayout = isComplexLayout(charsBuffer, 0, length); } } Object aaHint = (c == null) ? null : c.getClientProperty(KEY_TEXT_ANTIALIASING); if (aaHint != null) { Object oldContrast = null; Object oldAAValue = g2.getRenderingHint(KEY_TEXT_ANTIALIASING); if (aaHint != oldAAValue) { g2.setRenderingHint(KEY_TEXT_ANTIALIASING, aaHint); } else { oldAAValue = null; } Object lcdContrastHint = c.getClientProperty( KEY_TEXT_LCD_CONTRAST); if (lcdContrastHint != null) { oldContrast = g2.getRenderingHint(KEY_TEXT_LCD_CONTRAST); if (lcdContrastHint.equals(oldContrast)) { oldContrast = null; } else { g2.setRenderingHint(KEY_TEXT_LCD_CONTRAST, lcdContrastHint); } } if (needsTextLayout) { TextLayout layout = createTextLayout(c, text, g2.getFont(), g2.getFontRenderContext()); layout.draw(g2, x, y); } else { g2.drawString(text, x, y); } if (oldAAValue != null) { g2.setRenderingHint(KEY_TEXT_ANTIALIASING, oldAAValue); } if (oldContrast != null) { g2.setRenderingHint(KEY_TEXT_LCD_CONTRAST, oldContrast); } return; } if (needsTextLayout){ TextLayout layout = createTextLayout(c, text, g2.getFont(), g2.getFontRenderContext()); layout.draw(g2, x, y); return; } } g.drawString(text, (int) x, (int) y); } /** * Draws the string at the specified location underlining the specified * character. * * @param c JComponent that will display the string, may be null * @param g Graphics to draw the text to * @param text String to display * @param underlinedIndex Index of a character in the string to underline * @param x X coordinate to draw the text at * @param y Y coordinate to draw the text at */ public static void drawStringUnderlineCharAt(JComponent c,Graphics g, String text, int underlinedIndex, int x, int y) { drawStringUnderlineCharAt(c, g, text, underlinedIndex, x, y, false); } /** * Draws the string at the specified location underlining the specified * character. * * @param c JComponent that will display the string, may be null * @param g Graphics to draw the text to * @param text String to display * @param underlinedIndex Index of a character in the string to underline * @param x X coordinate to draw the text at * @param y Y coordinate to draw the text at * @param useFPAPI use floating point API */ public static void drawStringUnderlineCharAt(JComponent c, Graphics g, String text, int underlinedIndex, float x, float y, boolean useFPAPI) { if (text == null || text.length() <= 0) { return; } drawString(c, g, text, x, y, useFPAPI); int textLength = text.length(); if (underlinedIndex >= 0 && underlinedIndex < textLength ) { float underlineRectY = y; int underlineRectHeight = 1; float underlineRectX = 0; int underlineRectWidth = 0; // boolean isPrinting = isPrinting(g); // boolean needsTextLayout = isPrinting; boolean needsTextLayout = false; if (!needsTextLayout) { synchronized (charsBufferLock) { syncCharsBuffer(text); needsTextLayout = isComplexLayout(charsBuffer, 0, textLength); } } if (!needsTextLayout) { FontMetrics fm = g.getFontMetrics(); underlineRectX = x + stringWidth(c,fm, text.substring(0,underlinedIndex)); underlineRectWidth = fm.charWidth(text. charAt(underlinedIndex)); } else { Graphics2D g2d = getGraphics2D(g); if (g2d != null) { TextLayout layout = createTextLayout(c, text, g2d.getFont(), g2d.getFontRenderContext()); // if (isPrinting) { // float screenWidth = (float)g2d.getFont(). // getStringBounds(text, getFontRenderContext(c)).getWidth(); // // If text fits the screenWidth, then do not need to justify // if (stringWidth(c, g2d.getFontMetrics(), // text) > screenWidth) { // layout = layout.getJustifiedLayout(screenWidth); // } // } TextHitInfo leading = TextHitInfo.leading(underlinedIndex); TextHitInfo trailing = TextHitInfo.trailing(underlinedIndex); Shape shape = layout.getVisualHighlightShape(leading, trailing); Rectangle rect = shape.getBounds(); underlineRectX = x + rect.x; underlineRectWidth = rect.width; } } g.fillRect((int) underlineRectX, (int) underlineRectY + 1, underlineRectWidth, underlineRectHeight); } } /* * Tries it best to get Graphics2D out of the given Graphics * returns null if can not derive it. */ public static Graphics2D getGraphics2D(Graphics g) { if (g instanceof Graphics2D) { return (Graphics2D) g; // } else if (g instanceof ProxyPrintGraphics) { // return (Graphics2D)(((ProxyPrintGraphics)g).getGraphics()); } else { return null; } } /* * Returns FontRenderContext associated with Component. * FontRenderContext from Component.getFontMetrics is associated * with the component. * * Uses Component.getFontMetrics to get the FontRenderContext from. * see JComponent.getFontMetrics and TextLayoutStrategy.java */ public static FontRenderContext getFontRenderContext(Component c) { assert c != null; if (c == null) { return DEFAULT_FRC; } else { return c.getFontMetrics(c.getFont()).getFontRenderContext(); } } }
SwingUtilities2
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/connector/source/lib/util/IteratorSourceReader.java
{ "start": 1738, "end": 2096 }
class ____< E, IterT extends Iterator<E>, SplitT extends IteratorSourceSplit<E, IterT>> extends IteratorSourceReaderBase<E, E, IterT, SplitT> { public IteratorSourceReader(SourceReaderContext context) { super(context); } @Override protected E convert(E value) { return value; } }
IteratorSourceReader
java
google__guava
android/guava/src/com/google/common/reflect/TypeResolver.java
{ "start": 19952, "end": 20197 }
class ____<T> { // void set(T data) {...} // } // Holder<List<?>> should *not* resolve the set() method to set(List<?> data). // Instead, it should create a capture of the wildcard so that set() rejects any List<T>. private static
Holder
java
spring-projects__spring-framework
integration-tests/src/test/java/org/springframework/context/annotation/scope/ClassPathBeanDefinitionScannerScopeIntegrationTests.java
{ "start": 2031, "end": 11673 }
class ____ { private static final String DEFAULT_NAME = "default"; private static final String MODIFIED_NAME = "modified"; private ServletRequestAttributes oldRequestAttributes = new ServletRequestAttributes(new MockHttpServletRequest()); private ServletRequestAttributes newRequestAttributes = new ServletRequestAttributes(new MockHttpServletRequest()); private ServletRequestAttributes oldRequestAttributesWithSession; private ServletRequestAttributes newRequestAttributesWithSession; @BeforeEach void setup() { MockHttpServletRequest oldRequestWithSession = new MockHttpServletRequest(); oldRequestWithSession.setSession(new MockHttpSession()); this.oldRequestAttributesWithSession = new ServletRequestAttributes(oldRequestWithSession); MockHttpServletRequest newRequestWithSession = new MockHttpServletRequest(); newRequestWithSession.setSession(new MockHttpSession()); this.newRequestAttributesWithSession = new ServletRequestAttributes(newRequestWithSession); } @AfterEach void reset() { RequestContextHolder.resetRequestAttributes(); } @Test void singletonScopeWithNoProxy() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(NO); ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton"); // should not be a proxy assertThat(AopUtils.isAopProxy(bean)).isFalse(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); // singleton bean, so name should be modified even after lookup ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton"); assertThat(bean2.getName()).isEqualTo(MODIFIED_NAME); } @Test void singletonScopeIgnoresProxyInterfaces() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(INTERFACES); ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton"); // should not be a proxy assertThat(AopUtils.isAopProxy(bean)).isFalse(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); // singleton bean, so name should be modified even after lookup ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton"); assertThat(bean2.getName()).isEqualTo(MODIFIED_NAME); } @Test void singletonScopeIgnoresProxyTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(TARGET_CLASS); ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton"); // should not be a proxy assertThat(AopUtils.isAopProxy(bean)).isFalse(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); // singleton bean, so name should be modified even after lookup ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton"); assertThat(bean2.getName()).isEqualTo(MODIFIED_NAME); } @Test void requestScopeWithNoProxy() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(NO); ScopedTestBean bean = (ScopedTestBean) context.getBean("request"); // should not be a proxy assertThat(AopUtils.isAopProxy(bean)).isFalse(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); // but a newly retrieved bean should have the default name ScopedTestBean bean2 = (ScopedTestBean) context.getBean("request"); assertThat(bean2.getName()).isEqualTo(DEFAULT_NAME); } @Test void requestScopeWithProxiedInterfaces() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(INTERFACES); IScopedTestBean bean = (IScopedTestBean) context.getBean("request"); // should be dynamic proxy, implementing both interfaces assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); boolean condition = bean instanceof AnotherScopeTestInterface; assertThat(condition).isTrue(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // this is a proxy so it should be reset to default assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); RequestContextHolder.setRequestAttributes(oldRequestAttributes); assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); } @Test void requestScopeWithProxiedTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(TARGET_CLASS); IScopedTestBean bean = (IScopedTestBean) context.getBean("request"); // should be a class-based proxy assertThat(AopUtils.isCglibProxy(bean)).isTrue(); boolean condition = bean instanceof RequestScopedTestBean; assertThat(condition).isTrue(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // this is a proxy so it should be reset to default assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); RequestContextHolder.setRequestAttributes(oldRequestAttributes); assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); } @Test void sessionScopeWithNoProxy() { RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); ApplicationContext context = createContext(NO); ScopedTestBean bean = (ScopedTestBean) context.getBean("session"); // should not be a proxy assertThat(AopUtils.isAopProxy(bean)).isFalse(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession); // not a proxy so this should not have changed assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); // but a newly retrieved bean should have the default name ScopedTestBean bean2 = (ScopedTestBean) context.getBean("session"); assertThat(bean2.getName()).isEqualTo(DEFAULT_NAME); } @Test void sessionScopeWithProxiedInterfaces() { RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); ApplicationContext context = createContext(INTERFACES); IScopedTestBean bean = (IScopedTestBean) context.getBean("session"); // should be dynamic proxy, implementing both interfaces assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); boolean condition = bean instanceof AnotherScopeTestInterface; assertThat(condition).isTrue(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession); // this is a proxy so it should be reset to default assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); IScopedTestBean bean2 = (IScopedTestBean) context.getBean("session"); assertThat(bean2.getName()).isEqualTo(MODIFIED_NAME); bean2.setName(DEFAULT_NAME); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); } @Test void sessionScopeWithProxiedTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); ApplicationContext context = createContext(TARGET_CLASS); IScopedTestBean bean = (IScopedTestBean) context.getBean("session"); // should be a class-based proxy assertThat(AopUtils.isCglibProxy(bean)).isTrue(); boolean condition1 = bean instanceof ScopedTestBean; assertThat(condition1).isTrue(); boolean condition = bean instanceof SessionScopedTestBean; assertThat(condition).isTrue(); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession); // this is a proxy so it should be reset to default assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); bean.setName(MODIFIED_NAME); IScopedTestBean bean2 = (IScopedTestBean) context.getBean("session"); assertThat(bean2.getName()).isEqualTo(MODIFIED_NAME); bean2.setName(DEFAULT_NAME); assertThat(bean.getName()).isEqualTo(DEFAULT_NAME); RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); assertThat(bean.getName()).isEqualTo(MODIFIED_NAME); } private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) { GenericWebApplicationContext context = new GenericWebApplicationContext(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context); scanner.setIncludeAnnotationConfig(false); scanner.setBeanNameGenerator((definition, registry) -> definition.getScope()); scanner.setScopedProxyMode(scopedProxyMode); // Scan twice in order to find errors in the bean definition compatibility check. scanner.scan(getClass().getPackage().getName()); scanner.scan(getClass().getPackage().getName()); context.refresh(); return context; }
ClassPathBeanDefinitionScannerScopeIntegrationTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/node/DiscoveryNodeTests.java
{ "start": 1743, "end": 11914 }
class ____ extends ESTestCase { public void testRolesAreSorted() { final Set<DiscoveryNodeRole> roles = new HashSet<>(randomSubsetOf(DiscoveryNodeRole.roles())); final DiscoveryNode node = DiscoveryNodeUtils.create( "name", "id", new TransportAddress(TransportAddress.META_ADDRESS, 9200), emptyMap(), roles ); DiscoveryNodeRole previous = null; for (final DiscoveryNodeRole current : node.getRoles()) { if (previous != null) { assertThat(current, greaterThanOrEqualTo(previous)); } previous = current; } } public void testDiscoveryNodeIsCreatedWithHostFromInetAddress() throws Exception { InetAddress inetAddress = randomBoolean() ? InetAddress.getByName("192.0.2.1") : InetAddress.getByAddress("name1", new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 }); TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535)); DiscoveryNode node = DiscoveryNodeUtils.create("name1", "id1", transportAddress, emptyMap(), emptySet()); assertEquals(transportAddress.address().getHostString(), node.getHostName()); assertEquals(transportAddress.getAddress(), node.getHostAddress()); } public void testDiscoveryNodeSerializationKeepsHost() throws Exception { InetAddress inetAddress = InetAddress.getByAddress("name1", new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 }); TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535)); DiscoveryNode node = DiscoveryNodeUtils.create("name1", "id1", transportAddress, emptyMap(), emptySet()); BytesStreamOutput streamOutput = new BytesStreamOutput(); streamOutput.setTransportVersion(TransportVersion.current()); node.writeTo(streamOutput); StreamInput in = StreamInput.wrap(streamOutput.bytes().toBytesRef().bytes); DiscoveryNode serialized = new DiscoveryNode(in); assertEquals(transportAddress.address().getHostString(), serialized.getHostName()); assertEquals(transportAddress.address().getHostString(), serialized.getAddress().address().getHostString()); assertEquals(transportAddress.getAddress(), serialized.getHostAddress()); assertEquals(transportAddress.getAddress(), serialized.getAddress().getAddress()); assertEquals(transportAddress.getPort(), serialized.getAddress().getPort()); } public void testDiscoveryNodeRoleWithOldVersion() throws Exception { InetAddress inetAddress = InetAddress.getByAddress("name1", new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 }); TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535)); DiscoveryNodeRole customRole = new DiscoveryNodeRole("data_custom_role", "z", true); DiscoveryNode node = DiscoveryNodeUtils.create("name1", "id1", transportAddress, emptyMap(), Collections.singleton(customRole)); { BytesStreamOutput streamOutput = new BytesStreamOutput(); streamOutput.setTransportVersion(TransportVersion.current()); node.writeTo(streamOutput); StreamInput in = StreamInput.wrap(streamOutput.bytes().toBytesRef().bytes); in.setTransportVersion(TransportVersion.current()); DiscoveryNode serialized = new DiscoveryNode(in); final Set<DiscoveryNodeRole> roles = serialized.getRoles(); assertThat(roles, hasSize(1)); @SuppressWarnings("OptionalGetWithoutIsPresent") final DiscoveryNodeRole role = roles.stream().findFirst().get(); assertThat(role.roleName(), equalTo("data_custom_role")); assertThat(role.roleNameAbbreviation(), equalTo("z")); assertTrue(role.canContainData()); } } public void testDiscoveryNodeIsRemoteClusterClientDefault() { runTestDiscoveryNodeIsRemoteClusterClient(Settings.EMPTY, true); } public void testDiscoveryNodeIsRemoteClusterClientSet() { runTestDiscoveryNodeIsRemoteClusterClient(remoteClusterClientNode(), true); } public void testDiscoveryNodeIsRemoteClusterClientUnset() { runTestDiscoveryNodeIsRemoteClusterClient(nonRemoteClusterClientNode(), false); } private void runTestDiscoveryNodeIsRemoteClusterClient(final Settings settings, final boolean expected) { final DiscoveryNode node = DiscoveryNodeUtils.builder("node") .applySettings(settings) .address(new TransportAddress(TransportAddress.META_ADDRESS, 9200)) .build(); assertThat(node.isRemoteClusterClient(), equalTo(expected)); if (expected) { assertThat(node.getRoles(), hasItem(DiscoveryNodeRole.REMOTE_CLUSTER_CLIENT_ROLE)); } else { assertThat(node.getRoles(), not(hasItem(DiscoveryNodeRole.REMOTE_CLUSTER_CLIENT_ROLE))); } } public void testDiscoveryNodeDescriptionWithoutAttributes() { final DiscoveryNode node = DiscoveryNodeUtils.create( "test-id", buildNewFakeTransportAddress(), Map.of("test-attr", "val"), DiscoveryNodeRole.roles() ); final StringBuilder stringBuilder = new StringBuilder(); node.appendDescriptionWithoutAttributes(stringBuilder); final String descriptionWithoutAttributes = stringBuilder.toString(); assertThat(node.toString(), allOf(startsWith(descriptionWithoutAttributes), containsString("test-attr=val"))); assertThat(descriptionWithoutAttributes, not(containsString("test-attr"))); assertEquals(descriptionWithoutAttributes, node.descriptionWithoutAttributes()); } public void testDiscoveryNodeToXContent() { final TransportAddress transportAddress = buildNewFakeTransportAddress(); final boolean withExternalId = randomBoolean(); final DiscoveryNode node = new DiscoveryNode( "test-name", "test-id", "test-ephemeral-id", "test-hostname", "test-hostaddr", transportAddress, Map.of("test-attr", "val"), DiscoveryNodeRole.roles(), null, withExternalId ? "test-external-id" : null ); assertThat( Strings.toString(node, true, false), equalTo( Strings.format( """ { "test-id" : { "name" : "test-name", "ephemeral_id" : "test-ephemeral-id", "transport_address" : "%s", "external_id" : "%s", "attributes" : { "test-attr" : "val" }, "roles" : [ "data", "data_cold", "data_content", "data_frozen", "data_hot", "data_warm", "index", "ingest", "master", "ml", "remote_cluster_client", "search", "transform", "voting_only" ], "version" : "%s", "min_index_version" : %s, "max_index_version" : %s } }""", transportAddress, withExternalId ? "test-external-id" : "test-name", Version.CURRENT, IndexVersions.MINIMUM_COMPATIBLE, IndexVersion.current() ) ) ); } public void testDiscoveryNodeToString() { var node = DiscoveryNodeUtils.create( "test-id", buildNewFakeTransportAddress(), Map.of("test-attr", "val"), DiscoveryNodeRole.roles() ); var toString = node.toString(); assertThat(toString, containsString("{" + node.getId() + "}")); assertThat(toString, containsString("{" + node.getEphemeralId() + "}")); assertThat(toString, containsString("{" + node.getAddress() + "}")); assertThat(toString, containsString("{IScdfhilmrstvw}"));// roles assertThat(toString, containsString("{" + node.getBuildVersion() + "}")); assertThat(toString, containsString("{test-attr=val}"));// attributes } public void testDiscoveryNodeMinReadOnlyVersionSerialization() throws Exception { var node = DiscoveryNodeUtils.create("_id", buildNewFakeTransportAddress(), VersionInformation.CURRENT); { try (var out = new BytesStreamOutput()) { out.setTransportVersion(TransportVersion.current()); node.writeTo(out); try (var in = StreamInput.wrap(out.bytes().array())) { in.setTransportVersion(TransportVersion.current()); var deserialized = new DiscoveryNode(in); assertThat(deserialized.getId(), equalTo(node.getId())); assertThat(deserialized.getAddress(), equalTo(node.getAddress())); assertThat(deserialized.getMinIndexVersion(), equalTo(node.getMinIndexVersion())); assertThat(deserialized.getMaxIndexVersion(), equalTo(node.getMaxIndexVersion())); assertThat(deserialized.getMinReadOnlyIndexVersion(), equalTo(node.getMinReadOnlyIndexVersion())); assertThat(deserialized.getVersionInformation(), equalTo(node.getVersionInformation())); } } } } }
DiscoveryNodeTests
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/builder/xml/XsltOutputFileTest.java
{ "start": 1416, "end": 2909 }
class ____ extends ContextTestSupport { @Test public void testXsltOutputFile() throws Exception { Files.createDirectories(testDirectory()); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("<?xml version=\"1.0\" encoding=\"UTF-8\"?><goodbye>world!</goodbye>"); mock.expectedFileExists(testFile("xsltme.xml")); mock.message(0).body().isInstanceOf(File.class); template.sendBodyAndHeader("direct:start", "<hello>world!</hello>", Exchange.XSLT_FILE_NAME, testFile("xsltme.xml").toString()); mock.assertIsSatisfied(); } @Test public void testXsltOutputFileMissingHeader() { CamelExecutionException e = assertThrows(CamelExecutionException.class, () -> template.sendBody("direct:start", "<hello>world!</hello>"), "Should thrown exception"); NoSuchHeaderException nshe = assertIsInstanceOf(NoSuchHeaderException.class, e.getCause()); assertEquals(Exchange.XSLT_FILE_NAME, nshe.getHeaderName()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() throws Exception { URL styleSheet = getClass().getResource("example.xsl"); // output xslt as a file from("direct:start").process(xslt(styleSheet).outputFile()).to("mock:result"); } }; } }
XsltOutputFileTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/routing/allocation/ShardsLimitAllocationTests.java
{ "start": 1603, "end": 12318 }
class ____ extends ESAllocationTestCase { public void testIndexLevelShardsLimitAllocate() { AllocationService strategy = createAllocationService( Settings.builder().put("cluster.routing.allocation.node_concurrent_recoveries", 10).build() ); logger.info("Building initial routing table"); Metadata metadata = Metadata.builder() .put( IndexMetadata.builder("test") .settings( indexSettings(IndexVersion.current(), 4, 1).put( ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), 2 ) ) ) .build(); RoutingTable routingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY) .addAsNew(metadata.getProject().index("test")) .build(); ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadata).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder().add(newNode("node1")).add(newNode("node2"))) .build(); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(2)); logger.info("Start the primary shards"); clusterState = startInitializingShardsAndReroute(strategy, clusterState); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(0)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(0)); assertThat(clusterState.getRoutingNodes().unassigned().size(), equalTo(4)); logger.info("Do another reroute, make sure its still not allocated"); startInitializingShardsAndReroute(strategy, clusterState); } public void testClusterLevelShardsLimitAllocate() { AllocationService strategy = createAllocationService( Settings.builder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put(ShardsLimitAllocationDecider.CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), 1) .build() ); logger.info("Building initial routing table"); Metadata metadata = Metadata.builder() .put(IndexMetadata.builder("test").settings(indexSettings(IndexVersion.current(), 4, 0))) .build(); RoutingTable routingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY) .addAsNew(metadata.getProject().index("test")) .build(); ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadata).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder().add(newNode("node1")).add(newNode("node2"))) .build(); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(1)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(1)); logger.info("Start the primary shards"); clusterState = startInitializingShardsAndReroute(strategy, clusterState); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(1)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(1)); assertThat(clusterState.getRoutingNodes().unassigned().size(), equalTo(2)); // Bump the cluster total shards to 2 strategy = createAllocationService( Settings.builder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put(ShardsLimitAllocationDecider.CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), 2) .build() ); logger.info("Do another reroute, make sure shards are now allocated"); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(1)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(1)); clusterState = startInitializingShardsAndReroute(strategy, clusterState); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.getRoutingNodes().unassigned().size(), equalTo(0)); } public void testIndexLevelShardsLimitRemain() { AllocationService strategy = createAllocationService( Settings.builder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 10) .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1) .put("cluster.routing.allocation.balance.index", 0.0f) .build() ); logger.info("Building initial routing table"); Metadata metadata = Metadata.builder() .put(IndexMetadata.builder("test").settings(indexSettings(IndexVersion.current(), 5, 0))) .build(); RoutingTable initialRoutingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY) .addAsNew(metadata.getProject().index("test")) .build(); ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadata).routingTable(initialRoutingTable).build(); logger.info("Adding one node and reroute"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().add(newNode("node1"))).build(); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); logger.info("Start the primary shards"); clusterState = startInitializingShardsAndReroute(strategy, clusterState); assertThat(numberOfShardsWithState(clusterState.getRoutingNodes(), STARTED), equalTo(5)); logger.info("add another index with 5 shards"); metadata = Metadata.builder(clusterState.metadata()) .put(IndexMetadata.builder("test1").settings(indexSettings(IndexVersion.current(), 5, 0))) .build(); RoutingTable updatedRoutingTable = RoutingTable.builder( TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY, clusterState.routingTable() ).addAsNew(metadata.getProject().index("test1")).build(); clusterState = ClusterState.builder(clusterState).metadata(metadata).routingTable(updatedRoutingTable).build(); logger.info("Add another one node and reroute"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).add(newNode("node2"))).build(); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); clusterState = startInitializingShardsAndReroute(strategy, clusterState); assertThat(numberOfShardsWithState(clusterState.getRoutingNodes(), STARTED), equalTo(10)); for (ShardRouting shardRouting : clusterState.getRoutingNodes().node("node1")) { assertThat(shardRouting.getIndexName(), equalTo("test")); } for (ShardRouting shardRouting : clusterState.getRoutingNodes().node("node2")) { assertThat(shardRouting.getIndexName(), equalTo("test1")); } logger.info("update {} for test, see that things move", ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey()); metadata = Metadata.builder(clusterState.metadata()) .put( IndexMetadata.builder(clusterState.metadata().getProject().index("test")) .settings( indexSettings(IndexVersion.current(), 5, 0).put( ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), 3 ) ) ) .build(); clusterState = ClusterState.builder(clusterState).metadata(metadata).build(); logger.info("reroute after setting"); clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop()); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(STARTED), equalTo(3)); assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(RELOCATING), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(RELOCATING), equalTo(2)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(STARTED), equalTo(3)); // the first move will destroy the balance and the balancer will move 2 shards from node2 to node one right after // moving the nodes to node2 since we consider INITIALIZING nodes during rebalance clusterState = startInitializingShardsAndReroute(strategy, clusterState); // now we are done compared to EvenShardCountAllocator since the Balancer is not soely based on the average assertThat(clusterState.getRoutingNodes().node("node1").numberOfShardsWithState(STARTED), equalTo(5)); assertThat(clusterState.getRoutingNodes().node("node2").numberOfShardsWithState(STARTED), equalTo(5)); } }
ShardsLimitAllocationTests
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepository.java
{ "start": 18964, "end": 21767 }
class ____ implements Function<RegisteredClient, List<SqlParameterValue>> { private AbstractRegisteredClientParametersMapper() { } @Override public List<SqlParameterValue> apply(RegisteredClient registeredClient) { Timestamp clientIdIssuedAt = (registeredClient.getClientIdIssuedAt() != null) ? Timestamp.from(registeredClient.getClientIdIssuedAt()) : Timestamp.from(Instant.now()); Timestamp clientSecretExpiresAt = (registeredClient.getClientSecretExpiresAt() != null) ? Timestamp.from(registeredClient.getClientSecretExpiresAt()) : null; List<String> clientAuthenticationMethods = new ArrayList<>( registeredClient.getClientAuthenticationMethods().size()); registeredClient.getClientAuthenticationMethods() .forEach((clientAuthenticationMethod) -> clientAuthenticationMethods .add(clientAuthenticationMethod.getValue())); List<String> authorizationGrantTypes = new ArrayList<>( registeredClient.getAuthorizationGrantTypes().size()); registeredClient.getAuthorizationGrantTypes() .forEach((authorizationGrantType) -> authorizationGrantTypes.add(authorizationGrantType.getValue())); return Arrays.asList(new SqlParameterValue(Types.VARCHAR, registeredClient.getId()), new SqlParameterValue(Types.VARCHAR, registeredClient.getClientId()), new SqlParameterValue(Types.TIMESTAMP, clientIdIssuedAt), new SqlParameterValue(Types.VARCHAR, registeredClient.getClientSecret()), new SqlParameterValue(Types.TIMESTAMP, clientSecretExpiresAt), new SqlParameterValue(Types.VARCHAR, registeredClient.getClientName()), new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToCommaDelimitedString(clientAuthenticationMethods)), new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToCommaDelimitedString(authorizationGrantTypes)), new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToCommaDelimitedString(registeredClient.getRedirectUris())), new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToCommaDelimitedString(registeredClient.getPostLogoutRedirectUris())), new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToCommaDelimitedString(registeredClient.getScopes())), new SqlParameterValue(Types.VARCHAR, writeMap(registeredClient.getClientSettings().getSettings())), new SqlParameterValue(Types.VARCHAR, writeMap(registeredClient.getTokenSettings().getSettings()))); } private String writeMap(Map<String, Object> data) { try { return writeValueAsString(data); } catch (Exception ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } abstract String writeValueAsString(Map<String, Object> data) throws Exception; } /** * Nested
AbstractRegisteredClientParametersMapper
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/GenerateDistCacheData.java
{ "start": 5552, "end": 7152 }
class ____ extends Mapper<LongWritable, BytesWritable, NullWritable, BytesWritable> { private BytesWritable val; private final Random r = new Random(); private FileSystem fs; @Override protected void setup(Context context) throws IOException, InterruptedException { val = new BytesWritable(new byte[context.getConfiguration().getInt( GenerateData.GRIDMIX_VAL_BYTES, 1024 * 1024)]); fs = FileSystem.get(context.getConfiguration()); } // Create one distributed cache file with the needed file size. // key is distributed cache file size and // value is distributed cache file path. @Override public void map(LongWritable key, BytesWritable value, Context context) throws IOException, InterruptedException { String fileName = new String(value.getBytes(), 0, value.getLength(), charsetUTF8); Path path = new Path(fileName); FSDataOutputStream dos = FileSystem.create(fs, path, new FsPermission(GRIDMIX_DISTCACHE_FILE_PERM)); int size = 0; for (long bytes = key.get(); bytes > 0; bytes -= size) { r.nextBytes(val.getBytes()); size = (int)Math.min(val.getLength(), bytes); dos.write(val.getBytes(), 0, size);// Write to distCache file } dos.close(); } } /** * InputFormat for GenerateDistCacheData. * Input to GenerateDistCacheData is the special file(in SequenceFile format) * that contains the list of distributed cache files to be generated along * with their file sizes. */ static
GenDCDataMapper
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/codec/FindOutputCodec.java
{ "start": 673, "end": 1228 }
class ____ implements TextMessageCodec<Item> { @Override public boolean supports(Type type) { return type.equals(Item.class); } @Override public String encode(Item value) { JsonObject json = JsonObject.mapFrom(value); json.remove("count"); // intentionally remove the "count" return json.encode(); } @Override public Item decode(Type type, String value) { throw new UnsupportedOperationException(); } } }
MyOutputCodec
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/CGroupsV2MemoryResourceHandlerImpl.java
{ "start": 1152, "end": 2104 }
class ____ extends AbstractCGroupsMemoryResourceHandler { CGroupsV2MemoryResourceHandlerImpl(CGroupsHandler cGroupsHandler) { super(cGroupsHandler); } @Override protected void updateMemoryHardLimit(String cgroupId, long containerHardLimit) throws ResourceHandlerException { getCGroupsHandler().updateCGroupParam(MEMORY, cgroupId, CGroupsHandler.CGROUP_MEMORY_MAX, String.valueOf(containerHardLimit) + "M"); } @Override protected void updateOpportunisticMemoryLimits(String cgroupId) throws ResourceHandlerException { updateGuaranteedMemoryLimits(cgroupId, OPPORTUNISTIC_SOFT_LIMIT); } @Override protected void updateGuaranteedMemoryLimits(String cgroupId, long containerSoftLimit) throws ResourceHandlerException { getCGroupsHandler().updateCGroupParam(MEMORY, cgroupId, CGroupsHandler.CGROUP_MEMORY_LOW, String.valueOf(containerSoftLimit) + "M"); } }
CGroupsV2MemoryResourceHandlerImpl
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedDualCamelContextTest.java
{ "start": 1430, "end": 3898 }
class ____ extends TestSupport { protected CamelContext createCamelContext() throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(createRouteBuilder()); return context; } @Test public void testDualCamelContext() throws Exception { CamelContext camel1 = createCamelContext(); camel1.start(); CamelContext camel2 = createCamelContext(); camel2.start(); // Ensure JMX is enabled for this test so the ManagedManagementStrategy.class // If other tests cleaned up the environment properly the following assertions will be true with the default settings assertIsInstanceOf(JmxManagementStrategy.class, camel1.getManagementStrategy()); assertIsInstanceOf(JmxManagementStrategy.class, camel2.getManagementStrategy()); MBeanServer mbeanServer1 = camel1.getManagementStrategy().getManagementAgent().getMBeanServer(); Set<ObjectName> set = mbeanServer1 .queryNames(new ObjectName("*:context=" + camel1.getManagementName() + ",type=components,*"), null); assertEquals(2, set.size()); ObjectName on = set.iterator().next(); assertTrue(mbeanServer1.isRegistered(on), "Should be registered"); String state = (String) mbeanServer1.getAttribute(on, "State"); assertEquals(ServiceStatus.Started.name(), state); String id = (String) mbeanServer1.getAttribute(on, "CamelId"); assertEquals(camel1.getManagementName(), id); MBeanServer mbeanServer2 = camel2.getManagementStrategy().getManagementAgent().getMBeanServer(); set = mbeanServer1.queryNames(new ObjectName("*:context=" + camel2.getManagementName() + ",type=components,*"), null); assertEquals(2, set.size()); on = set.iterator().next(); assertTrue(mbeanServer2.isRegistered(on), "Should be registered"); state = (String) mbeanServer2.getAttribute(on, "State"); assertEquals(ServiceStatus.Started.name(), state); id = (String) mbeanServer2.getAttribute(on, "CamelId"); assertEquals(camel2.getManagementName(), id); camel1.stop(); camel2.stop(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("mock:result"); } }; } }
ManagedDualCamelContextTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
{ "start": 162725, "end": 162939 }
class ____ implements ITypeConverter<Long> { @Override public Long convert(final String value) { return Long.valueOf(value); } } static
LongConverter
java
dropwizard__dropwizard
dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkAwareProxyFactory.java
{ "start": 2980, "end": 3252 }
class ____ * @param <T> the type of the class * @return a new proxy */ public <T> T create(Class<T> clazz) { return create(clazz, new Class<?>[]{}, new Object[]{}); } /** * Creates a new <b>@UnitOfWork</b> aware proxy of a
definition
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMinBytesRefEvaluator.java
{ "start": 5385, "end": 5876 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final EvalOperator.ExpressionEvaluator.Factory field; public Factory(EvalOperator.ExpressionEvaluator.Factory field) { this.field = field; } @Override public MvMinBytesRefEvaluator get(DriverContext context) { return new MvMinBytesRefEvaluator(field.get(context), context); } @Override public String toString() { return "MvMin[field=" + field + "]"; } } }
Factory
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/superclass/SuperclassInjectionTest.java
{ "start": 2703, "end": 2889 }
class ____ extends SuperHarvester { @Inject Head sameName; Head getCombineHead() { return sameName; } } public static
CombineHarvester
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/helper/BufferedClientResponse.java
{ "start": 1239, "end": 1347 }
class ____ the details of how to do that and prevents * unnecessary code duplication in tests. */ public
hides
java
spring-projects__spring-boot
module/spring-boot-health/src/main/java/org/springframework/boot/health/contributor/ReactiveHealthContributor.java
{ "start": 1135, "end": 2227 }
interface ____ permits ReactiveHealthIndicator, CompositeReactiveHealthContributor { /** * Return this reactive contributor as a standard blocking {@link HealthContributor}. * @return a blocking health contributor */ HealthContributor asHealthContributor(); /** * Adapts the given {@link HealthContributor} into a {@link ReactiveHealthContributor} * by scheduling blocking calls to {@link Schedulers#boundedElastic()}. * @param contributor the contributor to adapt or {@code null} * @return the adapted contributor */ @Contract("!null -> !null") static @Nullable ReactiveHealthContributor adapt(@Nullable HealthContributor contributor) { if (contributor == null) { return null; } if (contributor instanceof HealthIndicator healthIndicator) { return new HealthIndicatorAdapter(healthIndicator); } if (contributor instanceof CompositeHealthContributor compositeHealthContributor) { return new CompositeHealthContributorAdapter(compositeHealthContributor); } throw new IllegalStateException("Unknown 'contributor' type"); } }
ReactiveHealthContributor
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/executor/loader/cglib/CglibProxyFactory.java
{ "start": 9449, "end": 9553 }
class ____ { private static final Log log = LogFactory.getLog(CglibProxyFactory.class); } }
LogHolder
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/instantiation/internal/BeanInjectorField.java
{ "start": 295, "end": 668 }
class ____<T> implements BeanInjector<T> { private final Field field; public BeanInjectorField(Field field) { this.field = field; } @Override public void inject(T target, Object value) { try { field.set( target, value ); } catch (Exception e) { throw new InstantiationException( "Error performing the dynamic instantiation", e ); } } }
BeanInjectorField
java
dropwizard__dropwizard
dropwizard-client/src/main/java/io/dropwizard/client/HttpClientConfiguration.java
{ "start": 487, "end": 659 }
class ____ by {@link HttpClientBuilder}. * * @see <a href="http://dropwizard.io/0.9.1/docs/manual/configuration.html#httpclient">Http Client Configuration</a> */ public
used
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/ElectLeadersResult.java
{ "start": 1286, "end": 2823 }
class ____ { private final KafkaFuture<Map<TopicPartition, Optional<Throwable>>> electionFuture; ElectLeadersResult(KafkaFuture<Map<TopicPartition, Optional<Throwable>>> electionFuture) { this.electionFuture = electionFuture; } /** * <p>Get a future for the topic partitions for which a leader election was attempted. * If the election succeeded then the value for a topic partition will be the empty Optional. * Otherwise the election failed and the Optional will be set with the error.</p> */ public KafkaFuture<Map<TopicPartition, Optional<Throwable>>> partitions() { return electionFuture; } /** * Return a future which succeeds if all the topic elections succeed. */ public KafkaFuture<Void> all() { final KafkaFutureImpl<Void> result = new KafkaFutureImpl<>(); partitions().whenComplete( (topicPartitions, throwable) -> { if (throwable != null) { result.completeExceptionally(throwable); } else { for (Optional<Throwable> exception : topicPartitions.values()) { if (exception.isPresent()) { result.completeExceptionally(exception.get()); return; } } result.complete(null); } }); return result; } }
ElectLeadersResult
java
spring-projects__spring-security
test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java
{ "start": 59818, "end": 63724 }
class ____ implements RequestPostProcessor { private String registrationId = "test"; private @Nullable ClientRegistration clientRegistration; private String principalName = "user"; private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", null, null, Collections.singleton("read")); private OAuth2ClientRequestPostProcessor() { } private OAuth2ClientRequestPostProcessor(String registrationId) { this.registrationId = registrationId; clientRegistration((c) -> { }); } /** * Use this {@link ClientRegistration} * @param clientRegistration * @return the {@link OAuth2ClientRequestPostProcessor} for further configuration */ public OAuth2ClientRequestPostProcessor clientRegistration(ClientRegistration clientRegistration) { this.clientRegistration = clientRegistration; return this; } /** * Use this {@link Consumer} to configure a {@link ClientRegistration} * @param clientRegistrationConfigurer the {@link ClientRegistration} configurer * @return the {@link OAuth2ClientRequestPostProcessor} for further configuration */ public OAuth2ClientRequestPostProcessor clientRegistration( Consumer<ClientRegistration.Builder> clientRegistrationConfigurer) { ClientRegistration.Builder builder = clientRegistrationBuilder(); clientRegistrationConfigurer.accept(builder); this.clientRegistration = builder.build(); return this; } /** * Use this as the resource owner's principal name * @param principalName the resource owner's principal name * @return the {@link OAuth2ClientRequestPostProcessor} for further configuration */ public OAuth2ClientRequestPostProcessor principalName(String principalName) { Assert.notNull(principalName, "principalName cannot be null"); this.principalName = principalName; return this; } /** * Use this {@link OAuth2AccessToken} * @param accessToken the {@link OAuth2AccessToken} to use * @return the {@link OAuth2ClientRequestPostProcessor} for further configuration */ public OAuth2ClientRequestPostProcessor accessToken(OAuth2AccessToken accessToken) { this.accessToken = accessToken; return this; } @NullUnmarked @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { if (this.clientRegistration == null) { throw new IllegalArgumentException( "Please specify a ClientRegistration via one " + "of the clientRegistration methods"); } OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken); OAuth2AuthorizedClientRepository authorizedClientRepository = OAuth2ClientServletTestUtils .getAuthorizedClientRepository(request); if (!(authorizedClientRepository instanceof TestOAuth2AuthorizedClientRepository)) { authorizedClientRepository = new TestOAuth2AuthorizedClientRepository(authorizedClientRepository); OAuth2ClientServletTestUtils.setAuthorizedClientRepository(request, authorizedClientRepository); } TestOAuth2AuthorizedClientRepository.enable(request); authorizedClientRepository.saveAuthorizedClient(client, null, request, new MockHttpServletResponse()); return request; } private ClientRegistration.Builder clientRegistrationBuilder() { return ClientRegistration.withRegistrationId(this.registrationId) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("https://client.example.com") .clientId("test-client") .clientSecret("test-secret") .authorizationUri("https://idp.example.org/oauth/authorize") .tokenUri("https://idp.example.org/oauth/token"); } /** * Used to wrap the {@link OAuth2AuthorizedClientRepository} to provide support * for testing when the request is wrapped */ private static final
OAuth2ClientRequestPostProcessor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/sink/RollingFileSystemSinkTestBase.java
{ "start": 2723, "end": 2843 }
class ____ various contexts. It provides the a number of useful utility * methods for classes that extend it. */ public
in
java
apache__maven
its/core-it-suite/src/test/resources/mng-3684/maven-mng3684-plugin/src/main/java/plugin/MyMojo.java
{ "start": 1800, "end": 5334 }
class ____ extends AbstractMojo { /** * @parameter default-value="${project.build}" * @required * @readonly */ private Build build; /** * @parameter default-value="${project}" * @required * @readonly */ private MavenProject project; public void execute() throws MojoExecutionException { Build projectBuild = project.getBuild(); Map failedComparisons = new HashMap(); check("project.build.directory", projectBuild.getDirectory(), build.getDirectory(), failedComparisons); check( "project.build.outputDirectory", projectBuild.getOutputDirectory(), build.getOutputDirectory(), failedComparisons); check( "project.build.sourceDirectory", projectBuild.getSourceDirectory(), build.getSourceDirectory(), failedComparisons); check( "project.build.testSourceDirectory", projectBuild.getTestSourceDirectory(), build.getTestSourceDirectory(), failedComparisons); check( "project.build.scriptSourceDirectory", projectBuild.getScriptSourceDirectory(), build.getScriptSourceDirectory(), failedComparisons); List projectResources = projectBuild.getResources(); List buildResources = build.getResources(); if (projectResources != null) { for (int i = 0; i < projectResources.size(); i++) { Resource projectRes = (Resource) projectResources.get(i); Resource buildRes = (Resource) buildResources.get(i); check( "project.build.resources[" + i + "].directory", projectRes.getDirectory(), buildRes.getDirectory(), failedComparisons); check( "project.build.resources[" + i + "].targetPath", projectRes.getTargetPath(), buildRes.getTargetPath(), failedComparisons); } } if (!failedComparisons.isEmpty()) { StringBuffer buffer = new StringBuffer(); buffer.append("One or more build-section values were not interpolated correctly" + "\nbefore the build instance was injected as a plugin parameter:\n"); for (Iterator it = failedComparisons.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String[] value = (String[]) entry.getValue(); buffer.append("\n- ").append(key); buffer.append("\n\tShould be: \'").append(value[0]); buffer.append("\'\n\t Was: \'").append(value[1]).append("\'\n"); } throw new MojoExecutionException(buffer.toString()); } } private void check(String description, String projectValue, String buildValue, Map failedComparisons) { if (projectValue == null && buildValue != null) { failedComparisons.put(description, new String[] {projectValue, buildValue}); } else if (projectValue != null && !projectValue.equals(buildValue)) { failedComparisons.put(description, new String[] {projectValue, buildValue}); } } }
MyMojo
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/AsyncLookupJoinHarnessTest.java
{ "start": 4105, "end": 15202 }
class ____ { private static final int ASYNC_BUFFER_CAPACITY = 100; private static final int ASYNC_TIMEOUT_MS = 3000; private boolean orderedResult; @Parameters(name = "ordered result = {0}") private static Object[] parameters() { return new Object[][] {new Object[] {true}, new Object[] {false}}; } private final TypeSerializer<RowData> inSerializer = new RowDataSerializer( DataTypes.INT().getLogicalType(), DataTypes.STRING().getLogicalType()); private final RowDataHarnessAssertor assertor = new RowDataHarnessAssertor( new LogicalType[] { DataTypes.INT().getLogicalType(), DataTypes.STRING().getLogicalType(), DataTypes.INT().getLogicalType(), DataTypes.STRING().getLogicalType() }); private final DataType rightRowDataType = DataTypes.ROW( DataTypes.FIELD("f0", DataTypes.INT()), DataTypes.FIELD("f1", DataTypes.STRING())) .bridgedTo(RowData.class); @SuppressWarnings({"unchecked", "rawtypes"}) private final DataStructureConverter<RowData, Object> fetcherConverter = (DataStructureConverter) DataStructureConverters.getConverter(rightRowDataType); private final RowDataSerializer rightRowSerializer = (RowDataSerializer) InternalSerializers.<RowData>create(rightRowDataType.getLogicalType()); @TestTemplate void testTemporalInnerAsyncJoin() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createHarness(JoinType.INNER_JOIN, FilterOnTable.WITHOUT_FILTER); testHarness.open(); synchronized (testHarness.getCheckpointLock()) { testHarness.processElement(insertRecord(1, "a")); testHarness.processElement(insertRecord(2, "b")); testHarness.processElement(insertRecord(3, "c")); testHarness.processElement(insertRecord(4, "d")); testHarness.processElement(insertRecord(5, "e")); } // wait until all async collectors in the buffer have been emitted out. synchronized (testHarness.getCheckpointLock()) { testHarness.endInput(); testHarness.close(); } List<Object> expectedOutput = new ArrayList<>(); expectedOutput.add(insertRecord(1, "a", 1, "Julian")); expectedOutput.add(insertRecord(3, "c", 3, "Jark")); expectedOutput.add(insertRecord(3, "c", 3, "Jackson")); expectedOutput.add(insertRecord(4, "d", 4, "Fabian")); checkResult(expectedOutput, testHarness.getOutput()); } @TestTemplate void testTemporalInnerAsyncJoinWithFilter() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createHarness(JoinType.INNER_JOIN, FilterOnTable.WITH_FILTER); testHarness.open(); synchronized (testHarness.getCheckpointLock()) { testHarness.processElement(insertRecord(1, "a")); testHarness.processElement(insertRecord(2, "b")); testHarness.processElement(insertRecord(3, "c")); testHarness.processElement(insertRecord(4, "d")); testHarness.processElement(insertRecord(5, "e")); } // wait until all async collectors in the buffer have been emitted out. synchronized (testHarness.getCheckpointLock()) { testHarness.endInput(); testHarness.close(); } List<Object> expectedOutput = new ArrayList<>(); expectedOutput.add(insertRecord(1, "a", 1, "Julian")); expectedOutput.add(insertRecord(3, "c", 3, "Jackson")); expectedOutput.add(insertRecord(4, "d", 4, "Fabian")); checkResult(expectedOutput, testHarness.getOutput()); } @TestTemplate void testTemporalLeftAsyncJoin() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createHarness(JoinType.LEFT_JOIN, FilterOnTable.WITHOUT_FILTER); testHarness.open(); synchronized (testHarness.getCheckpointLock()) { testHarness.processElement(insertRecord(1, "a")); testHarness.processElement(insertRecord(2, "b")); testHarness.processElement(insertRecord(3, "c")); testHarness.processElement(insertRecord(4, "d")); testHarness.processElement(insertRecord(5, "e")); testHarness.processElement(insertRecord(6, null)); } // wait until all async collectors in the buffer have been emitted out. synchronized (testHarness.getCheckpointLock()) { testHarness.endInput(); testHarness.close(); } List<Object> expectedOutput = new ArrayList<>(); expectedOutput.add(insertRecord(1, "a", 1, "Julian")); expectedOutput.add(insertRecord(2, "b", null, null)); expectedOutput.add(insertRecord(3, "c", 3, "Jark")); expectedOutput.add(insertRecord(3, "c", 3, "Jackson")); expectedOutput.add(insertRecord(4, "d", 4, "Fabian")); expectedOutput.add(insertRecord(5, "e", null, null)); expectedOutput.add(insertRecord(6, null, null, null)); checkResult(expectedOutput, testHarness.getOutput()); } @TestTemplate void testTemporalLeftAsyncJoinWithFilter() throws Exception { OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = createHarness(JoinType.LEFT_JOIN, FilterOnTable.WITH_FILTER); testHarness.open(); synchronized (testHarness.getCheckpointLock()) { testHarness.processElement(insertRecord(1, "a")); testHarness.processElement(insertRecord(2, "b")); testHarness.processElement(insertRecord(3, "c")); testHarness.processElement(insertRecord(4, "d")); testHarness.processElement(insertRecord(5, "e")); testHarness.processElement(insertRecord(6, null)); } // wait until all async collectors in the buffer have been emitted out. synchronized (testHarness.getCheckpointLock()) { testHarness.endInput(); testHarness.close(); } List<Object> expectedOutput = new ArrayList<>(); expectedOutput.add(insertRecord(1, "a", 1, "Julian")); expectedOutput.add(insertRecord(2, "b", null, null)); expectedOutput.add(insertRecord(3, "c", 3, "Jackson")); expectedOutput.add(insertRecord(4, "d", 4, "Fabian")); expectedOutput.add(insertRecord(5, "e", null, null)); expectedOutput.add(insertRecord(6, null, null, null)); checkResult(expectedOutput, testHarness.getOutput()); } // --------------------------------------------------------------------------------- private void checkResult(Collection<Object> expectedOutput, Collection<Object> actualOutput) { if (orderedResult) { assertor.assertOutputEquals("output wrong.", expectedOutput, actualOutput); } else { assertor.assertOutputEqualsSorted("output wrong.", expectedOutput, actualOutput); } } @SuppressWarnings({"unchecked", "rawtypes"}) private OneInputStreamOperatorTestHarness<RowData, RowData> createHarness( JoinType joinType, FilterOnTable filterOnTable) throws Exception { RichAsyncFunction<RowData, RowData> joinRunner; boolean isLeftJoin = joinType == JoinType.LEFT_JOIN; if (filterOnTable == FilterOnTable.WITHOUT_FILTER) { joinRunner = new AsyncLookupJoinRunner( new GeneratedFunctionWrapper(new TestingFetcherFunction()), fetcherConverter, new GeneratedResultFutureWrapper<>(new TestingFetcherResultFuture()), new GeneratedFunctionWrapper( new LookupJoinHarnessTest.TestingPreFilterCondition()), rightRowSerializer, isLeftJoin, ASYNC_BUFFER_CAPACITY); } else { joinRunner = new AsyncLookupJoinWithCalcRunner( new GeneratedFunctionWrapper(new TestingFetcherFunction()), fetcherConverter, new GeneratedFunctionWrapper<>(new CalculateOnTemporalTable()), new GeneratedResultFutureWrapper<>(new TestingFetcherResultFuture()), new GeneratedFunctionWrapper( new LookupJoinHarnessTest.TestingPreFilterCondition()), rightRowSerializer, isLeftJoin, ASYNC_BUFFER_CAPACITY); } return new OneInputStreamOperatorTestHarness<>( new AsyncWaitOperatorFactory<>( joinRunner, ASYNC_TIMEOUT_MS, ASYNC_BUFFER_CAPACITY, orderedResult ? AsyncDataStream.OutputMode.ORDERED : AsyncDataStream.OutputMode.UNORDERED), inSerializer); } @TestTemplate void testCloseAsyncLookupJoinRunner() throws Exception { final AsyncLookupJoinRunner joinRunner = new AsyncLookupJoinRunner( new GeneratedFunctionWrapper(new TestingFetcherFunction()), fetcherConverter, new GeneratedResultFutureWrapper<>(new TestingFetcherResultFuture()), new GeneratedFunctionWrapper( new LookupJoinHarnessTest.TestingPreFilterCondition()), rightRowSerializer, true, 100); assertThat(joinRunner.getAllResultFutures()).isNull(); closeAsyncLookupJoinRunner(joinRunner); joinRunner.setRuntimeContext(new MockStreamingRuntimeContext(1, 0)); joinRunner.open(DefaultOpenContext.INSTANCE); assertThat(joinRunner.getAllResultFutures()).isNotNull(); closeAsyncLookupJoinRunner(joinRunner); joinRunner.open(DefaultOpenContext.INSTANCE); joinRunner.asyncInvoke(row(1, "a"), new TestingFetcherResultFuture()); assertThat(joinRunner.getAllResultFutures()).isNotNull(); closeAsyncLookupJoinRunner(joinRunner); } private void closeAsyncLookupJoinRunner(AsyncLookupJoinRunner joinRunner) throws Exception { try { joinRunner.close(); } catch (NullPointerException e) { fail("Unexpected close to fail with null pointer exception."); } } /** Whether this is a inner join or left join. */ private
AsyncLookupJoinHarnessTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/Attribute.java
{ "start": 12268, "end": 16812 }
class ____ which this attribute must be added. This parameter can be used * to add the items that corresponds to this attribute to the constant pool of this class. * @param code the bytecode of the method corresponding to this Code attribute, or {@literal null} * if this attribute is not a Code attribute. Corresponds to the 'code' field of the Code * attribute. * @param codeLength the length of the bytecode of the method corresponding to this code * attribute, or 0 if this attribute is not a Code attribute. Corresponds to the 'code_length' * field of the Code attribute. * @param maxStack the maximum stack size of the method corresponding to this Code attribute, or * -1 if this attribute is not a Code attribute. * @param maxLocals the maximum number of local variables of the method corresponding to this code * attribute, or -1 if this attribute is not a Code attribute. * @return the byte array form of this attribute. */ public static byte[] write( final Attribute attribute, final ClassWriter classWriter, final byte[] code, final int codeLength, final int maxStack, final int maxLocals) { ByteVector content = attribute.maybeWrite(classWriter, code, codeLength, maxStack, maxLocals); byte[] result = new byte[content.length]; System.arraycopy(content.data, 0, result, 0, content.length); return result; } /** * Returns the number of attributes of the attribute list that begins with this attribute. * * @return the number of attributes of the attribute list that begins with this attribute. */ final int getAttributeCount() { int count = 0; Attribute attribute = this; while (attribute != null) { count += 1; attribute = attribute.nextAttribute; } return count; } /** * Returns the total size in bytes of all the attributes in the attribute list that begins with * this attribute. This size includes the 6 header bytes (attribute_name_index and * attribute_length) per attribute. Also adds the attribute type names to the constant pool. * * @param symbolTable where the constants used in the attributes must be stored. * @return the size of all the attributes in this attribute list. This size includes the size of * the attribute headers. */ final int computeAttributesSize(final SymbolTable symbolTable) { final byte[] code = null; final int codeLength = 0; final int maxStack = -1; final int maxLocals = -1; return computeAttributesSize(symbolTable, code, codeLength, maxStack, maxLocals); } /** * Returns the total size in bytes of all the attributes in the attribute list that begins with * this attribute. This size includes the 6 header bytes (attribute_name_index and * attribute_length) per attribute. Also adds the attribute type names to the constant pool. * * @param symbolTable where the constants used in the attributes must be stored. * @param code the bytecode of the method corresponding to these Code attributes, or {@literal * null} if they are not Code attributes. Corresponds to the 'code' field of the Code * attribute. * @param codeLength the length of the bytecode of the method corresponding to these code * attributes, or 0 if they are not Code attributes. Corresponds to the 'code_length' field of * the Code attribute. * @param maxStack the maximum stack size of the method corresponding to these Code attributes, or * -1 if they are not Code attributes. * @param maxLocals the maximum number of local variables of the method corresponding to these * Code attributes, or -1 if they are not Code attribute. * @return the size of all the attributes in this attribute list. This size includes the size of * the attribute headers. */ final int computeAttributesSize( final SymbolTable symbolTable, final byte[] code, final int codeLength, final int maxStack, final int maxLocals) { final ClassWriter classWriter = symbolTable.classWriter; int size = 0; Attribute attribute = this; while (attribute != null) { symbolTable.addConstantUtf8(attribute.type); size += 6 + attribute.maybeWrite(classWriter, code, codeLength, maxStack, maxLocals).length; attribute = attribute.nextAttribute; } return size; } /** * Returns the total size in bytes of all the attributes that correspond to the given field, * method or
to