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
spring-projects__spring-boot
module/spring-boot-webservices-test/src/main/java/org/springframework/boot/webservices/test/autoconfigure/client/AutoConfigureWebServiceClient.java
{ "start": 1262, "end": 1553 }
class ____ enable and configure * auto-configuration of web service clients. * * @author Dmytro Nosan * @since 2.3.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @ImportAutoConfiguration @PropertyMapping("spring.test.webservice.client") public @
to
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/AWSClientIOException.java
{ "start": 1045, "end": 1821 }
class ____ extends IOException { private final String operation; public AWSClientIOException(String operation, SdkException cause) { super(cause); Preconditions.checkArgument(operation != null, "Null 'operation' argument"); Preconditions.checkArgument(cause != null, "Null 'cause' argument"); this.operation = operation; } public SdkException getCause() { return (SdkException) super.getCause(); } @Override public String getMessage() { return operation + ": " + getCause().getMessage(); } /** * Query inner cause for retryability. * @return what the cause says. */ public boolean retryable() { return getCause().retryable(); } public String getOperation() { return operation; } }
AWSClientIOException
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/stream/sql/TableLineageGraphTest.java
{ "start": 1112, "end": 1386 }
class ____ extends TableLineageGraphTestBase { @Override protected TableTestUtil getTableTestUtil() { return streamTestUtil(TableConfig.getDefault()); } @Override protected boolean isBatchMode() { return false; } }
TableLineageGraphTest
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/EncryptedPemWithWrongPasswordTest.java
{ "start": 863, "end": 1733 }
class ____ { private static final String configuration = """ quarkus.tls.key-store.pem.foo.cert=target/certs/test-formats-encrypted-pem.crt quarkus.tls.key-store.pem.foo.key=target/certs/test-formats-encrypted-pem.key quarkus.tls.key-store.pem.foo.password=wrong """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .add(new StringAsset(configuration), "application.properties")) .assertException(t -> assertThat(t.getMessage()).contains("key/certificate pair", "default")); @Test void test() throws KeyStoreException, CertificateParsingException { fail("Should not be called as the extension should fail before."); } }
EncryptedPemWithWrongPasswordTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/HdfsPartialListing.java
{ "start": 1285, "end": 2474 }
class ____ { private final List<HdfsFileStatus> partialListing; private final int parentIdx; private final RemoteException exception; public HdfsPartialListing( int parentIdx, List<HdfsFileStatus> partialListing) { this(parentIdx, partialListing, null); } public HdfsPartialListing( int parentIdx, RemoteException exception) { this(parentIdx, null, exception); } private HdfsPartialListing( int parentIdx, List<HdfsFileStatus> partialListing, RemoteException exception) { Preconditions.checkArgument(partialListing == null ^ exception == null); this.parentIdx = parentIdx; this.partialListing = partialListing; this.exception = exception; } public int getParentIdx() { return parentIdx; } public List<HdfsFileStatus> getPartialListing() { return partialListing; } public RemoteException getException() { return exception; } @Override public String toString() { return new ToStringBuilder(this) .append("partialListing", partialListing) .append("parentIdx", parentIdx) .append("exception", exception) .toString(); } }
HdfsPartialListing
java
processing__processing4
app/src/processing/app/Util.java
{ "start": 21215, "end": 21866 }
class ____ in there // https://github.com/processing/processing/issues/5778 if (name.endsWith(".class") && !name.contains("META-INF/")) { int slash = name.lastIndexOf('/'); if (slash != -1) { String packageName = name.substring(0, slash); list.appendUnique(packageName); } } } } file.close(); } catch (IOException e) { System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); //e.printStackTrace(); } } /** * Make list of package names by traversing a directory hierarchy. * Each time a
files
java
mockito__mockito
mockito-extensions/mockito-junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
{ "start": 3591, "end": 4005 }
class ____ { @Mock Object nestedMock; @Mock ArgumentCaptor<String> nestedCaptor; @Test void ensure_mocks_are_created_for_nested_tests() { assertThat(nestedMock).isNotNull(); } @Test void ensure_captor_is_created_for_nested_tests() { assertThat(nestedCaptor).isNotNull(); } } @Nested
DuplicateExtensionOnNestedTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/JobResourceRequirementsBody.java
{ "start": 2101, "end": 3645 }
class ____ implements RequestBody, ResponseBody { @JsonAnySetter @JsonAnyGetter @JsonSerialize(keyUsing = JobVertexIDKeySerializer.class) @JsonDeserialize(keyUsing = JobVertexIDKeyDeserializer.class) private final Map<JobVertexID, JobVertexResourceRequirements> jobVertexResourceRequirements; public JobResourceRequirementsBody() { this(null); } public JobResourceRequirementsBody(@Nullable JobResourceRequirements jobResourceRequirements) { if (jobResourceRequirements != null) { this.jobVertexResourceRequirements = jobResourceRequirements.getJobVertexParallelisms(); } else { this.jobVertexResourceRequirements = new HashMap<>(); } } @JsonIgnore public Optional<JobResourceRequirements> asJobResourceRequirements() { if (jobVertexResourceRequirements.isEmpty()) { return Optional.empty(); } return Optional.of(new JobResourceRequirements(jobVertexResourceRequirements)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JobResourceRequirementsBody that = (JobResourceRequirementsBody) o; return Objects.equals(jobVertexResourceRequirements, that.jobVertexResourceRequirements); } @Override public int hashCode() { return Objects.hash(jobVertexResourceRequirements); } }
JobResourceRequirementsBody
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/suggest/completion/GeoContextMappingTests.java
{ "start": 2209, "end": 20315 }
class ____ extends MapperServiceTestCase { @Override protected IndexAnalyzers createIndexAnalyzers(IndexSettings indexSettings) { return IndexAnalyzers.of( Map.of( "default", new NamedAnalyzer("default", AnalyzerScope.INDEX, new StandardAnalyzer()), "simple", new NamedAnalyzer("simple", AnalyzerScope.INDEX, new SimpleAnalyzer()) ) ); } public void testIndexingWithNoContexts() throws Exception { XContentBuilder mapping = jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("completion") .field("type", "completion") .startArray("contexts") .startObject() .field("name", "ctx") .field("type", "geo") .endObject() .endArray() .endObject() .endObject() .endObject() .endObject(); MapperService mapperService = createMapperService(mapping); MappedFieldType completionFieldType = mapperService.fieldType("completion"); ParsedDocument parsedDocument = mapperService.documentMapper() .parse( new SourceToParse( "1", BytesReference.bytes( jsonBuilder().startObject() .startArray("completion") .startObject() .array("input", "suggestion1", "suggestion2") .field("weight", 3) .endObject() .startObject() .array("input", "suggestion3", "suggestion4") .field("weight", 4) .endObject() .startObject() .array("input", "suggestion5", "suggestion6", "suggestion7") .field("weight", 5) .endObject() .endArray() .endObject() ), XContentType.JSON ) ); List<IndexableField> fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); assertContextSuggestFields(fields, 7); } public void testIndexingWithSimpleContexts() throws Exception { XContentBuilder mapping = jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("completion") .field("type", "completion") .startArray("contexts") .startObject() .field("name", "ctx") .field("type", "geo") .endObject() .endArray() .endObject() .endObject() .endObject() .endObject(); MapperService mapperService = createMapperService(mapping); MappedFieldType completionFieldType = mapperService.fieldType("completion"); ParsedDocument parsedDocument = mapperService.documentMapper() .parse( new SourceToParse( "1", BytesReference.bytes( jsonBuilder().startObject() .startArray("completion") .startObject() .array("input", "suggestion5", "suggestion6", "suggestion7") .startObject("contexts") .startObject("ctx") .field("lat", 43.6624803) .field("lon", -79.3863353) .endObject() .endObject() .field("weight", 5) .endObject() .endArray() .endObject() ), XContentType.JSON ) ); List<IndexableField> fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); assertContextSuggestFields(fields, 3); } public void testIndexingWithContextList() throws Exception { XContentBuilder mapping = jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("completion") .field("type", "completion") .startArray("contexts") .startObject() .field("name", "ctx") .field("type", "geo") .endObject() .endArray() .endObject() .endObject() .endObject() .endObject(); MapperService mapperService = createMapperService(mapping); MappedFieldType completionFieldType = mapperService.fieldType("completion"); ParsedDocument parsedDocument = mapperService.documentMapper() .parse( new SourceToParse( "1", BytesReference.bytes( jsonBuilder().startObject() .startObject("completion") .array("input", "suggestion5", "suggestion6", "suggestion7") .startObject("contexts") .startArray("ctx") .startObject() .field("lat", 43.6624803) .field("lon", -79.3863353) .endObject() .startObject() .field("lat", 43.6624718) .field("lon", -79.3873227) .endObject() .endArray() .endObject() .field("weight", 5) .endObject() .endObject() ), XContentType.JSON ) ); List<IndexableField> fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); assertContextSuggestFields(fields, 3); } public void testIndexingWithMultipleContexts() throws Exception { XContentBuilder mapping = jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("completion") .field("type", "completion") .startArray("contexts") .startObject() .field("name", "loc1") .field("type", "geo") .endObject() .startObject() .field("name", "loc2") .field("type", "geo") .endObject() .endArray() .endObject() .endObject() .endObject() .endObject(); MapperService mapperService = createMapperService(mapping); MappedFieldType completionFieldType = mapperService.fieldType("completion"); XContentBuilder builder = jsonBuilder().startObject() .startArray("completion") .startObject() .array("input", "suggestion5", "suggestion6", "suggestion7") .field("weight", 5) .startObject("contexts") .array("loc1", "ezs42e44yx96") .array("loc2", "wh0n9447fwrc") .endObject() .endObject() .endArray() .endObject(); ParsedDocument parsedDocument = mapperService.documentMapper() .parse(new SourceToParse("1", BytesReference.bytes(builder), XContentType.JSON)); List<IndexableField> fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); assertContextSuggestFields(fields, 3); } public void testMalformedGeoField() throws Exception { XContentBuilder mapping = jsonBuilder(); mapping.startObject(); mapping.startObject("_doc"); mapping.startObject("properties"); mapping.startObject("pin"); String type = randomFrom("text", "keyword", "long"); mapping.field("type", type); mapping.endObject(); mapping.startObject("suggestion"); mapping.field("type", "completion"); mapping.field("analyzer", "simple"); mapping.startArray("contexts"); mapping.startObject(); mapping.field("name", "st"); mapping.field("type", "geo"); mapping.field("path", "pin"); mapping.field("precision", 5); mapping.endObject(); mapping.endArray(); mapping.endObject(); mapping.endObject(); mapping.endObject(); mapping.endObject(); ElasticsearchParseException ex = expectThrows(ElasticsearchParseException.class, () -> createMapperService(mapping)); assertThat(ex.getMessage(), equalTo("field [pin] referenced in context [st] must be mapped to geo_point, found [" + type + "]")); } public void testMissingGeoField() throws Exception { XContentBuilder mapping = jsonBuilder(); mapping.startObject(); mapping.startObject("_doc"); mapping.startObject("properties"); mapping.startObject("suggestion"); mapping.field("type", "completion"); mapping.field("analyzer", "simple"); mapping.startArray("contexts"); mapping.startObject(); mapping.field("name", "st"); mapping.field("type", "geo"); mapping.field("path", "pin"); mapping.field("precision", 5); mapping.endObject(); mapping.endArray(); mapping.endObject(); mapping.endObject(); mapping.endObject(); mapping.endObject(); ElasticsearchParseException ex = expectThrows(ElasticsearchParseException.class, () -> createMapperService(mapping)); assertThat(ex.getMessage(), equalTo("field [pin] referenced in context [st] is not defined in the mapping")); } public void testParsingQueryContextBasic() throws Exception { XContentBuilder builder = jsonBuilder().value("ezs42e44yx96"); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); assertThat(internalQueryContexts.size(), equalTo(1 + 8)); Collection<String> locations = new ArrayList<>(); locations.add("ezs42e"); addNeighborsAtLevel("ezs42e", GeoContextMapping.DEFAULT_PRECISION, locations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { assertThat(internalQueryContext.context(), is(in(locations))); assertThat(internalQueryContext.boost(), equalTo(1)); assertThat(internalQueryContext.isPrefix(), equalTo(false)); } } public void testParsingQueryContextGeoPoint() throws Exception { XContentBuilder builder = jsonBuilder().startObject().field("lat", 23.654242).field("lon", 90.047153).endObject(); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); assertThat(internalQueryContexts.size(), equalTo(1 + 8)); Collection<String> locations = new ArrayList<>(); locations.add("wh0n94"); addNeighborsAtLevel("wh0n94", GeoContextMapping.DEFAULT_PRECISION, locations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { assertThat(internalQueryContext.context(), is(in(locations))); assertThat(internalQueryContext.boost(), equalTo(1)); assertThat(internalQueryContext.isPrefix(), equalTo(false)); } } public void testParsingQueryContextObject() throws Exception { XContentBuilder builder = jsonBuilder().startObject() .startObject("context") .field("lat", 23.654242) .field("lon", 90.047153) .endObject() .field("boost", 10) .array("neighbours", 1, 2, 3) .endObject(); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); assertThat(internalQueryContexts.size(), equalTo(1 + 1 + 8 + 1 + 8 + 1 + 8)); Collection<String> locations = new ArrayList<>(); locations.add("wh0n94"); locations.add("w"); addNeighborsAtLevel("w", 1, locations); locations.add("wh"); addNeighborsAtLevel("wh", 2, locations); locations.add("wh0"); addNeighborsAtLevel("wh0", 3, locations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { assertThat(internalQueryContext.context(), is(in(locations))); assertThat(internalQueryContext.boost(), equalTo(10)); assertThat( internalQueryContext.isPrefix(), equalTo(internalQueryContext.context().length() < GeoContextMapping.DEFAULT_PRECISION) ); } } public void testParsingQueryContextObjectArray() throws Exception { XContentBuilder builder = jsonBuilder().startArray() .startObject() .startObject("context") .field("lat", 23.654242) .field("lon", 90.047153) .endObject() .field("boost", 10) .array("neighbours", 1, 2, 3) .endObject() .startObject() .startObject("context") .field("lat", 22.337374) .field("lon", 92.112583) .endObject() .field("boost", 2) .array("neighbours", 5) .endObject() .endArray(); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); assertThat(internalQueryContexts.size(), equalTo(1 + 1 + 8 + 1 + 8 + 1 + 8 + 1 + 1 + 8)); Collection<String> firstLocations = new ArrayList<>(); firstLocations.add("wh0n94"); firstLocations.add("w"); addNeighborsAtLevel("w", 1, firstLocations); firstLocations.add("wh"); addNeighborsAtLevel("wh", 2, firstLocations); firstLocations.add("wh0"); addNeighborsAtLevel("wh0", 3, firstLocations); Collection<String> secondLocations = new ArrayList<>(); secondLocations.add("w5cx04"); secondLocations.add("w5cx0"); addNeighborsAtLevel("w5cx0", 5, secondLocations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { if (firstLocations.contains(internalQueryContext.context())) { assertThat(internalQueryContext.boost(), equalTo(10)); } else if (secondLocations.contains(internalQueryContext.context())) { assertThat(internalQueryContext.boost(), equalTo(2)); } else { fail(internalQueryContext.context() + " was not expected"); } assertThat( internalQueryContext.isPrefix(), equalTo(internalQueryContext.context().length() < GeoContextMapping.DEFAULT_PRECISION) ); } } public void testParsingQueryContextMixed() throws Exception { XContentBuilder builder = jsonBuilder().startArray() .startObject() .startObject("context") .field("lat", 23.654242) .field("lon", 90.047153) .endObject() .field("boost", 10) .array("neighbours", 1, 2) .endObject() .startObject() .field("lat", 22.337374) .field("lon", 92.112583) .endObject() .endArray(); XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder)); GeoContextMapping mapping = ContextBuilder.geo("geo").build(); List<ContextMapping.InternalQueryContext> internalQueryContexts = mapping.parseQueryContext(parser); assertThat(internalQueryContexts.size(), equalTo(1 + 1 + 8 + 1 + 8 + 1 + 8)); Collection<String> firstLocations = new ArrayList<>(); firstLocations.add("wh0n94"); firstLocations.add("w"); addNeighborsAtLevel("w", 1, firstLocations); firstLocations.add("wh"); addNeighborsAtLevel("wh", 2, firstLocations); Collection<String> secondLocations = new ArrayList<>(); secondLocations.add("w5cx04"); addNeighborsAtLevel("w5cx04", 6, secondLocations); for (ContextMapping.InternalQueryContext internalQueryContext : internalQueryContexts) { if (firstLocations.contains(internalQueryContext.context())) { assertThat(internalQueryContext.boost(), equalTo(10)); } else if (secondLocations.contains(internalQueryContext.context())) { assertThat(internalQueryContext.boost(), equalTo(1)); } else { fail(internalQueryContext.context() + " was not expected"); } assertThat( internalQueryContext.isPrefix(), equalTo(internalQueryContext.context().length() < GeoContextMapping.DEFAULT_PRECISION) ); } } }
GeoContextMappingTests
java
bumptech__glide
instrumentation/src/androidTest/java/com/bumptech/glide/LoadResourcesWithDownsamplerTest.java
{ "start": 9408, "end": 11175 }
class ____ implements DataFetcher<InputStream> { private InputStream inputStream; @Override public void loadData( @NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) { inputStream = getInputStreamForResource(context, resourceId); callback.onDataReady(inputStream); } private InputStream getInputStreamForResource(Context context, @DrawableRes int resourceId) { Resources resources = context.getResources(); try { Uri parse = Uri.parse( String.format( Locale.US, "%s://%s/%s/%s", ContentResolver.SCHEME_ANDROID_RESOURCE, resources.getResourcePackageName(resourceId), resources.getResourceTypeName(resourceId), resources.getResourceEntryName(resourceId))); return context.getContentResolver().openInputStream(parse); } catch (Resources.NotFoundException | FileNotFoundException e) { throw new IllegalArgumentException("Resource ID " + resourceId + " not found", e); } } @Override public void cleanup() { InputStream local = inputStream; if (local != null) { try { local.close(); } catch (IOException e) { // Ignored. } } } @Override public void cancel() { // Do nothing. } @NonNull @Override public Class<InputStream> getDataClass() { return InputStream.class; } @NonNull @Override public DataSource getDataSource() { return DataSource.LOCAL; } } } }
Fetcher
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/ObjectArrayTypeInfo.java
{ "start": 1389, "end": 5060 }
class ____<T, C> extends TypeInformation<T> { private static final long serialVersionUID = 1L; private final Class<T> arrayType; private final TypeInformation<C> componentInfo; private ObjectArrayTypeInfo(Class<T> arrayType, TypeInformation<C> componentInfo) { this.arrayType = checkNotNull(arrayType); this.componentInfo = checkNotNull(componentInfo); } // -------------------------------------------------------------------------------------------- @Override @PublicEvolving public boolean isBasicType() { return false; } @Override @PublicEvolving public boolean isTupleType() { return false; } @Override @PublicEvolving public int getArity() { return 1; } @Override @PublicEvolving public int getTotalFields() { return 1; } @SuppressWarnings("unchecked") @Override @PublicEvolving public Class<T> getTypeClass() { return arrayType; } @PublicEvolving public TypeInformation<C> getComponentInfo() { return componentInfo; } @Override @PublicEvolving public boolean isKeyType() { return false; } @SuppressWarnings("unchecked") @Override @PublicEvolving public TypeSerializer<T> createSerializer(SerializerConfig serializerConfig) { return (TypeSerializer<T>) new GenericArraySerializer<C>( componentInfo.getTypeClass(), componentInfo.createSerializer(serializerConfig)); } @Override public String toString() { return this.getClass().getSimpleName() + "<" + this.componentInfo + ">"; } @Override public boolean equals(Object obj) { if (obj instanceof ObjectArrayTypeInfo) { @SuppressWarnings("unchecked") ObjectArrayTypeInfo<T, C> objectArrayTypeInfo = (ObjectArrayTypeInfo<T, C>) obj; return objectArrayTypeInfo.canEqual(this) && arrayType == objectArrayTypeInfo.arrayType && componentInfo.equals(objectArrayTypeInfo.componentInfo); } else { return false; } } @Override public boolean canEqual(Object obj) { return obj instanceof ObjectArrayTypeInfo; } @Override public int hashCode() { return 31 * this.arrayType.hashCode() + this.componentInfo.hashCode(); } // -------------------------------------------------------------------------------------------- @PublicEvolving public static <T, C> ObjectArrayTypeInfo<T, C> getInfoFor( Class<T> arrayClass, TypeInformation<C> componentInfo) { checkNotNull(arrayClass); checkNotNull(componentInfo); checkArgument(arrayClass.isArray(), "Class " + arrayClass + " must be an array."); return new ObjectArrayTypeInfo<T, C>(arrayClass, componentInfo); } /** * Creates a new {@link org.apache.flink.api.java.typeutils.ObjectArrayTypeInfo} from a {@link * TypeInformation} for the component type. * * <p>This must be used in cases where the complete type of the array is not available as a * {@link java.lang.reflect.Type} or {@link java.lang.Class}. */ @SuppressWarnings("unchecked") @PublicEvolving public static <T, C> ObjectArrayTypeInfo<T, C> getInfoFor(TypeInformation<C> componentInfo) { checkNotNull(componentInfo); return new ObjectArrayTypeInfo<T, C>( (Class<T>) Array.newInstance(componentInfo.getTypeClass(), 0).getClass(), componentInfo); } }
ObjectArrayTypeInfo
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/abilities/sink/BucketingSpec.java
{ "start": 1290, "end": 1432 }
interface ____ implemented again during deserialization */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeName("Bucketing") public final
is
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/elastic/ccm/CCMAuthenticationApplierFactoryTests.java
{ "start": 1115, "end": 5903 }
class ____ extends ESTestCase { public static CCMAuthenticationApplierFactory createNoopApplierFactory() { var mockFactory = mock(CCMAuthenticationApplierFactory.class); doAnswer(invocation -> { ActionListener<CCMAuthenticationApplierFactory.AuthApplier> listener = invocation.getArgument(0); listener.onResponse(CCMAuthenticationApplierFactory.NOOP_APPLIER); return Void.TYPE; }).when(mockFactory).getAuthenticationApplier(any()); return mockFactory; } public static CCMAuthenticationApplierFactory createApplierFactory(String secret) { var mockFactory = mock(CCMAuthenticationApplierFactory.class); doAnswer(invocation -> { ActionListener<CCMAuthenticationApplierFactory.AuthApplier> listener = invocation.getArgument(0); listener.onResponse(new CCMAuthenticationApplierFactory.AuthenticationHeaderApplier(secret)); return Void.TYPE; }).when(mockFactory).getAuthenticationApplier(any()); return mockFactory; } public void testNoopApplierReturnsSameRequest() { var applier = CCMAuthenticationApplierFactory.NOOP_APPLIER; var request = new HttpGet("http://localhost"); var result = applier.apply(request); assertThat(result, sameInstance(request)); } public void testAuthenticationHeaderApplierSetsAuthorizationHeader() { var secret = "my-secret"; var applier = new CCMAuthenticationApplierFactory.AuthenticationHeaderApplier(secret); var request = new HttpGet("http://localhost"); applier.apply(request); assertThat(request.getFirstHeader(HttpHeaders.AUTHORIZATION).getValue(), is(apiKey(secret))); } public void testGetAuthenticationApplier_ReturnsNoopWhenConfiguringCCMIsDisabled() { var ccmFeature = mock(CCMFeature.class); when(ccmFeature.isCcmSupportedEnvironment()).thenReturn(false); var ccmService = mock(CCMService.class); var factory = new CCMAuthenticationApplierFactory(ccmFeature, ccmService); var listener = new TestPlainActionFuture<CCMAuthenticationApplierFactory.AuthApplier>(); factory.getAuthenticationApplier(listener); assertThat(listener.actionGet(TimeValue.THIRTY_SECONDS), sameInstance(CCMAuthenticationApplierFactory.NOOP_APPLIER)); } public void testGetAuthenticationApplier_ReturnsFailure_WhenConfiguringCCMIsEnabled_ButHasNotBeenConfiguredYet() { var ccmFeature = mock(CCMFeature.class); when(ccmFeature.isCcmSupportedEnvironment()).thenReturn(true); var ccmService = mock(CCMService.class); doAnswer(invocation -> { ActionListener<Boolean> listener = invocation.getArgument(0); listener.onResponse(false); return Void.TYPE; }).when(ccmService).isEnabled(any()); var factory = new CCMAuthenticationApplierFactory(ccmFeature, ccmService); var listener = new TestPlainActionFuture<CCMAuthenticationApplierFactory.AuthApplier>(); factory.getAuthenticationApplier(listener); var exception = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TimeValue.THIRTY_SECONDS)); assertThat( exception.getMessage(), containsString( "Cloud connected mode is not configured, please configure it using PUT _inference/_ccm " + "before accessing the Elastic Inference Service." ) ); } public void testGetAuthenticationApplier_ReturnsApiKey_WhenConfiguringCCMIsEnabled_AndSet() { var secret = "secret"; var ccmFeature = mock(CCMFeature.class); when(ccmFeature.isCcmSupportedEnvironment()).thenReturn(true); var ccmService = mock(CCMService.class); doAnswer(invocation -> { ActionListener<Boolean> listener = invocation.getArgument(0); listener.onResponse(true); return Void.TYPE; }).when(ccmService).isEnabled(any()); doAnswer(invocation -> { ActionListener<CCMModel> listener = invocation.getArgument(0); listener.onResponse(new CCMModel(new SecureString(secret.toCharArray()))); return Void.TYPE; }).when(ccmService).getConfiguration(any()); var factory = new CCMAuthenticationApplierFactory(ccmFeature, ccmService); var listener = new TestPlainActionFuture<CCMAuthenticationApplierFactory.AuthApplier>(); factory.getAuthenticationApplier(listener); var applier = listener.actionGet(TimeValue.THIRTY_SECONDS); assertThat(applier, is(new CCMAuthenticationApplierFactory.AuthenticationHeaderApplier(secret))); } }
CCMAuthenticationApplierFactoryTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequestTests.java
{ "start": 1091, "end": 2768 }
class ____ extends ESTestCase { @SuppressWarnings("unchecked") public void testCreateRepositoryToXContent() throws IOException { Map<String, String> mapParams = new HashMap<>(); PutRepositoryRequest request = new PutRepositoryRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT); String repoName = "test"; request.name(repoName); mapParams.put("name", repoName); Boolean verify = randomBoolean(); request.verify(verify); mapParams.put("verify", verify.toString()); String type = FsRepository.TYPE; request.type(type); mapParams.put("type", type); Boolean addSettings = randomBoolean(); if (addSettings) { request.settings(Settings.builder().put(FsRepository.LOCATION_SETTING.getKey(), ".").build()); } XContentBuilder builder = jsonBuilder(); request.toXContent(builder, new ToXContent.MapParams(mapParams)); builder.flush(); Map<String, Object> outputMap = XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2(); assertThat(outputMap.get("name"), equalTo(request.name())); assertThat(outputMap.get("verify"), equalTo(request.verify())); assertThat(outputMap.get("type"), equalTo(request.type())); Map<String, Object> settings = (Map<String, Object>) outputMap.get("settings"); if (addSettings) { assertThat(settings.get(FsRepository.LOCATION_SETTING.getKey()), equalTo(".")); } else { assertTrue(((Map<String, Object>) outputMap.get("settings")).isEmpty()); } } }
PutRepositoryRequestTests
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/jta/DeleteCollectionJtaSessionClosedBeforeCommitTest.java
{ "start": 3431, "end": 4544 }
class ____ { @Id private Integer id; private String name; @OneToMany @JoinTable(name = "LINK_TABLE", joinColumns = @JoinColumn(name = "ENTITY_ID")) private List<OtherTestEntity> others = new ArrayList<>(); public TestEntity() { } public TestEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void addOther(OtherTestEntity other) { this.others.add( other ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } TestEntity that = (TestEntity) o; if ( getId() != null ? !getId().equals( that.getId() ) : that.getId() != null ) { return false; } return name != null ? name.equals( that.name ) : that.name == null; } @Override public int hashCode() { int result = getId() != null ? getId().hashCode() : 0; result = 31 * result + ( name != null ? name.hashCode() : 0 ); return result; } } @Audited @Entity @Table(name = "O_ENTITY") public static
TestEntity
java
grpc__grpc-java
api/src/main/java/io/grpc/MethodDescriptor.java
{ "start": 1374, "end": 2878 }
class ____<ReqT, RespT> { private final MethodType type; private final String fullMethodName; @Nullable private final String serviceName; private final Marshaller<ReqT> requestMarshaller; private final Marshaller<RespT> responseMarshaller; private final @Nullable Object schemaDescriptor; private final boolean idempotent; private final boolean safe; private final boolean sampledToLocalTracing; // Must be set to InternalKnownTransport.values().length // Not referenced to break the dependency. private final AtomicReferenceArray<Object> rawMethodNames = new AtomicReferenceArray<>(2); /** * Gets the cached "raw" method name for this Method Descriptor. The raw name is transport * specific, and should be set using {@link #setRawMethodName} by the transport. * * @param transportOrdinal the unique ID of the transport, given by * {@link InternalKnownTransport#ordinal}. * @return a transport specific representation of the method name. */ final Object getRawMethodName(int transportOrdinal) { return rawMethodNames.get(transportOrdinal); } /** * Safely, but weakly, sets the raw method name for this Method Descriptor. This should only be * called by the transport. See {@link #getRawMethodName} for more detail. */ final void setRawMethodName(int transportOrdinal, Object o) { rawMethodNames.lazySet(transportOrdinal, o); } /** * The call type of a method. * * @since 1.0.0 */ public
MethodDescriptor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/notfound/NotFoundTest.java
{ "start": 1073, "end": 1804 }
class ____ { @Test public void testManyToOne(SessionFactoryScope scope) { final Currency euro = new Currency(); euro.setName( "Euro" ); final Coin fiveCents = new Coin(); fiveCents.setName( "Five cents" ); fiveCents.setCurrency( euro ); scope.inTransaction( session -> { session.persist( euro ); session.persist( fiveCents ); } ); scope.inTransaction( session -> { Currency _euro = session.get( Currency.class, euro.getId() ); session.remove( _euro ); } ); scope.inTransaction( session -> { Coin _fiveCents = session.get( Coin.class, fiveCents.getId() ); assertNull( _fiveCents.getCurrency() ); session.remove( _fiveCents ); } ); } @Entity(name = "Coin") public static
NotFoundTest
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/legacy/TestInstancePerClassTest.java
{ "start": 1496, "end": 2399 }
class ____ extends CamelMainTestSupport { @Override protected Class<?> getMainClass() { return MyMainClass.class; } @Order(1) @Test void shouldBeLaunchedFirst() throws Exception { MockEndpoint mock = context.getEndpoint("mock:bean", MockEndpoint.class); mock.expectedBodiesReceived(1); int result = template.requestBody("direct:bean", null, Integer.class); mock.assertIsSatisfied(); assertEquals(1, result); } @Order(2) @Test void shouldBeLaunchedSecondWithDifferentResult() throws Exception { MockEndpoint mock = context.getEndpoint("mock:bean", MockEndpoint.class); mock.reset(); mock.expectedBodiesReceived(2); int result = template.requestBody("direct:bean", null, Integer.class); mock.assertIsSatisfied(); assertEquals(2, result); } }
TestInstancePerClassTest
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/NamedJKSTrustStoreWithCredentialsProviderTest.java
{ "start": 974, "end": 2310 }
class ____ { private static final String configuration = """ quarkus.tls.foo.trust-store.jks.path=target/certs/test-credentials-provider-truststore.jks quarkus.tls.foo.trust-store.credentials-provider.name=tls """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClass(MyCredentialProvider.class) .add(new StringAsset(configuration), "application.properties")); @Inject TlsConfigurationRegistry certificates; @Test void test() throws KeyStoreException, CertificateParsingException { TlsConfiguration def = certificates.get("foo").orElseThrow(); assertThat(def.getTrustStoreOptions()).isNotNull(); assertThat(def.getTrustStore()).isNotNull(); X509Certificate certificate = (X509Certificate) def.getTrustStore().getCertificate("test-credentials-provider"); assertThat(certificate).isNotNull(); assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> { assertThat(l.get(0)).isEqualTo(2); assertThat(l.get(1)).isEqualTo("localhost"); }); } @ApplicationScoped public static
NamedJKSTrustStoreWithCredentialsProviderTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/error/future/ShouldBeDone_create_Test.java
{ "start": 1028, "end": 1468 }
class ____ { @Test void should_create_error_message() { // WHEN String error = shouldBeDone(new CompletableFuture<>()).create(new TestDescription("TEST")); // THEN then(error).isEqualTo(format("[TEST] %n" + "Expecting%n" + " <CompletableFuture[Incomplete]>%n" + "to be done.%n%s", WARNING)); } }
ShouldBeDone_create_Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/Reverse.java
{ "start": 1509, "end": 5002 }
class ____ extends UnaryScalarFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Reverse", Reverse::new); @FunctionInfo( returnType = { "keyword" }, description = "Returns a new string representing the input string in reverse order.", examples = { @Example(file = "string", tag = "reverse"), @Example( file = "string", tag = "reverseEmoji", description = "`REVERSE` works with unicode, too! It keeps unicode grapheme clusters together during reversal." ) } ) public Reverse( Source source, @Param( name = "str", type = { "keyword", "text" }, description = "String expression. If `null`, the function returns `null`." ) Expression field ) { super(source, field); } private Reverse(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } return isString(field, sourceText(), DEFAULT); } /** * Reverses a unicode string, keeping grapheme clusters together */ public static String reverseStringWithUnicodeCharacters(String str) { BreakIterator boundary = BreakIterator.getCharacterInstance(Locale.ROOT); boundary.setText(str); List<String> characters = new ArrayList<>(); int start = boundary.first(); for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) { characters.add(str.substring(start, end)); } StringBuilder reversed = new StringBuilder(str.length()); for (int i = characters.size() - 1; i >= 0; i--) { reversed.append(characters.get(i)); } return reversed.toString(); } private static boolean reverseBytesIsReverseUnicode(BytesRef ref) { int end = ref.offset + ref.length; for (int i = ref.offset; i < end; i++) { if (ref.bytes[i] < 0 // Anything encoded in multibyte utf-8 || ref.bytes[i] == 0x28 // Backspace ) { return false; } } return true; } @Evaluator static BytesRef process(BytesRef val) { if (reverseBytesIsReverseUnicode(val)) { // this is the fast path. we know we can just reverse the bytes. BytesRef reversed = BytesRef.deepCopyOf(val); reverseArray(reversed.bytes, reversed.offset, reversed.length); return reversed; } return new BytesRef(reverseStringWithUnicodeCharacters(val.utf8ToString())); } @Override public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { var fieldEvaluator = toEvaluator.apply(field); return new ReverseEvaluator.Factory(source(), fieldEvaluator); } @Override public Expression replaceChildren(List<Expression> newChildren) { assert newChildren.size() == 1; return new Reverse(source(), newChildren.get(0)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, Reverse::new, field); } }
Reverse
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/plugin/internal/MavenPluginValidatorTest.java
{ "start": 1374, "end": 4657 }
class ____ extends AbstractCoreMavenComponentTestCase { @Inject private MavenPluginValidator mavenPluginValidator; protected String getProjectsDirectory() { return "src/test/projects/default-maven"; } @Test void testValidate() { Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", "jar", null, new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); descriptor.setGroupId("org.apache.maven.its.plugins"); descriptor.setArtifactId("maven-it-plugin"); descriptor.setVersion("0.1"); List<String> errors = new ArrayList<>(); mavenPluginValidator.validate(plugin, descriptor, errors); assertTrue( errors.isEmpty(), "Expected collection to be empty but had " + errors.size() + " elements: " + errors); } @Test void testInvalidGroupId() { Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", "jar", null, new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); descriptor.setGroupId("org.apache.maven.its.plugins.invalid"); descriptor.setArtifactId("maven-it-plugin"); descriptor.setVersion("0.1"); List<String> errors = new ArrayList<>(); mavenPluginValidator.validate(plugin, descriptor, errors); assertFalse(errors.isEmpty(), "Expected collection to not be empty but was empty"); } @Test void testInvalidArtifactId() { Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", "jar", null, new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); descriptor.setGroupId("org.apache.maven.its.plugins"); descriptor.setArtifactId("maven-it-plugin.invalid"); descriptor.setVersion("0.1"); List<String> errors = new ArrayList<>(); mavenPluginValidator.validate(plugin, descriptor, errors); assertFalse(errors.isEmpty(), "Expected collection to not be empty but was empty"); } @Test void testInvalidVersion() { Artifact plugin = new DefaultArtifact( "org.apache.maven.its.plugins", "maven-it-plugin", "0.1", "compile", "jar", null, new DefaultArtifactHandler("ignore")); PluginDescriptor descriptor = new PluginDescriptor(); descriptor.setGroupId("org.apache.maven.its.plugins"); descriptor.setArtifactId("maven-it-plugin"); List<String> errors = new ArrayList<>(); mavenPluginValidator.validate(plugin, descriptor, errors); assertFalse(errors.isEmpty(), "Expected collection to not be empty but was empty"); } }
MavenPluginValidatorTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/ErrorPage.java
{ "start": 1066, "end": 2382 }
class ____ extends HtmlPage { @Override protected void render(Page.HTML<__> html) { set(JQueryUI.ACCORDION_ID, "msg"); String title = "Sorry, got error "+ status(); html. title(title). link(root_url("static", "yarn.css")). __(JQueryUI.class). // an embedded sub-view style("#msg { margin: 1em auto; width: 88%; }", "#msg h1 { padding: 0.2em 1.5em; font: bold 1.3em serif; }"). div("#msg"). h1(title). div(). __("Please consult"). a("http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html", "RFC 2616").__(" for meanings of the error code.").__(). h1("Error Details"). pre(). __(errorDetails()).__().__().__(); } protected String errorDetails() { if (!$(ERROR_DETAILS).isEmpty()) { return $(ERROR_DETAILS); } if (error() != null) { return toStackTrace(error(), 1024 * 64); } return "No exception was thrown."; } public static String toStackTrace(Throwable error, int cutoff) { // default initial size is 32 chars CharArrayWriter buffer = new CharArrayWriter(8 * 1024); error.printStackTrace(new PrintWriter(buffer)); return buffer.size() < cutoff ? buffer.toString() : buffer.toString().substring(0, cutoff); } }
ErrorPage
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapKeyToOneInEmbeddedIdTest.java
{ "start": 1251, "end": 2631 }
class ____ { @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityC entityC = new EntityC( "entity_c" ); session.persist( entityC ); final EntityB entityB = new EntityB( new EntityBID( entityC, 1 ), "entity_b" ); session.persist( entityB ); final EntityA entityA = new EntityA( 1 ); entityA.getbEntities().put( entityC, entityB ); session.persist( entityA ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> { session.createMutationQuery( "delete from EntityA" ).executeUpdate(); session.createMutationQuery( "delete from EntityB" ).executeUpdate(); session.createMutationQuery( "delete from EntityC" ).executeUpdate(); } ); } @Test public void testMapping(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityA entityA = session.find( EntityA.class, 1 ); assertThat( entityA.getbEntities() ).hasSize( 1 ); final Map.Entry<EntityC, EntityB> entry = entityA.getbEntities().entrySet().iterator().next(); assertThat( entry.getKey().getName() ).isEqualTo( "entity_c" ); assertThat( entry.getValue().getName() ).isEqualTo( "entity_b" ); assertThat( entry.getValue().getId().getEntity() ).isSameAs( entry.getKey() ); } ); } @Entity( name = "EntityA" ) public static
MapKeyToOneInEmbeddedIdTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java
{ "start": 6982, "end": 7276 }
enum ____ used to classify whether a CaseTree includes a null and/or default. Referencing * JLS 21 §14.11.1, the `SwitchLabel:` production has specific rules applicable to null/default * cases: `case null, [default]` and `default`. All other scenarios are lumped into KIND_NEITHER. */
is
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxDetach.java
{ "start": 1650, "end": 3380 }
class ____<T> implements InnerOperator<T, T> { @Nullable CoreSubscriber<? super T> actual; @Nullable Subscription s; DetachSubscriber(CoreSubscriber<? super T> actual) { this.actual = actual; } @Override public Context currentContext() { return actual == null ? Context.empty() : actual.currentContext(); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return s; if (key == Attr.TERMINATED) return actual == null; if (key == Attr.CANCELLED) return actual == null && s == null; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return InnerOperator.super.scanUnsafe(key); } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; assert actual != null : "actual can not be null when onSubscribe is called"; actual.onSubscribe(this); } } @Override public void onNext(T t) { Subscriber<? super T> a = actual; if (a != null) { a.onNext(t); } } @Override public void onError(Throwable t) { Subscriber<? super T> a = actual; if (a != null) { actual = null; s = null; a.onError(t); } } @Override public @Nullable CoreSubscriber<? super T> actual() { return actual; } @Override public void onComplete() { Subscriber<? super T> a = actual; if (a != null) { actual = null; s = null; a.onComplete(); } } @Override public void request(long n) { Subscription a = s; if (a != null) { a.request(n); } } @Override public void cancel() { Subscription a = s; if (a != null) { actual = null; s = null; a.cancel(); } } } }
DetachSubscriber
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/AlmostJavadocTest.java
{ "start": 1818, "end": 2247 }
class ____ { /** Foo {@link Test}. */ void foo() {} /** * Bar. * * @param bar bar */ void bar(int bar) {} } """) .doTest(TEXT_MATCH); } @Test public void notJavadocButNoTag() { helper .addSourceLines( "Test.java", """ public
Test
java
apache__camel
components/camel-aws/camel-aws2-step-functions/src/generated/java/org/apache/camel/component/aws2/stepfunctions/StepFunctions2EndpointConfigurer.java
{ "start": 745, "end": 8722 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { StepFunctions2Endpoint target = (StepFunctions2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": target.getConfiguration().setAccessKey(property(camelContext, java.lang.String.class, value)); return true; case "awssfnclient": case "awsSfnClient": target.getConfiguration().setAwsSfnClient(property(camelContext, software.amazon.awssdk.services.sfn.SfnClient.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.aws2.stepfunctions.StepFunctions2Operations.class, value)); return true; case "overrideendpoint": case "overrideEndpoint": target.getConfiguration().setOverrideEndpoint(property(camelContext, boolean.class, value)); return true; case "pojorequest": case "pojoRequest": target.getConfiguration().setPojoRequest(property(camelContext, boolean.class, value)); return true; case "profilecredentialsname": case "profileCredentialsName": target.getConfiguration().setProfileCredentialsName(property(camelContext, java.lang.String.class, value)); return true; case "proxyhost": case "proxyHost": target.getConfiguration().setProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "proxyport": case "proxyPort": target.getConfiguration().setProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "proxyprotocol": case "proxyProtocol": target.getConfiguration().setProxyProtocol(property(camelContext, software.amazon.awssdk.core.Protocol.class, value)); return true; case "region": target.getConfiguration().setRegion(property(camelContext, java.lang.String.class, value)); return true; case "secretkey": case "secretKey": target.getConfiguration().setSecretKey(property(camelContext, java.lang.String.class, value)); return true; case "sessiontoken": case "sessionToken": target.getConfiguration().setSessionToken(property(camelContext, java.lang.String.class, value)); return true; case "trustallcertificates": case "trustAllCertificates": target.getConfiguration().setTrustAllCertificates(property(camelContext, boolean.class, value)); return true; case "uriendpointoverride": case "uriEndpointOverride": target.getConfiguration().setUriEndpointOverride(property(camelContext, java.lang.String.class, value)); return true; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": target.getConfiguration().setUseDefaultCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": target.getConfiguration().setUseProfileCredentialsProvider(property(camelContext, boolean.class, value)); return true; case "usesessioncredentials": case "useSessionCredentials": target.getConfiguration().setUseSessionCredentials(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"awsSfnClient"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return java.lang.String.class; case "awssfnclient": case "awsSfnClient": return software.amazon.awssdk.services.sfn.SfnClient.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return org.apache.camel.component.aws2.stepfunctions.StepFunctions2Operations.class; case "overrideendpoint": case "overrideEndpoint": return boolean.class; case "pojorequest": case "pojoRequest": return boolean.class; case "profilecredentialsname": case "profileCredentialsName": return java.lang.String.class; case "proxyhost": case "proxyHost": return java.lang.String.class; case "proxyport": case "proxyPort": return java.lang.Integer.class; case "proxyprotocol": case "proxyProtocol": return software.amazon.awssdk.core.Protocol.class; case "region": return java.lang.String.class; case "secretkey": case "secretKey": return java.lang.String.class; case "sessiontoken": case "sessionToken": return java.lang.String.class; case "trustallcertificates": case "trustAllCertificates": return boolean.class; case "uriendpointoverride": case "uriEndpointOverride": return java.lang.String.class; case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return boolean.class; case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return boolean.class; case "usesessioncredentials": case "useSessionCredentials": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { StepFunctions2Endpoint target = (StepFunctions2Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesskey": case "accessKey": return target.getConfiguration().getAccessKey(); case "awssfnclient": case "awsSfnClient": return target.getConfiguration().getAwsSfnClient(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getConfiguration().getOperation(); case "overrideendpoint": case "overrideEndpoint": return target.getConfiguration().isOverrideEndpoint(); case "pojorequest": case "pojoRequest": return target.getConfiguration().isPojoRequest(); case "profilecredentialsname": case "profileCredentialsName": return target.getConfiguration().getProfileCredentialsName(); case "proxyhost": case "proxyHost": return target.getConfiguration().getProxyHost(); case "proxyport": case "proxyPort": return target.getConfiguration().getProxyPort(); case "proxyprotocol": case "proxyProtocol": return target.getConfiguration().getProxyProtocol(); case "region": return target.getConfiguration().getRegion(); case "secretkey": case "secretKey": return target.getConfiguration().getSecretKey(); case "sessiontoken": case "sessionToken": return target.getConfiguration().getSessionToken(); case "trustallcertificates": case "trustAllCertificates": return target.getConfiguration().isTrustAllCertificates(); case "uriendpointoverride": case "uriEndpointOverride": return target.getConfiguration().getUriEndpointOverride(); case "usedefaultcredentialsprovider": case "useDefaultCredentialsProvider": return target.getConfiguration().isUseDefaultCredentialsProvider(); case "useprofilecredentialsprovider": case "useProfileCredentialsProvider": return target.getConfiguration().isUseProfileCredentialsProvider(); case "usesessioncredentials": case "useSessionCredentials": return target.getConfiguration().isUseSessionCredentials(); default: return null; } } }
StepFunctions2EndpointConfigurer
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/MoreAnnotationsTest.java
{ "start": 3903, "end": 3942 }
interface ____ {} @Target(TYPE_USE) @
Other
java
quarkusio__quarkus
test-framework/vertx/src/main/java/io/quarkus/test/vertx/RunOnVertxContextTestMethodInvoker.java
{ "start": 6226, "end": 8808 }
class ____ implements Handler<Void> { private static final Runnable DO_NOTHING = new Runnable() { @Override public void run() { } }; private final Object testInstance; private final Method targetMethod; private final List<Object> methodArgs; private final UnwrappableUniAsserter uniAsserter; private final CompletableFuture<Object> future; public RunTestMethodOnVertxEventLoopContextHandler(Object testInstance, Method targetMethod, List<Object> methodArgs, UniAsserter uniAsserter, CompletableFuture<Object> future) { this.testInstance = testInstance; this.future = future; this.targetMethod = targetMethod; this.methodArgs = methodArgs; this.uniAsserter = (UnwrappableUniAsserter) uniAsserter; } @Override public void handle(Void event) { ManagedContext requestContext = Arc.container().requestContext(); if (requestContext.isActive()) { doRun(DO_NOTHING); } else { requestContext.activate(); doRun(new Runnable() { @Override public void run() { requestContext.terminate(); } }); } } private void doRun(Runnable onTerminate) { try { Object testMethodResult = targetMethod.invoke(testInstance, methodArgs.toArray(new Object[0])); if (uniAsserter != null) { uniAsserter.asUni().subscribe().with(new Consumer<Object>() { @Override public void accept(Object o) { onTerminate.run(); future.complete(testMethodResult); } }, new Consumer<Throwable>() { @Override public void accept(Throwable t) { onTerminate.run(); future.completeExceptionally(t); } }); } else { onTerminate.run(); future.complete(testMethodResult); } } catch (Throwable t) { onTerminate.run(); future.completeExceptionally(t.getCause()); } } } public static
RunTestMethodOnVertxEventLoopContextHandler
java
spring-projects__spring-boot
integration-test/spring-boot-server-integration-tests/src/intTest/java/org/springframework/boot/context/embedded/AbstractApplicationLauncher.java
{ "start": 1239, "end": 1352 }
class ____ launching a Spring Boot application as part of a JUnit test. * * @author Andy Wilkinson */ abstract
for
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/filter/factory/cache/LocalResponseCacheProperties.java
{ "start": 1083, "end": 2357 }
class ____ { static final String PREFIX = "spring.cloud.gateway.server.webflux.filter.local-response-cache"; private static final Log LOGGER = LogFactory.getLog(LocalResponseCacheProperties.class); private static final Duration DEFAULT_CACHE_TTL_MINUTES = Duration.ofMinutes(5); private @Nullable DataSize size; private @Nullable Duration timeToLive; private RequestOptions request = new RequestOptions(); public @Nullable DataSize getSize() { return size; } public void setSize(DataSize size) { this.size = size; } public Duration getTimeToLive() { if (timeToLive == null) { LOGGER.debug(String.format( "No TTL configuration found. Default TTL will be applied for cache entries: %s minutes", DEFAULT_CACHE_TTL_MINUTES)); return DEFAULT_CACHE_TTL_MINUTES; } else { return timeToLive; } } public void setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; } public RequestOptions getRequest() { return request; } public void setRequest(RequestOptions request) { this.request = request; } @Override public String toString() { return "LocalResponseCacheProperties{" + "size=" + size + ", timeToLive=" + timeToLive + ", request=" + request + '}'; } public static
LocalResponseCacheProperties
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/utils/DummyStreamExecutionEnvironment.java
{ "start": 3367, "end": 3587 }
interface ____ reworked. * * <p>NOTE: Please remove {@code com.esotericsoftware.kryo} item in the whitelist of * checkCodeDependencies() method in {@code test_table_shaded_dependencies.sh} end-to-end test when * this
are
java
apache__spark
sql/core/src/main/java/org/apache/spark/sql/execution/datasources/parquet/ParquetVectorUpdaterFactory.java
{ "start": 44782, "end": 46068 }
class ____ implements ParquetVectorUpdater { private final int arrayLen; FixedLenByteArrayAsIntUpdater(int arrayLen) { this.arrayLen = arrayLen; } @Override public void readValues( int total, int offset, WritableColumnVector values, VectorizedValuesReader valuesReader) { for (int i = 0; i < total; i++) { readValue(offset + i, values, valuesReader); } } @Override public void skipValues(int total, VectorizedValuesReader valuesReader) { valuesReader.skipFixedLenByteArray(total, arrayLen); } @Override public void readValue( int offset, WritableColumnVector values, VectorizedValuesReader valuesReader) { int value = (int) ParquetRowConverter.binaryToUnscaledLong(valuesReader.readBinary(arrayLen)); values.putInt(offset, value); } @Override public void decodeSingleDictionaryId( int offset, WritableColumnVector values, WritableColumnVector dictionaryIds, Dictionary dictionary) { Binary v = dictionary.decodeToBinary(dictionaryIds.getDictId(offset)); values.putInt(offset, (int) ParquetRowConverter.binaryToUnscaledLong(v)); } } private static
FixedLenByteArrayAsIntUpdater
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/test/java/io/quarkus/smallrye/health/test/DispatchedThreadTest.java
{ "start": 2602, "end": 3033 }
class ____ implements HealthCheck { @Override public HealthCheckResponse call() { return HealthCheckResponse.named("my-readiness-check") .up() .withData("thread", Thread.currentThread().getName()) .withData("request", Arc.container().requestContext().isActive()) .build(); } } }
ReadinessHealthCheckCapturingThread
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/DoubleFieldTest_A.java
{ "start": 246, "end": 1236 }
class ____ extends TestCase { public void test_codec() throws Exception { User user = new User(); user.setValue(1001D); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user1.getValue(), user.getValue()); } public void test_codec_null() throws Exception { User user = new User(); user.setValue(null); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(user, mapping, SerializerFeature.WriteMapNullValue); System.out.println(text); User user1 = JSON.parseObject(text, User.class); Assert.assertEquals(user1.getValue(), user.getValue()); } public static
DoubleFieldTest_A
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamTestCase.java
{ "start": 1509, "end": 8404 }
class ____ { @TestHTTPResource URI uri; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) .addClasses(StreamResource.class, Message.class, Demands.class)); @Test public void testSseFromSse() throws Exception { testSse("streams"); } @Test public void testSseFromMulti() throws Exception { testSse("streams/multi"); } private void testSse(String path) throws Exception { Client client = ClientBuilder.newBuilder().build(); WebTarget target = client.target(uri.toString() + path); // do not reconnect try (SseEventSource eventSource = SseEventSource.target(target).reconnectingEvery(Integer.MAX_VALUE, TimeUnit.SECONDS) .build()) { CompletableFuture<List<String>> res = new CompletableFuture<>(); List<String> collect = Collections.synchronizedList(new ArrayList<>()); eventSource.register(new Consumer<InboundSseEvent>() { @Override public void accept(InboundSseEvent inboundSseEvent) { collect.add(inboundSseEvent.readData()); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { res.completeExceptionally(throwable); } }, () -> { res.complete(collect); }); eventSource.open(); assertThat(res.get(5, TimeUnit.SECONDS)).containsExactly("hello", "stef"); } } @Test public void testMultiFromSse() { testMulti("streams"); } @Test public void testMultiFromMulti() { testMulti("streams/multi"); } private void testMulti(String path) { Client client = ClientBuilder.newBuilder().build(); WebTarget target = client.target(uri.toString() + path); Multi<String> multi = target.request().rx(MultiInvoker.class).get(String.class); List<String> list = multi.collect().asList().await().atMost(Duration.ofSeconds(30)); assertThat(list).containsExactly("hello", "stef"); } @Test public void testJsonMultiFromSse() { testJsonMulti("streams/json"); testJsonMulti("streams/json2"); testJsonMulti("streams/blocking/json"); } @Test public void testJsonMultiFromMulti() { testJsonMulti("streams/json/multi"); testJsonMulti("streams/json/multi-alt"); } @Test public void testJsonMultiFromMultiWithDefaultElementType() { testJsonMulti("streams/json/multi2"); } @Test public void testJsonMultiMultiDoc() { when().get(uri.toString() + "streams/json/multi-docs") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(is("{\"name\":\"hello\"}\n" + "{\"name\":\"stef\"}\n")) // @formatter:on .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_JSON)); } @Test public void testJsonMultiMultiDocHigherDemand() { when().get(uri.toString() + "streams/json/multi-docs-huge-demand") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(allOf( containsString("{\"name\":\"hello\"}\n"), containsString("{\"name\":\"stef\"}\n"), containsString("{\"name\":\"snazy\"}\n"), containsString("{\"name\":\"elani\"}\n"), containsString("{\"name\":\"foo\"}\n"), containsString("{\"name\":\"bar\"}\n"), containsString("{\"name\":\"baz\"}\n"), endsWith("{\"demands\":[5,5]}\n"))) // @formatter:on .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_JSON)) .header("foo", equalTo("bar")); } @Test public void testNdJsonMultiFromMulti() { when().get(uri.toString() + "streams/ndjson/multi") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(is("{\"name\":\"hello\"}\n" + "{\"name\":\"stef\"}\n")) // @formatter:on .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_NDJSON)); } @Test public void testNdJsonMultiFromMulti2() { when().get(uri.toString() + "streams/ndjson/multi2") .then().statusCode(222) // @formatter:off .body(is("{\"name\":\"hello\"}\n" + "{\"name\":\"stef\"}\n")) // @formatter:on .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_NDJSON)) .header("foo", "bar"); } @Test public void testRestMultiEmptyJson() { when().get(uri.toString() + "streams/restmulti/empty") .then().statusCode(222) .body(is("[]")) .header("foo", "bar"); } @Test public void testStreamJsonMultiFromMulti() { when().get(uri.toString() + "streams/stream-json/multi") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(is("{\"name\":\"hello\"}\n" + "{\"name\":\"stef\"}\n")) // @formatter:on .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_STREAM_JSON)); } private void testJsonMulti(String path) { Client client = ClientBuilder.newBuilder().register(new JacksonBasicMessageBodyReader(new ObjectMapper())).build(); WebTarget target = client.target(uri.toString() + path); Multi<Message> multi = target.request().rx(MultiInvoker.class).get(Message.class); List<Message> list = multi.collect().asList().await().atMost(Duration.ofSeconds(30)); assertThat(list).extracting("name").containsExactly("hello", "stef"); } /** * Reproduce <a href="https://github.com/quarkusio/quarkus/issues/30044">#30044</a>. */ @Test public void testStreamJsonMultiFromMultiFast() { String payload = when().get(uri.toString() + "streams/stream-json/multi/fast") .then().statusCode(HttpStatus.SC_OK) .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_STREAM_JSON)) .extract().response().asString(); // the payload include 5000 json objects assertThat(payload.lines()).hasSize(5000) .allSatisfy(s -> assertThat(s).matches("\\{\"name\":\".*\"}")); } }
StreamTestCase
java
micronaut-projects__micronaut-core
http-server-netty/src/test/groovy/io/micronaut/http/server/netty/errors/handler/PropagatedContextExceptionHandlerTest.java
{ "start": 448, "end": 1820 }
class ____ { EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class, Map.of("spec.name", "PropagatedContextExceptionHandlerTest") ); HttpClient httpClient = embeddedServer.getApplicationContext().createBean(HttpClient.class, embeddedServer.getURL()); @Test void testNonBlockingPropagatingTrace() { HttpResponse<?> response; try { response = httpClient.toBlocking().exchange(HttpRequest.GET("/non-blocking"), Map.class); } catch (HttpClientResponseException e) { response = e.getResponse(); } Assertions.assertEquals("1234", response.getBody(Map.class).get().get("controllerTraceId")); Assertions.assertEquals("1234", response.getBody(Map.class).get().get("exceptionHandlerTraceId")); } @Test void testBlockingNotPropagatingMDCTrace() { HttpResponse<?> response; try { response = httpClient.toBlocking().exchange(HttpRequest.GET("/blocking"), Map.class); } catch (HttpClientResponseException e) { response = e.getResponse(); } Assertions.assertEquals("1234", response.getBody(Map.class).get().get("controllerTraceId")); Assertions.assertEquals("1234", response.getBody(Map.class).get().get("exceptionHandlerTraceId")); } }
PropagatedContextExceptionHandlerTest
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 890218, "end": 895832 }
class ____ extends YamlDeserializerBase<RestBindingDefinition> { public RestBindingDefinitionDeserializer() { super(RestBindingDefinition.class); } @Override protected RestBindingDefinition newInstance() { return new RestBindingDefinition(); } @Override protected boolean setProperty(RestBindingDefinition target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "bindingMode": { String val = asText(node); target.setBindingMode(val); break; } case "clientRequestValidation": { String val = asText(node); target.setClientRequestValidation(val); break; } case "clientResponseValidation": { String val = asText(node); target.setClientResponseValidation(val); break; } case "component": { String val = asText(node); target.setComponent(val); break; } case "consumes": { String val = asText(node); target.setConsumes(val); break; } case "enableCORS": { String val = asText(node); target.setEnableCORS(val); break; } case "enableNoContentResponse": { String val = asText(node); target.setEnableNoContentResponse(val); break; } case "outType": { String val = asText(node); target.setOutType(val); break; } case "produces": { String val = asText(node); target.setProduces(val); break; } case "skipBindingOnErrorCode": { String val = asText(node); target.setSkipBindingOnErrorCode(val); break; } case "type": { String val = asText(node); target.setType(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "description": { String val = asText(node); target.setDescription(val); break; } case "note": { String val = asText(node); target.setNote(val); break; } default: { return false; } } return true; } } @YamlIn @YamlType( nodes = "restConfiguration", types = org.apache.camel.model.rest.RestConfigurationDefinition.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "Rest Configuration", description = "To configure rest", deprecated = false, properties = { @YamlProperty(name = "apiComponent", type = "enum:openapi,swagger", description = "The name of the Camel component to use as the REST API. If no API Component has been explicit configured, then Camel will lookup if there is a Camel component responsible for servicing and generating the REST API documentation, or if a org.apache.camel.spi.RestApiProcessorFactory is registered in the registry. If either one is found, then that is being used.", displayName = "Api Component"), @YamlProperty(name = "apiContextPath", type = "string", description = "Sets a leading context-path the REST API will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path.", displayName = "Api Context Path"), @YamlProperty(name = "apiContextRouteId", type = "string", description = "Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id.", displayName = "Api Context Route Id"), @YamlProperty(name = "apiHost", type = "string", description = "To use a specific hostname for the API documentation (such as swagger or openapi) This can be used to override the generated host with this configured hostname", displayName = "Api Host"), @YamlProperty(name = "apiProperty", type = "array:org.apache.camel.model.rest.RestPropertyDefinition", description = "Allows to configure as many additional properties for the api documentation. For example set property api.title to my cool stuff", displayName = "Api Property"), @YamlProperty(name = "apiVendorExtension", type = "boolean", defaultValue = "false", description = "Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids,
RestBindingDefinitionDeserializer
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java
{ "start": 5704, "end": 5826 }
interface ____ extends CrudRepository<PersistableWithIdClass, PersistableWithIdClassPK> { } }
SampleWithIdClassRepository
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/YearMonthAssert.java
{ "start": 805, "end": 1095 }
class ____ extends AbstractYearMonthAssert<YearMonthAssert> { /** * Creates a new <code>{@link YearMonthAssert}</code>. * * @param actual the actual value to verify */ protected YearMonthAssert(YearMonth actual) { super(actual, YearMonthAssert.class); } }
YearMonthAssert
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/jackson/JsonProcessingExceptionMapper.java
{ "start": 493, "end": 1933 }
class ____ extends LoggingExceptionMapper<JsonProcessingException> { private final boolean showDetails; public JsonProcessingExceptionMapper() { this(false); } public JsonProcessingExceptionMapper(boolean showDetails) { super(LoggerFactory.getLogger(JsonProcessingExceptionMapper.class)); this.showDetails = showDetails; } public boolean isShowDetails() { return showDetails; } @Override public Response toResponse(JsonProcessingException exception) { /* * If the error is in the JSON generation or an invalid definition, it's a server error. */ if (exception instanceof JsonGenerationException || exception instanceof InvalidDefinitionException) { return super.toResponse(exception); // LoggingExceptionMapper will log exception } /* * Otherwise, it's those pesky users. */ logger.debug("Unable to process JSON", exception); final String message = exception.getOriginalMessage(); final ErrorMessage errorMessage = new ErrorMessage(Response.Status.BAD_REQUEST.getStatusCode(), "Unable to process JSON", showDetails ? message : null); return Response.status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON_TYPE) .entity(errorMessage) .build(); } }
JsonProcessingExceptionMapper
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/discovery/DiscoveryLocatorProperties.java
{ "start": 1142, "end": 3731 }
class ____ { /** Flag that enables DiscoveryClient gateway integration. */ private boolean enabled = false; /** * The prefix for the routeId, defaults to discoveryClient.getClass().getSimpleName() * + "_". Service Id will be appended to create the routeId. */ private @Nullable String routeIdPrefix; /** * SpEL expression that will evaluate whether to include a service in gateway * integration or not, defaults to: true. */ private String includeExpression = "true"; /** * SpEL expression that create the uri for each route, defaults to: 'lb://'+serviceId. */ private String urlExpression = "'lb://'+serviceId"; /** * Option to lower case serviceId in predicates and filters, defaults to false. Useful * with eureka when it automatically uppercases serviceId. so MYSERIVCE, would match * /myservice/** */ private boolean lowerCaseServiceId = false; private List<PredicateDefinition> predicates = new ArrayList<>(); private List<FilterDefinition> filters = new ArrayList<>(); public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable String getRouteIdPrefix() { return routeIdPrefix; } public void setRouteIdPrefix(String routeIdPrefix) { this.routeIdPrefix = routeIdPrefix; } public String getIncludeExpression() { return includeExpression; } public void setIncludeExpression(String includeExpression) { this.includeExpression = includeExpression; } public String getUrlExpression() { return urlExpression; } public void setUrlExpression(String urlExpression) { this.urlExpression = urlExpression; } public boolean isLowerCaseServiceId() { return lowerCaseServiceId; } public void setLowerCaseServiceId(boolean lowerCaseServiceId) { this.lowerCaseServiceId = lowerCaseServiceId; } public List<PredicateDefinition> getPredicates() { return predicates; } public void setPredicates(List<PredicateDefinition> predicates) { this.predicates = predicates; } public List<FilterDefinition> getFilters() { return filters; } public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } @Override public String toString() { return new ToStringCreator(this).append("enabled", enabled) .append("routeIdPrefix", routeIdPrefix) .append("includeExpression", includeExpression) .append("urlExpression", urlExpression) .append("lowerCaseServiceId", lowerCaseServiceId) .append("predicates", predicates) .append("filters", filters) .toString(); } }
DiscoveryLocatorProperties
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProviderTest.java
{ "start": 25964, "end": 28053 }
interface ____<T extends Car> { public Insurance<T> create(T car, double premium); } public void testAssistedFactoryForParameterizedType() { final TypeLiteral<InsuranceFactory<Mustang>> mustangInsuranceFactoryType = new TypeLiteral<InsuranceFactory<Mustang>>() {}; final TypeLiteral<InsuranceFactory<Camaro>> camaroInsuranceFactoryType = new TypeLiteral<InsuranceFactory<Camaro>>() {}; Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(Double.class).annotatedWith(Names.named("lowLimit")).toInstance(50000.0d); bind(Double.class).annotatedWith(Names.named("highLimit")).toInstance(100000.0d); bind(mustangInsuranceFactoryType) .toProvider( FactoryProvider.newFactory( mustangInsuranceFactoryType, TypeLiteral.get(MustangInsurance.class))); bind(camaroInsuranceFactoryType) .toProvider( FactoryProvider.newFactory( camaroInsuranceFactoryType, TypeLiteral.get(CamaroInsurance.class))); } }); InsuranceFactory<Mustang> mustangInsuranceFactory = injector.getInstance(Key.get(mustangInsuranceFactoryType)); InsuranceFactory<Camaro> camaroInsuranceFactory = injector.getInstance(Key.get(camaroInsuranceFactoryType)); Mustang mustang = new Mustang(5000d, Color.BLACK); MustangInsurance mustangPolicy = (MustangInsurance) mustangInsuranceFactory.create(mustang, 800.0d); assertEquals(800.0d, mustangPolicy.premium, 0.0); assertEquals(50000.0d, mustangPolicy.limit, 0.0); Camaro camaro = new Camaro(3000, 1967, Color.BLUE); CamaroInsurance camaroPolicy = (CamaroInsurance) camaroInsuranceFactory.create(camaro, 800.0d); assertEquals(800.0d, camaroPolicy.premium, 0.0); assertEquals(100000.0d, camaroPolicy.limit, 0.0); } public static
InsuranceFactory
java
quarkusio__quarkus
core/processor/src/main/java/io/quarkus/annotation/processor/documentation/config/util/TypeUtil.java
{ "start": 107, "end": 1194 }
class ____ { /* * Retrieve a default value of a primitive type. * */ public static String getPrimitiveDefaultValue(String primitiveType) { return Types.PRIMITIVE_DEFAULT_VALUES.get(primitiveType); } /** * Replaces Java primitive wrapper types with primitive types */ public static String unbox(String type) { String mapping = Types.PRIMITIVE_WRAPPERS.get(type); return mapping == null ? type : mapping; } public static boolean isPrimitiveWrapper(String type) { return Types.PRIMITIVE_WRAPPERS.containsKey(type); } public static String getAlias(String qualifiedName) { return Types.ALIASED_TYPES.get(qualifiedName); } public static String normalizeDurationValue(String value) { if (!value.isEmpty() && Character.isDigit(value.charAt(value.length() - 1))) { try { value = Integer.parseInt(value) + "S"; } catch (NumberFormatException ignore) { } } return value.toUpperCase(Locale.ROOT); } }
TypeUtil
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregationStrategyBeanAdapterNonStaticMethodTest.java
{ "start": 1039, "end": 1850 }
class ____ extends ContextTestSupport { @Test public void testAggregate() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("ABC"); template.sendBody("direct:start", "A"); template.sendBody("direct:start", "B"); template.sendBody("direct:start", "C"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(constant(true), AggregationStrategies.bean(MyBodyAppender.class, "append")) .completionSize(3).to("mock:result"); } }; } public static final
AggregationStrategyBeanAdapterNonStaticMethodTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java
{ "start": 12312, "end": 12472 }
class ____ extends TestObject { @Override public void absquatulate() { throw new UnsupportedOperationException(); } } private static
TestObjectSubclass
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementAndPrimaryUsingDifferentTlsConfigurationTest.java
{ "start": 3441, "end": 4892 }
class ____ implements Handler<RoutingContext> { @Override public void handle(RoutingContext routingContext) { routingContext.response() .setStatusCode(200) .end("Hello management"); } } @TestHTTPResource(value = "/route", tls = true) URL url; @TestHTTPResource(value = "/management", management = true, tls = true) URL management; @ConfigProperty(name = "quarkus.management.test-port") int managementPort; @ConfigProperty(name = "quarkus.http.test-ssl-port") int primaryPort; @Test public void test() { Assertions.assertNotEquals(url.getPort(), management.getPort()); Assertions.assertEquals(url.getPort(), primaryPort); Assertions.assertEquals(management.getPort(), managementPort); for (int i = 0; i < 10; i++) { RestAssured.given() .trustStore(new File("target/certs/ssl-main-interface-test-truststore.jks"), "secret-main") .get(url.toExternalForm()).then().body(Matchers.is("Hello primary")); } for (int i = 0; i < 10; i++) { RestAssured.given() .trustStore(new File("target/certs/ssl-management-interface-test-truststore.jks"), "secret") .get(management.toExternalForm()).then().body(Matchers.is("Hello management")); } } @Singleton static
MyHandler
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/resource/drawable/DrawableResource.java
{ "start": 910, "end": 1951 }
class ____<T extends Drawable> implements Resource<T>, Initializable { protected final T drawable; public DrawableResource(T drawable) { this.drawable = Preconditions.checkNotNull(drawable); } @NonNull @SuppressWarnings("unchecked") @Override public final T get() { @Nullable ConstantState state = drawable.getConstantState(); if (state == null) { return drawable; } // Drawables contain temporary state related to how they're being displayed // (alpha, color filter etc), so return a new copy each time. // If we ever return the original drawable, it's temporary state may be changed // and subsequent copies may end up with that temporary state. See #276. return (T) state.newDrawable(); } @Override public void initialize() { if (drawable instanceof BitmapDrawable) { ((BitmapDrawable) drawable).getBitmap().prepareToDraw(); } else if (drawable instanceof GifDrawable) { ((GifDrawable) drawable).getFirstFrame().prepareToDraw(); } } }
DrawableResource
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/savedrequest/FastHttpDateFormat.java
{ "start": 940, "end": 985 }
class ____ generate HTTP dates. * <p> * This
to
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/launcher/core/DiscoveryIssueCollectorTests.java
{ "start": 2055, "end": 4401 }
class ____ { @ParameterizedTest(name = "{0}") @MethodSource("pairs") void reportsFailedResolutionResultAsDiscoveryIssue(DiscoverySelector selector, TestSource source) { var collector = new DiscoveryIssueCollector(mock()); var failure = SelectorResolutionResult.failed(new RuntimeException("boom")); collector.selectorProcessed(UniqueId.forEngine("dummy"), selector, failure); var expectedIssue = DiscoveryIssue.builder(Severity.ERROR, selector + " resolution failed") // .cause(failure.getThrowable()) // .source(source) // .build(); assertThat(collector.toNotifier().getAllIssues()).containsExactly(expectedIssue); } public static Stream<Pair> pairs() { return Stream.of( // new Pair(selectClass("SomeClass"), ClassSource.from("SomeClass")), // new Pair(selectMethod("SomeClass#someMethod(int,int)"), org.junit.platform.engine.support.descriptor.MethodSource.from("SomeClass", "someMethod", "int,int")), // new Pair(selectClasspathResource("someResource"), ClasspathResourceSource.from("someResource")), // new Pair(selectClasspathResource("someResource", FilePosition.from(42)), ClasspathResourceSource.from("someResource", org.junit.platform.engine.support.descriptor.FilePosition.from(42))), // new Pair(selectClasspathResource("someResource", FilePosition.from(42, 23)), ClasspathResourceSource.from("someResource", org.junit.platform.engine.support.descriptor.FilePosition.from(42, 23))), // new Pair(selectPackage(""), PackageSource.from("")), // new Pair(selectPackage("some.package"), PackageSource.from("some.package")), // new Pair(selectFile("someFile"), FileSource.from(new File("someFile"))), // new Pair(selectFile("someFile", FilePosition.from(42)), FileSource.from(new File("someFile"), org.junit.platform.engine.support.descriptor.FilePosition.from(42))), // new Pair(selectFile("someFile", FilePosition.from(42, 23)), FileSource.from(new File("someFile"), org.junit.platform.engine.support.descriptor.FilePosition.from(42, 23))), // new Pair(selectDirectory("someDir"), DirectorySource.from(new File("someDir"))), // new Pair(selectUri("some:uri"), UriSource.from(URI.create("some:uri"))) // ); } record Pair(DiscoverySelector selector, TestSource source) implements RecordArguments { } }
DiscoveryIssueCollectorTests
java
apache__kafka
storage/src/main/java/org/apache/kafka/server/log/remote/metadata/storage/serialization/RemoteLogSegmentMetadataSnapshotTransform.java
{ "start": 1408, "end": 4650 }
class ____ implements RemoteLogMetadataTransform<RemoteLogSegmentMetadataSnapshot> { public ApiMessageAndVersion toApiMessageAndVersion(RemoteLogSegmentMetadataSnapshot segmentMetadata) { RemoteLogSegmentMetadataSnapshotRecord record = new RemoteLogSegmentMetadataSnapshotRecord() .setSegmentId(segmentMetadata.segmentId()) .setStartOffset(segmentMetadata.startOffset()) .setEndOffset(segmentMetadata.endOffset()) .setBrokerId(segmentMetadata.brokerId()) .setEventTimestampMs(segmentMetadata.eventTimestampMs()) .setMaxTimestampMs(segmentMetadata.maxTimestampMs()) .setSegmentSizeInBytes(segmentMetadata.segmentSizeInBytes()) .setSegmentLeaderEpochs(createSegmentLeaderEpochsEntry(segmentMetadata.segmentLeaderEpochs())) .setRemoteLogSegmentState(segmentMetadata.state().id()) .setTxnIndexEmpty(segmentMetadata.isTxnIdxEmpty()); segmentMetadata.customMetadata().ifPresent(md -> record.setCustomMetadata(md.value())); return new ApiMessageAndVersion(record, record.highestSupportedVersion()); } private List<RemoteLogSegmentMetadataSnapshotRecord.SegmentLeaderEpochEntry> createSegmentLeaderEpochsEntry(Map<Integer, Long> leaderEpochs) { return leaderEpochs.entrySet().stream() .map(entry -> new RemoteLogSegmentMetadataSnapshotRecord.SegmentLeaderEpochEntry() .setLeaderEpoch(entry.getKey()) .setOffset(entry.getValue())) .toList(); } @Override public RemoteLogSegmentMetadataSnapshot fromApiMessageAndVersion(ApiMessageAndVersion apiMessageAndVersion) { RemoteLogSegmentMetadataSnapshotRecord record = (RemoteLogSegmentMetadataSnapshotRecord) apiMessageAndVersion.message(); Map<Integer, Long> segmentLeaderEpochs = new HashMap<>(); for (RemoteLogSegmentMetadataSnapshotRecord.SegmentLeaderEpochEntry segmentLeaderEpoch : record.segmentLeaderEpochs()) { segmentLeaderEpochs.put(segmentLeaderEpoch.leaderEpoch(), segmentLeaderEpoch.offset()); } Optional<CustomMetadata> customMetadata = Optional.ofNullable(record.customMetadata()).map(CustomMetadata::new); return new RemoteLogSegmentMetadataSnapshot(record.segmentId(), record.startOffset(), record.endOffset(), record.maxTimestampMs(), record.brokerId(), record.eventTimestampMs(), record.segmentSizeInBytes(), customMetadata, RemoteLogSegmentState.forId(record.remoteLogSegmentState()), segmentLeaderEpochs, record.txnIndexEmpty()); } }
RemoteLogSegmentMetadataSnapshotTransform
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/migration/MultiTenancyStrategy.java
{ "start": 235, "end": 563 }
class ____ temporarily useful to facilitate the migration to Hibernate ORM 6; * we should get rid of it afterwards as we adapt to the new details of configuring multi-tenancy. * Copied from Hibernate ORM 5.x * * Describes the methods for multi-tenancy understood by Hibernate. * * @author Steve Ebersole * @deprecated This
is
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/MappingMethodUtils.java
{ "start": 362, "end": 541 }
class ____ { /** * Hide default constructor. */ private MappingMethodUtils() { } /** * Checks if the provided {@code method} is for
MappingMethodUtils
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/method/configuration/aot/EnableMethodSecurityAotTests.java
{ "start": 3344, "end": 4362 }
class ____ { @Bean DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.HSQL).build(); } @Bean LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(true); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("org.springframework.security.config.annotation.method.configuration.aot"); factory.setDataSource(dataSource()); return factory; } @Bean JpaRepositoryFactoryBean<@NonNull MessageRepository, Message, Long> repo(EntityManager entityManager) { JpaRepositoryFactoryBean<@NonNull MessageRepository, Message, Long> bean = new JpaRepositoryFactoryBean<>( MessageRepository.class); bean.setEntityManager(entityManager); return bean; } } }
AppConfig
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TruthConstantAssertsTest.java
{ "start": 3948, "end": 4421 }
class ____ { public void test(Object a) { // BUG: Diagnostic contains: assertThat(ImmutableList.of(1, 2, 3)).isEqualTo(a); } } """) .doTest(); } @Test public void positiveWithEnumOnLeftHandSide() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; public
Test
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/table/lookup/CachingAsyncLookupFunction.java
{ "start": 1832, "end": 5694 }
class ____ extends AsyncLookupFunction { private static final long serialVersionUID = 1L; // Constants public static final String LOOKUP_CACHE_METRIC_GROUP_NAME = "cache"; private static final long UNINITIALIZED = -1; // The actual user-provided lookup function private final AsyncLookupFunction delegate; private LookupCache cache; private transient String cacheIdentifier; // Cache metrics private transient CacheMetricGroup cacheMetricGroup; private transient Counter loadCounter; private transient Counter numLoadFailuresCounter; private volatile long latestLoadTime = UNINITIALIZED; public CachingAsyncLookupFunction(LookupCache cache, AsyncLookupFunction delegate) { this.cache = cache; this.delegate = delegate; } @Override public void open(FunctionContext context) throws Exception { // Get the shared cache from manager cacheIdentifier = functionIdentifier(); cache = LookupCacheManager.getInstance().registerCacheIfAbsent(cacheIdentifier, cache); // Register metrics cacheMetricGroup = new InternalCacheMetricGroup( context.getMetricGroup(), LOOKUP_CACHE_METRIC_GROUP_NAME); loadCounter = new ThreadSafeSimpleCounter(); cacheMetricGroup.loadCounter(loadCounter); numLoadFailuresCounter = new ThreadSafeSimpleCounter(); cacheMetricGroup.numLoadFailuresCounter(numLoadFailuresCounter); cache.open(cacheMetricGroup); delegate.open(context); } @Override public CompletableFuture<Collection<RowData>> asyncLookup(RowData keyRow) { Collection<RowData> cachedValues = cache.getIfPresent(keyRow); if (cachedValues != null) { return CompletableFuture.completedFuture(cachedValues); } else { long loadStartTime = System.currentTimeMillis(); return delegate.asyncLookup(keyRow) .whenComplete( (lookupValues, throwable) -> { if (throwable != null) { // TODO: Should implement retry on failure logic as proposed in // FLIP-234 numLoadFailuresCounter.inc(); throw new RuntimeException( String.format("Failed to lookup key '%s'", keyRow), throwable); } updateLatestLoadTime(System.currentTimeMillis() - loadStartTime); loadCounter.inc(); Collection<RowData> cachingValues = lookupValues; if (lookupValues == null || lookupValues.isEmpty()) { cachingValues = Collections.emptyList(); } cache.put(keyRow, cachingValues); }); } } @Override public void close() throws Exception { delegate.close(); if (cacheIdentifier != null) { LookupCacheManager.getInstance().unregisterCache(cacheIdentifier); } } public AsyncLookupFunction getDelegate() { return delegate; } @VisibleForTesting public LookupCache getCache() { return cache; } // --------------------------------- Helper functions ---------------------------- private synchronized void updateLatestLoadTime(long loadTime) { if (latestLoadTime == UNINITIALIZED) { cacheMetricGroup.latestLoadTimeGauge(() -> latestLoadTime); } latestLoadTime = loadTime; } }
CachingAsyncLookupFunction
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/execution/search/AggRef.java
{ "start": 412, "end": 685 }
class ____ implements FieldExtraction { @Override public void collectFields(QlSourceBuilder sourceBuilder) { // Aggregations do not need any special fields } @Override public boolean supportedByAggsOnlyQuery() { return true; } }
AggRef
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/annotation/ProfileValueSource.java
{ "start": 1429, "end": 1762 }
interface ____ { /** * Get the <em>profile value</em> indicated by the specified key. * @param key the name of the <em>profile value</em> * @return the String value of the <em>profile value</em>, or {@code null} * if there is no <em>profile value</em> with that key */ @Nullable String get(String key); }
ProfileValueSource
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/authorization/HttpStatusServerAccessDeniedHandlerTests.java
{ "start": 1470, "end": 3133 }
class ____ { @Mock private MockServerWebExchange exchange; private HttpStatus httpStatus = HttpStatus.FORBIDDEN; private HttpStatusServerAccessDeniedHandler handler = new HttpStatusServerAccessDeniedHandler(this.httpStatus); private AccessDeniedException exception = new AccessDeniedException("Forbidden"); @Test public void constructorHttpStatusWhenNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusServerAccessDeniedHandler(null)); } @Test public void commenceWhenNoSubscribersThenNoActions() { this.handler.handle(this.exchange, this.exception); verifyNoMoreInteractions(this.exchange); } @Test public void commenceWhenSubscribeThenStatusSet() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.handle(this.exchange, this.exception).block(); MockServerHttpResponse response = this.exchange.getResponse(); assertThat(response.getStatusCode()).isEqualTo(this.httpStatus); assertThat(response.getBodyAsString().block()).isEqualTo("Access Denied"); } @Test public void commenceWhenCustomStatusSubscribeThenStatusSet() { this.httpStatus = HttpStatus.NOT_FOUND; this.handler = new HttpStatusServerAccessDeniedHandler(this.httpStatus); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.handler.handle(this.exchange, this.exception).block(); MockServerHttpResponse response = this.exchange.getResponse(); assertThat(response.getStatusCode()).isEqualTo(this.httpStatus); assertThat(response.getBodyAsString().block()).isEqualTo("Access Denied"); } }
HttpStatusServerAccessDeniedHandlerTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/PolymorphicDeductionObjectVsArrayTest.java
{ "start": 391, "end": 643 }
class ____ extends DatabindTestUtil { @JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = DataArray.class) @JsonSubTypes({@JsonSubTypes.Type(DataObject.class), @JsonSubTypes.Type(DataArray.class)})
PolymorphicDeductionObjectVsArrayTest
java
resilience4j__resilience4j
resilience4j-metrics/src/main/java/io/github/resilience4j/metrics/publisher/CircuitBreakerMetricsPublisher.java
{ "start": 1051, "end": 4045 }
class ____ extends AbstractMetricsPublisher<CircuitBreaker> { private final String prefix; public CircuitBreakerMetricsPublisher() { this(DEFAULT_PREFIX, new MetricRegistry()); } public CircuitBreakerMetricsPublisher(MetricRegistry metricRegistry) { this(DEFAULT_PREFIX, metricRegistry); } public CircuitBreakerMetricsPublisher(String prefix, MetricRegistry metricRegistry) { super(metricRegistry); this.prefix = requireNonNull(prefix); } @Override public void publishMetrics(CircuitBreaker circuitBreaker) { String name = circuitBreaker.getName(); //state as an integer String state = name(prefix, name, STATE); String successful = name(prefix, name, SUCCESSFUL); String failed = name(prefix, name, FAILED); String slow = name(prefix, name, SLOW); String slowSuccess = name(prefix, name, SLOW_SUCCESS); String slowFailed = name(prefix, name, SLOW_FAILED); String notPermitted = name(prefix, name, NOT_PERMITTED); String numberOfBufferedCalls = name(prefix, name, BUFFERED); String failureRate = name(prefix, name, FAILURE_RATE); String slowCallRate = name(prefix, name, SLOW_CALL_RATE); metricRegistry.register(state, (Gauge<Integer>) () -> circuitBreaker.getState().getOrder()); metricRegistry.register(successful, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()); metricRegistry.register(failed, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfFailedCalls()); metricRegistry.register(slow, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfSlowCalls()); metricRegistry.register(slowSuccess, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfSlowCalls()); metricRegistry.register(slowFailed, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfSlowFailedCalls()); metricRegistry.register(notPermitted, (Gauge<Long>) () -> circuitBreaker.getMetrics().getNumberOfNotPermittedCalls()); metricRegistry.register(numberOfBufferedCalls, (Gauge<Integer>) () -> circuitBreaker.getMetrics().getNumberOfBufferedCalls()); metricRegistry.register(failureRate, (Gauge<Float>) () -> circuitBreaker.getMetrics().getFailureRate()); metricRegistry.register(slowCallRate, (Gauge<Float>) () -> circuitBreaker.getMetrics().getSlowCallRate()); List<String> metricNames = Arrays .asList(state, successful, failed, notPermitted, numberOfBufferedCalls, failureRate, slow, slowSuccess, slowFailed, slowCallRate); metricsNameMap.put(name, new HashSet<>(metricNames)); } @Override public void removeMetrics(CircuitBreaker circuitBreaker) { removeMetrics(circuitBreaker.getName()); } }
CircuitBreakerMetricsPublisher
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/UFreeIdent.java
{ "start": 1279, "end": 3785 }
class ____ extends Bindings.Key<JCExpression> { Key(CharSequence name) { super(name.toString()); } } public static UFreeIdent create(CharSequence identifier) { return new AutoValue_UFreeIdent(StringName.of(identifier)); } @Override public abstract StringName getName(); public Key key() { return new Key(getName()); } @Override public JCExpression inline(Inliner inliner) { return inliner.getBinding(key()); } private static boolean trueOrNull(@Nullable Boolean condition) { return condition == null || condition; } @Override public Choice<Unifier> visitIdentifier(IdentifierTree node, Unifier unifier) { Names names = Names.instance(unifier.getContext()); return node.getName().equals(names._super) ? Choice.<Unifier>none() : defaultAction(node, unifier); } @Override protected Choice<Unifier> defaultAction(Tree target, Unifier unifier) { if (target instanceof JCExpression expression) { JCExpression currentBinding = unifier.getBinding(key()); // Check that the expression does not reference any template-local variables. boolean isGood = trueOrNull( new TreeScanner<Boolean, Void>() { @Override public Boolean reduce(@Nullable Boolean left, @Nullable Boolean right) { return trueOrNull(left) && trueOrNull(right); } @Override public Boolean visitIdentifier(IdentifierTree ident, Void v) { Symbol identSym = ASTHelpers.getSymbol(ident); for (ULocalVarIdent.Key key : Iterables.filter(unifier.getBindings().keySet(), ULocalVarIdent.Key.class)) { if (identSym == unifier.getBinding(key).symbol()) { return false; } } return true; } }.scan(expression, null)); if (!isGood) { return Choice.none(); } else if (currentBinding == null) { unifier.putBinding(key(), expression); return Choice.of(unifier); } else if (currentBinding.toString().equals(expression.toString())) { // TODO(lowasser): try checking types here in a way that doesn't reject // different wildcard captures // If it's the same code, treat it as the same expression. return Choice.of(unifier); } } return Choice.none(); } }
Key
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/TemplateRootBuildItem.java
{ "start": 457, "end": 980 }
class ____ extends MultiBuildItem { private final String path; public TemplateRootBuildItem(String path) { this.path = normalize(path); } public String getPath() { return path; } static String normalize(String path) { path = path.strip(); if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } }
TemplateRootBuildItem
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/InstantSecondParam.java
{ "start": 323, "end": 632 }
class ____ extends AbstractParam<Instant> { public InstantSecondParam(@Nullable final String input) { super(input); } @Override protected Instant parse(@Nullable final String input) throws Exception { return Instant.ofEpochSecond(Long.parseLong(input)); } }
InstantSecondParam
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/test-flaky-test-multiple-profiles/src/test/java/org/acme/FlakyHelloResourceWithAnotherProfileTest.java
{ "start": 1242, "end": 1349 }
class ____ implements QuarkusTestProfile { public AnotherProfile() { } } }
AnotherProfile
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/FunctionalIO.java
{ "start": 1140, "end": 2750 }
class ____ { private FunctionalIO() { } /** * Invoke any operation, wrapping IOExceptions with * {@code UncheckedIOException}. * @param call callable * @param <T> type of result * @return result * @throws UncheckedIOException if an IOE was raised. */ public static <T> T uncheckIOExceptions(CallableRaisingIOE<T> call) { return call.unchecked(); } /** * Wrap a {@link CallableRaisingIOE} as a {@link Supplier}. * @param call call to wrap * @param <T> type of result * @return a supplier which invokes the call. */ public static <T> Supplier<T> toUncheckedIOExceptionSupplier(CallableRaisingIOE<T> call) { return call::unchecked; } /** * Invoke the supplier, catching any {@code UncheckedIOException} raised, * extracting the inner IOException and rethrowing it. * @param call call to invoke * @param <T> type of result * @return result * @throws IOException if the call raised an IOException wrapped by an UncheckedIOException. */ public static <T> T extractIOExceptions(Supplier<T> call) throws IOException { try { return call.get(); } catch (UncheckedIOException e) { throw e.getCause(); } } /** * Convert a {@link FunctionRaisingIOE} as a {@link Supplier}. * @param fun function to wrap * @param <T> type of input * @param <R> type of return value. * @return a new function which invokes the inner function and wraps * exceptions. */ public static <T, R> Function<T, R> toUncheckedFunction(FunctionRaisingIOE<T, R> fun) { return fun::unchecked; } }
FunctionalIO
java
apache__camel
core/camel-health/src/main/java/org/apache/camel/impl/health/DefaultHealthChecksLoader.java
{ "start": 1352, "end": 3965 }
class ____ { public static final String META_INF_SERVICES = "META-INF/services/org/apache/camel/health-check"; private static final Logger LOG = LoggerFactory.getLogger(DefaultHealthChecksLoader.class); protected final CamelContext camelContext; protected final PackageScanResourceResolver resolver; protected final HealthCheckResolver healthCheckResolver; public DefaultHealthChecksLoader(CamelContext camelContext) { this.camelContext = camelContext; this.resolver = PluginHelper.getPackageScanResourceResolver(camelContext); this.healthCheckResolver = PluginHelper.getHealthCheckResolver(camelContext); } public Collection<HealthCheck> loadHealthChecks() { Collection<HealthCheck> answer = new ArrayList<>(); LOG.trace("Searching for {} health checks", META_INF_SERVICES); try { Collection<Resource> resources = resolver.findResources(META_INF_SERVICES + "/*-check"); if (LOG.isDebugEnabled()) { LOG.debug("Discovered {} health checks from classpath scanning", resources.size()); } for (Resource resource : resources) { LOG.trace("Resource: {}", resource); if (acceptResource(resource)) { String id = extractId(resource); LOG.trace("Loading HealthCheck: {}", id); HealthCheck hc = healthCheckResolver.resolveHealthCheck(id); if (hc != null) { LOG.debug("Loaded HealthCheck: {}/{}", hc.getGroup(), hc.getId()); answer.add(hc); } } } } catch (Exception e) { LOG.warn("Error during scanning for custom health-checks on classpath due to: {}. This exception is ignored.", e.getMessage()); } return answer; } protected boolean acceptResource(Resource resource) { String loc = resource.getLocation(); if (loc == null) { return false; } // this is an out of the box health-check if (loc.endsWith("context-check")) { return false; } return true; } protected String extractId(Resource resource) { String loc = resource.getLocation(); loc = StringHelper.after(loc, META_INF_SERVICES + "/"); // remove -check suffix if (loc != null && loc.endsWith("-check")) { loc = loc.substring(0, loc.length() - 6); } return loc; } }
DefaultHealthChecksLoader
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/search/WatcherSearchTemplateRequestTests.java
{ "start": 778, "end": 5072 }
class ____ extends ESTestCase { public void testFromXContentWithTemplateDefaultLang() throws IOException { String source = """ {"template":{"id":"default-script", "params":{"foo":"bar"}}}"""; assertTemplate(source, "default-script", null, singletonMap("foo", "bar")); } public void testFromXContentWithTemplateCustomLang() throws IOException { String source = """ {"template":{"source":"custom-script", "lang":"painful","params":{"bar":"baz"}}}"""; assertTemplate(source, "custom-script", "painful", singletonMap("bar", "baz")); } public void testFromXContentWithEmptyTypes() throws IOException { String source = """ { "search_type" : "query_then_fetch", "indices" : [ ".ml-anomalies-*" ], "types" : [ ], "body" : { "query" : { "bool" : { "filter" : [ { "term" : { "job_id" : "my-job" } }, { "range" : { "timestamp" : { "gte" : "now-30m" } } } ] } } } } """; try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { parser.nextToken(); ElasticsearchParseException e = expectThrows( ElasticsearchParseException.class, () -> WatcherSearchTemplateRequest.fromXContent(parser, randomFrom(SearchType.values())) ); assertThat(e.getMessage(), is("could not read search request. unexpected array field [types]")); } } public void testFromXContentWithNonEmptyTypes() throws IOException { String source = """ { "search_type" : "query_then_fetch", "indices" : [ "my-index" ], "types" : [ "my-type" ], "body" : { "query" : { "match_all" : {} } } } """; try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { parser.nextToken(); ElasticsearchParseException e = expectThrows( ElasticsearchParseException.class, () -> WatcherSearchTemplateRequest.fromXContent(parser, randomFrom(SearchType.values())) ); assertThat(e.getMessage(), is("could not read search request. unexpected array field [types]")); } } public void testDefaultHitCountsDefaults() throws IOException { assertHitCount("{}", true); } public void testDefaultHitCountsConfigured() throws IOException { boolean hitCountsAsInt = randomBoolean(); String source = "{ \"rest_total_hits_as_int\" : " + hitCountsAsInt + " }"; assertHitCount(source, hitCountsAsInt); } private void assertHitCount(String source, boolean expectedHitCountAsInt) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { parser.nextToken(); WatcherSearchTemplateRequest request = WatcherSearchTemplateRequest.fromXContent(parser, SearchType.QUERY_THEN_FETCH); assertThat(request.isRestTotalHitsAsint(), is(expectedHitCountAsInt)); } } private void assertTemplate(String source, String expectedScript, String expectedLang, Map<String, Object> expectedParams) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { parser.nextToken(); WatcherSearchTemplateRequest result = WatcherSearchTemplateRequest.fromXContent(parser, randomFrom(SearchType.values())); assertNotNull(result.getTemplate()); assertThat(result.getTemplate().getIdOrCode(), equalTo(expectedScript)); assertThat(result.getTemplate().getLang(), equalTo(expectedLang)); assertThat(result.getTemplate().getParams(), equalTo(expectedParams)); } } protected List<String> filteredWarnings() { return List.of(WatcherSearchTemplateRequest.TYPES_DEPRECATION_MESSAGE); } }
WatcherSearchTemplateRequestTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/CoerceMiscScalarsTest.java
{ "start": 577, "end": 8174 }
class ____ { private final ObjectMapper DEFAULT_MAPPER = sharedMapper(); private final ObjectMapper MAPPER_EMPTY_TO_EMPTY = jsonMapperBuilder() .withCoercionConfigDefaults(cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty)) .build(); private final ObjectMapper MAPPER_EMPTY_TO_TRY_CONVERT = jsonMapperBuilder() .withCoercionConfigDefaults(cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.TryConvert)) .build(); private final ObjectMapper MAPPER_EMPTY_TO_NULL = jsonMapperBuilder() .withCoercionConfigDefaults(cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull)) .build(); private final ObjectMapper MAPPER_EMPTY_TO_FAIL = jsonMapperBuilder() .withCoercionConfigDefaults(cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)) .build(); private final String JSON_EMPTY = q(""); /* /********************************************************************** /* Test methods, defaults (legacy) /********************************************************************** */ @Test public void testScalarDefaultsFromEmpty() throws Exception { // mostly as null, with some exceptions _testScalarEmptyToNull(DEFAULT_MAPPER, File.class); _testScalarEmptyToNull(DEFAULT_MAPPER, URL.class); _testScalarEmptyToEmpty(DEFAULT_MAPPER, URI.class, URI.create("")); _testScalarEmptyToNull(DEFAULT_MAPPER, Class.class); _testScalarEmptyToNull(DEFAULT_MAPPER, JavaType.class); _testScalarEmptyToNull(DEFAULT_MAPPER, Currency.class); _testScalarEmptyToNull(DEFAULT_MAPPER, Pattern.class); _testScalarEmptyToEmpty(DEFAULT_MAPPER, Locale.class, Locale.ROOT); _testScalarEmptyToNull(DEFAULT_MAPPER, Charset.class); _testScalarEmptyToNull(DEFAULT_MAPPER, TimeZone.class); _testScalarEmptyToNull(DEFAULT_MAPPER, InetAddress.class); _testScalarEmptyToNull(DEFAULT_MAPPER, InetSocketAddress.class); } /* /********************************************************************** /* Test methods, successful coercions from empty String /********************************************************************** */ @Test public void testScalarEmptyToNull() throws Exception { _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, File.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, URL.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, URI.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, Class.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, JavaType.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, Currency.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, Pattern.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, Locale.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, Charset.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, TimeZone.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, InetAddress.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, InetSocketAddress.class); } @Test public void testScalarEmptyToEmpty() throws Exception { _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, File.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, URL.class); _testScalarEmptyToEmpty(MAPPER_EMPTY_TO_EMPTY, URI.class, URI.create("")); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, Class.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, JavaType.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, Currency.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, Pattern.class); _testScalarEmptyToEmpty(MAPPER_EMPTY_TO_EMPTY, Locale.class, Locale.ROOT); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, Charset.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, TimeZone.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, InetAddress.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_EMPTY, InetSocketAddress.class); } @Test public void testScalarEmptyToTryConvert() throws Exception { // Should be same as `AsNull` for most but not all _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, File.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, URL.class); _testScalarEmptyToEmpty(MAPPER_EMPTY_TO_TRY_CONVERT, URI.class, URI.create("")); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, Class.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, JavaType.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, Currency.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, Pattern.class); _testScalarEmptyToEmpty(MAPPER_EMPTY_TO_TRY_CONVERT, Locale.class, Locale.ROOT); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, Charset.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, TimeZone.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, InetAddress.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, InetSocketAddress.class); } /* /********************************************************************** /* Test methods, failed coercions from empty String /********************************************************************** */ @Test public void testScalarsFailFromEmpty() throws Exception { _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, File.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, URL.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, URI.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, Class.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, JavaType.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, Currency.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, Pattern.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, Locale.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, Charset.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, TimeZone.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, InetAddress.class); _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, InetSocketAddress.class); } /* /******************************************************** /* Test methods, (more) special type(s) /******************************************************** */ // UUID is quite compatible, but not exactly due to historical reasons; // also uses custom subtype, so test separately @Test public void testUUIDCoercions() throws Exception { // Coerce to `null` both by default, "TryConvert" and explicit _testScalarEmptyToNull(DEFAULT_MAPPER, UUID.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_NULL, UUID.class); _testScalarEmptyToNull(MAPPER_EMPTY_TO_TRY_CONVERT, UUID.class); // but allow separate "empty" value is specifically requested _testScalarEmptyToEmpty(MAPPER_EMPTY_TO_EMPTY, UUID.class, new UUID(0L, 0L)); // allow forcing failure, too _verifyScalarToFail(MAPPER_EMPTY_TO_FAIL, UUID.class); // and allow failure with specifically configured per-
CoerceMiscScalarsTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/abstractclass/ReferencedMapperInterface.java
{ "start": 235, "end": 320 }
interface ____ { int holderToInt(Holder<String> holder); }
ReferencedMapperInterface
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableRefCountTest.java
{ "start": 27918, "end": 28554 }
class ____ extends ConnectableObservable<Object> { @Override public void reset() { throw new TestException("dispose"); } @Override public void connect(Consumer<? super Disposable> connection) { try { connection.accept(Disposable.empty()); } catch (Throwable ex) { throw ExceptionHelper.wrapOrThrow(ex); } } @Override protected void subscribeActual(Observer<? super Object> observer) { observer.onSubscribe(Disposable.empty()); } } static final
BadObservableDispose
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/HandlerMethod.java
{ "start": 1749, "end": 4170 }
class ____ extends AnnotatedMethod { /** Public for wrapping with fallback logger. */ public static final Log defaultLogger = LogFactory.getLog(HandlerMethod.class); private final Object bean; private final @Nullable BeanFactory beanFactory; private final Class<?> beanType; private @Nullable HandlerMethod resolvedFromHandlerMethod; protected Log logger = defaultLogger; /** * Create an instance from a bean instance and a method. */ public HandlerMethod(Object bean, Method method) { super(method); this.bean = bean; this.beanFactory = null; this.beanType = ClassUtils.getUserClass(bean); } /** * Create an instance from a bean instance, method name, and parameter types. * @throws NoSuchMethodException when the method cannot be found */ public HandlerMethod(Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { super(bean.getClass().getMethod(methodName, parameterTypes)); this.bean = bean; this.beanFactory = null; this.beanType = ClassUtils.getUserClass(bean); } /** * Create an instance from a bean name, a method, and a {@code BeanFactory}. * The method {@link #createWithResolvedBean()} may be used later to * re-create the {@code HandlerMethod} with an initialized bean. */ public HandlerMethod(String beanName, BeanFactory beanFactory, Method method) { super(method); this.bean = beanName; this.beanFactory = beanFactory; Class<?> beanType = beanFactory.getType(beanName); if (beanType == null) { throw new IllegalStateException("Cannot resolve bean type for bean with name '" + beanName + "'"); } this.beanType = ClassUtils.getUserClass(beanType); } /** * Copy constructor for use in subclasses. */ protected HandlerMethod(HandlerMethod handlerMethod) { super(handlerMethod); this.bean = handlerMethod.bean; this.beanFactory = handlerMethod.beanFactory; this.beanType = handlerMethod.beanType; this.resolvedFromHandlerMethod = handlerMethod.resolvedFromHandlerMethod; } /** * Re-create HandlerMethod with the resolved handler. */ private HandlerMethod(HandlerMethod handlerMethod, Object handler) { super(handlerMethod); this.bean = handler; this.beanFactory = handlerMethod.beanFactory; this.beanType = handlerMethod.beanType; this.resolvedFromHandlerMethod = handlerMethod; } /** * Set an alternative logger to use than the one based on the
HandlerMethod
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchingInheritanceDeleteTest.java
{ "start": 3590, "end": 4188 }
class ____ extends AbstractFoo { public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } @Column(name = "NAME") private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "BAR_ID") private Bar bar; public Bar getBar() { return bar; } public void setBar(final Bar bar) { this.bar = bar; } public String getName() { return name; } public void setName(final String name) { this.name = name; } } @Entity(name = "AbstractBar") @Inheritance(strategy = InheritanceType.JOINED) public static
Foo
java
spring-projects__spring-security
oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponseTests.java
{ "start": 1201, "end": 7394 }
class ____ { private static final String TOKEN_VALUE = "access-token"; private static final String REFRESH_TOKEN_VALUE = "refresh-token"; private static final long EXPIRES_IN = Instant.now().plusSeconds(5).toEpochMilli(); @Test public void buildWhenTokenValueIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AccessTokenResponse.withToken(null) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(EXPIRES_IN) .build() // @formatter:on ); } @Test public void buildWhenTokenTypeIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> // @formatter:off OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(null) .expiresIn(EXPIRES_IN) .build() // @formatter:on ); } @Test public void buildWhenExpiresInIsZeroThenExpiresAtOneSecondAfterIssueAt() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(0) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getIssuedAt().plusSeconds(1)); } @Test public void buildWhenExpiresInIsNegativeThenExpiresAtOneSecondAfterIssueAt() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(-1L) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getIssuedAt().plusSeconds(1)); } @Test public void buildWhenAllAttributesProvidedThenAllAttributesAreSet() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .refreshToken(REFRESH_TOKEN_VALUE) .additionalParameters(additionalParameters) .build(); // @formatter:on assertThat(tokenResponse.getAccessToken()).isNotNull(); assertThat(tokenResponse.getAccessToken().getTokenValue()).isEqualTo(TOKEN_VALUE); assertThat(tokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(tokenResponse.getAccessToken().getIssuedAt()).isNotNull(); assertThat(tokenResponse.getAccessToken().getExpiresAt()).isAfterOrEqualTo(expiresAt); assertThat(tokenResponse.getAccessToken().getScopes()).isEqualTo(scopes); assertThat(tokenResponse.getRefreshToken().getTokenValue()).isEqualTo(REFRESH_TOKEN_VALUE); assertThat(tokenResponse.getAdditionalParameters()).isEqualTo(additionalParameters); } @Test public void buildWhenResponseThenAllAttributesAreSet() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .refreshToken(REFRESH_TOKEN_VALUE) .additionalParameters(additionalParameters) .build(); // @formatter:on OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse).build(); assertThat(withResponse.getAccessToken().getTokenValue()) .isEqualTo(tokenResponse.getAccessToken().getTokenValue()); assertThat(withResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER); assertThat(withResponse.getAccessToken().getIssuedAt()).isEqualTo(tokenResponse.getAccessToken().getIssuedAt()); assertThat(withResponse.getAccessToken().getExpiresAt()) .isEqualTo(tokenResponse.getAccessToken().getExpiresAt()); assertThat(withResponse.getAccessToken().getScopes()).isEqualTo(tokenResponse.getAccessToken().getScopes()); assertThat(withResponse.getRefreshToken().getTokenValue()) .isEqualTo(tokenResponse.getRefreshToken().getTokenValue()); assertThat(withResponse.getAdditionalParameters()).isEqualTo(tokenResponse.getAdditionalParameters()); } @Test public void buildWhenResponseAndRefreshNullThenRefreshNull() { Instant expiresAt = Instant.now().plusSeconds(5); Set<String> scopes = new LinkedHashSet<>(Arrays.asList("scope1", "scope2")); Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(expiresAt.toEpochMilli()) .scopes(scopes) .additionalParameters(additionalParameters) .build(); // @formatter:on OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse).build(); assertThat(withResponse.getRefreshToken()).isNull(); } @Test public void buildWhenResponseAndExpiresInThenExpiresAtEqualToIssuedAtPlusExpiresIn() { // @formatter:off OAuth2AccessTokenResponse tokenResponse = OAuth2AccessTokenResponse.withToken(TOKEN_VALUE) .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); // @formatter:on long expiresIn = 30; OAuth2AccessTokenResponse withResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .expiresIn(expiresIn) .build(); assertThat(withResponse.getAccessToken().getExpiresAt()) .isEqualTo(withResponse.getAccessToken().getIssuedAt().plusSeconds(expiresIn)); } }
OAuth2AccessTokenResponseTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_265.java
{ "start": 1055, "end": 1777 }
class ____ implements JSONSerializable, ExtraProcessable { protected Map<String, Object> attributes = new HashMap<String, Object>(); public Map<String, Object> getAttributes() { return attributes; } public Object getAttribute(String name) { return attributes.get(name); } @Override public void write(JSONSerializer serializer, Object fieldName, Type fieldType, int features) throws IOException { serializer.write(attributes); } @Override public void processExtra(String key, Object value) { attributes.put(key, value); } } public static
Model
java
elastic__elasticsearch
modules/repository-gcs/src/test/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobContainerRetriesTests.java
{ "start": 5072, "end": 33636 }
class ____ extends AbstractBlobContainerRetriesTestCase { private final ClusterService clusterService = ClusterServiceUtils.createClusterService(new DeterministicTaskQueue().getThreadPool()); private final Map<String, AtomicInteger> requestCounters = new ConcurrentHashMap<>(); private String endpointUrlOverride; private String httpServerUrl() { assertThat(httpServer, notNullValue()); InetSocketAddress address = httpServer.getAddress(); return "http://" + InetAddresses.toUriString(address.getAddress()) + ":" + address.getPort(); } private String getEndpointUrl() { return endpointUrlOverride != null ? endpointUrlOverride : httpServerUrl(); } @Override protected String downloadStorageEndpoint(BlobContainer container, String blob) { return "/download/storage/v1/b/bucket/o/" + container.path().buildAsString() + blob; } @Override protected String bytesContentType() { return "application/octet-stream"; } @Override protected Class<? extends Exception> unresponsiveExceptionType() { return StorageException.class; } @Override protected BlobContainer createBlobContainer( final @Nullable Integer maxRetries, final @Nullable TimeValue readTimeout, final @Nullable Boolean disableChunkedEncoding, final @Nullable Integer maxConnections, final @Nullable ByteSizeValue bufferSize, final @Nullable Integer maxBulkDeletes, final @Nullable BlobPath blobContainerPath ) { final Settings.Builder clientSettings = Settings.builder(); final String client = randomAlphaOfLength(5).toLowerCase(Locale.ROOT); clientSettings.put(ENDPOINT_SETTING.getConcreteSettingForNamespace(client).getKey(), getEndpointUrl()); clientSettings.put(TOKEN_URI_SETTING.getConcreteSettingForNamespace(client).getKey(), httpServerUrl() + "/token"); if (readTimeout != null) { clientSettings.put(READ_TIMEOUT_SETTING.getConcreteSettingForNamespace(client).getKey(), readTimeout); } final MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setFile(CREDENTIALS_FILE_SETTING.getConcreteSettingForNamespace(client).getKey(), createServiceAccount(random())); clientSettings.setSecureSettings(secureSettings); final GoogleCloudStorageService service = new GoogleCloudStorageService(clusterService, TestProjectResolvers.DEFAULT_PROJECT_ONLY) { @Override StorageOptions createStorageOptions( final GoogleCloudStorageClientSettings gcsClientSettings, final HttpTransportOptions httpTransportOptions ) { final HttpTransportOptions requestCountingHttpTransportOptions = new HttpTransportOptions( HttpTransportOptions.newBuilder() .setConnectTimeout(httpTransportOptions.getConnectTimeout()) .setHttpTransportFactory(httpTransportOptions.getHttpTransportFactory()) .setReadTimeout(httpTransportOptions.getReadTimeout()) ) { @Override public HttpRequestInitializer getHttpRequestInitializer(ServiceOptions<?, ?> serviceOptions) { // Add initializer/interceptor without interfering with any pre-existing ones HttpRequestInitializer httpRequestInitializer = httpTransportOptions.getHttpRequestInitializer(serviceOptions); return request -> { if (httpRequestInitializer != null) { httpRequestInitializer.initialize(request); } HttpExecuteInterceptor interceptor = request.getInterceptor(); request.setInterceptor(req -> { if (interceptor != null) { interceptor.intercept(req); } requestCounters.computeIfAbsent(request.getUrl().getRawPath(), (url) -> new AtomicInteger()) .incrementAndGet(); }); }; } }; final StorageOptions options = super.createStorageOptions(gcsClientSettings, requestCountingHttpTransportOptions); final RetrySettings.Builder retrySettingsBuilder = RetrySettings.newBuilder() .setTotalTimeout(options.getRetrySettings().getTotalTimeout()) .setInitialRetryDelay(Duration.ofMillis(10L)) .setRetryDelayMultiplier(1.0d) .setMaxRetryDelay(Duration.ofSeconds(1L)) .setJittered(false) .setInitialRpcTimeout(Duration.ofSeconds(1)) .setRpcTimeoutMultiplier(options.getRetrySettings().getRpcTimeoutMultiplier()) .setMaxRpcTimeout(Duration.ofSeconds(1)); if (maxRetries != null) { retrySettingsBuilder.setMaxAttempts(maxRetries + 1); } return options.toBuilder() .setStorageRetryStrategy(getRetryStrategy()) .setHost(options.getHost()) .setCredentials(options.getCredentials()) .setRetrySettings(retrySettingsBuilder.build()) .build(); } }; service.refreshAndClearCache(GoogleCloudStorageClientSettings.load(clientSettings.build())); httpServer.createContext("/token", new FakeOAuth2HttpHandler()); final GoogleCloudStorageBlobStore blobStore = new GoogleCloudStorageBlobStore( ProjectId.DEFAULT, "bucket", client, "repo", service, BigArrays.NON_RECYCLING_INSTANCE, randomIntBetween(1, 8) * 1024, BackoffPolicy.linearBackoff(TimeValue.timeValueMillis(1), 3, TimeValue.timeValueSeconds(1)), new GcsRepositoryStatsCollector() ); return new GoogleCloudStorageBlobContainer( Objects.requireNonNullElse(blobContainerPath, randomBoolean() ? BlobPath.EMPTY : BlobPath.EMPTY.add("foo")), blobStore ); } @Override protected void addSuccessfulDownloadHeaders(HttpExchange exchange) { exchange.getResponseHeaders().add("x-goog-generation", String.valueOf(randomNonNegativeInt())); } public void testShouldRetryOnConnectionRefused() { // port 1 should never be open endpointUrlOverride = "http://127.0.0.1:1"; executeListBlobsAndAssertRetries(); } public void testShouldRetryOnUnresolvableHost() { // https://www.rfc-editor.org/rfc/rfc2606.html#page-2 endpointUrlOverride = "http://unresolvable.invalid"; executeListBlobsAndAssertRetries(); } private void executeListBlobsAndAssertRetries() { final int maxRetries = randomIntBetween(3, 5); final BlobContainer blobContainer = blobContainerBuilder().maxRetries(maxRetries).build(); expectThrows(StorageException.class, () -> blobContainer.listBlobs(randomPurpose())); assertEquals(maxRetries + 1, requestCounters.get("/storage/v1/b/bucket/o").get()); } public void testReadLargeBlobWithRetries() throws Exception { final int maxRetries = randomIntBetween(2, 10); final AtomicInteger countDown = new AtomicInteger(maxRetries); final BlobContainer blobContainer = blobContainerBuilder().maxRetries(maxRetries).build(); // SDK reads in 2 MB chunks so we use twice that to simulate 2 chunks final byte[] bytes = randomBytes(1 << 22); httpServer.createContext(downloadStorageEndpoint(blobContainer, "large_blob_retries"), exchange -> { Streams.readFully(exchange.getRequestBody()); exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); addSuccessfulDownloadHeaders(exchange); final HttpHeaderParser.Range range = getRange(exchange); final int offset = Math.toIntExact(range.start()); final byte[] chunk = Arrays.copyOfRange(bytes, offset, Math.toIntExact(Math.min(range.end() + 1, bytes.length))); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), chunk.length); if (randomBoolean() && countDown.decrementAndGet() >= 0) { exchange.getResponseBody().write(chunk, 0, chunk.length - 1); exchange.close(); return; } exchange.getResponseBody().write(chunk); exchange.close(); }); try (InputStream inputStream = blobContainer.readBlob(randomPurpose(), "large_blob_retries")) { assertArrayEquals(bytes, BytesReference.toBytes(Streams.readFully(inputStream))); } } public void testWriteBlobWithRetries() throws Exception { final int maxRetries = randomIntBetween(2, 10); final CountDown countDown = new CountDown(maxRetries); final BlobContainer blobContainer = blobContainerBuilder().maxRetries(maxRetries).build(); final byte[] bytes = randomBlobContent(0); httpServer.createContext("/upload/storage/v1/b/bucket/o", safeHandler(exchange -> { assertThat(exchange.getRequestURI().getQuery(), containsString("uploadType=multipart")); if (countDown.countDown()) { MultipartUpload multipartUpload = MultipartUpload.parseBody(exchange, exchange.getRequestBody()); assertEquals(multipartUpload.name(), blobContainer.path().buildAsString() + "write_blob_max_retries"); if (multipartUpload.content().equals(new BytesArray(bytes))) { byte[] response = Strings.format(""" {"bucket":"bucket","name":"%s"} """, multipartUpload.name()).getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else { exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1); } return; } if (randomBoolean()) { if (randomBoolean()) { org.elasticsearch.core.Streams.readFully( exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))] ); } else { Streams.readFully(exchange.getRequestBody()); exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, -1); } } })); try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) { blobContainer.writeBlob(randomPurpose(), "write_blob_max_retries", stream, bytes.length, false); } assertThat(countDown.isCountedDown(), is(true)); } public void testWriteBlobWithReadTimeouts() { final byte[] bytes = randomByteArrayOfLength(randomIntBetween(10, 128)); final TimeValue readTimeout = TimeValue.timeValueMillis(randomIntBetween(100, 500)); final BlobContainer blobContainer = blobContainerBuilder().maxRetries(1).readTimeout(readTimeout).build(); // HTTP server does not send a response httpServer.createContext("/upload/storage/v1/b/bucket/o", exchange -> { if (randomBoolean()) { if (randomBoolean()) { org.elasticsearch.core.Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, bytes.length - 1)]); } else { Streams.readFully(exchange.getRequestBody()); } } }); Exception exception = expectThrows(StorageException.class, () -> { try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) { blobContainer.writeBlob(randomPurpose(), "write_blob_timeout", stream, bytes.length, false); } }); assertThat(exception.getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); assertThat(exception.getCause(), instanceOf(SocketTimeoutException.class)); assertThat(exception.getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out")); } public void testWriteLargeBlob() throws IOException { final int defaultChunkSize = GoogleCloudStorageBlobStore.SDK_DEFAULT_CHUNK_SIZE; final int nbChunks = randomIntBetween(3, 5); final int lastChunkSize = randomIntBetween(1, defaultChunkSize - 1); final int totalChunks = nbChunks + 1; final byte[] data = randomBytes(defaultChunkSize * nbChunks + lastChunkSize); assertThat(data.length, greaterThan(GoogleCloudStorageBlobStore.LARGE_BLOB_THRESHOLD_BYTE_SIZE)); logger.debug( "resumable upload is composed of [{}] total chunks ([{}] chunks of length [{}] and last chunk of length [{}]", totalChunks, nbChunks, defaultChunkSize, lastChunkSize ); final int nbErrors = 2; // we want all requests to fail at least once final AtomicInteger countInits = new AtomicInteger(nbErrors); final AtomicInteger countUploads = new AtomicInteger(nbErrors * totalChunks); final AtomicBoolean allow410Gone = new AtomicBoolean(randomBoolean()); final AtomicBoolean allowReadTimeout = new AtomicBoolean(rarely()); final AtomicInteger bytesReceived = new AtomicInteger(); final int wrongChunk = randomIntBetween(1, totalChunks); final AtomicReference<String> sessionUploadId = new AtomicReference<>(UUIDs.randomBase64UUID()); logger.debug("starting with resumable upload id [{}]", sessionUploadId.get()); final TimeValue readTimeout = allowReadTimeout.get() ? TimeValue.timeValueSeconds(3) : null; final BlobContainer blobContainer = blobContainerBuilder().maxRetries(nbErrors + 1).readTimeout(readTimeout).build(); httpServer.createContext("/upload/storage/v1/b/bucket/o", safeHandler(exchange -> { final BytesReference requestBody = Streams.readFully(exchange.getRequestBody()); final Map<String, String> params = new HashMap<>(); RestUtils.decodeQueryString(exchange.getRequestURI().getQuery(), 0, params); assertThat(params.get("uploadType"), equalTo("resumable")); if ("POST".equals(exchange.getRequestMethod())) { assertThat(params.get("name"), equalTo(blobContainer.path().buildAsString() + "write_large_blob")); if (countInits.decrementAndGet() <= 0) { byte[] response = requestBody.utf8ToString().getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.getResponseHeaders() .add( "Location", httpServerUrl() + "/upload/storage/v1/b/bucket/o?uploadType=resumable&upload_id=" + sessionUploadId.get() ); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); return; } if (allowReadTimeout.get()) { assertThat(wrongChunk, greaterThan(0)); return; } } else if ("PUT".equals(exchange.getRequestMethod())) { final String uploadId = params.get("upload_id"); if (uploadId.equals(sessionUploadId.get()) == false) { logger.debug("session id [{}] is gone", uploadId); assertThat(wrongChunk, greaterThan(0)); exchange.sendResponseHeaders(HttpStatus.SC_GONE, -1); return; } if (countUploads.get() == (wrongChunk * nbErrors)) { if (allowReadTimeout.compareAndSet(true, false)) { assertThat(wrongChunk, greaterThan(0)); return; } if (allow410Gone.compareAndSet(true, false)) { final String newUploadId = UUIDs.randomBase64UUID(random()); logger.debug("chunk [{}] gone, updating session ids [{} -> {}]", wrongChunk, sessionUploadId.get(), newUploadId); sessionUploadId.set(newUploadId); // we must reset the counters because the whole object upload will be retried countInits.set(nbErrors); countUploads.set(nbErrors * totalChunks); bytesReceived.set(0); exchange.sendResponseHeaders(HttpStatus.SC_GONE, -1); return; } } final String contentRangeHeaderValue = exchange.getRequestHeaders().getFirst("Content-Range"); final HttpHeaderParser.ContentRange contentRange = HttpHeaderParser.parseContentRangeHeader(contentRangeHeaderValue); assertNotNull("Invalid content range header: " + contentRangeHeaderValue, contentRange); if (contentRange.hasRange() == false) { // Content-Range: */... is a status check // https://cloud.google.com/storage/docs/performing-resumable-uploads#status-check final int receivedSoFar = bytesReceived.get(); if (receivedSoFar > 0) { exchange.getResponseHeaders().add("Range", Strings.format("bytes=0-%s", receivedSoFar)); } exchange.getResponseHeaders().add("Content-Length", "0"); exchange.sendResponseHeaders(308 /* Resume Incomplete */, -1); return; } if (countUploads.decrementAndGet() % 2 == 0) { assertThat(Math.toIntExact(requestBody.length()), anyOf(equalTo(defaultChunkSize), equalTo(lastChunkSize))); final int rangeStart = Math.toIntExact(contentRange.start()); final int rangeEnd = Math.toIntExact(contentRange.end()); assertThat(rangeEnd + 1 - rangeStart, equalTo(Math.toIntExact(requestBody.length()))); assertThat(new BytesArray(data, rangeStart, rangeEnd - rangeStart + 1), is(requestBody)); bytesReceived.updateAndGet(existing -> Math.max(existing, rangeEnd)); if (contentRange.size() != null) { exchange.getResponseHeaders().add("x-goog-stored-content-length", String.valueOf(bytesReceived.get() + 1)); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1); return; } else { exchange.getResponseHeaders().add("Range", Strings.format("bytes=%s-%s", rangeStart, rangeEnd)); exchange.getResponseHeaders().add("Content-Length", "0"); exchange.sendResponseHeaders(308 /* Resume Incomplete */, -1); return; } } } else { ExceptionsHelper.maybeDieOnAnotherThread( new AssertionError("Unexpected request" + exchange.getRequestMethod() + " " + exchange.getRequestURI()) ); } if (randomBoolean()) { exchange.sendResponseHeaders(HttpStatus.SC_INTERNAL_SERVER_ERROR, -1); } })); if (randomBoolean()) { try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", data), data.length)) { blobContainer.writeBlob(randomPurpose(), "write_large_blob", stream, data.length, false); } } else { blobContainer.writeMetadataBlob(randomPurpose(), "write_large_blob", false, randomBoolean(), out -> out.write(data)); } assertThat(countInits.get(), equalTo(0)); assertThat(countUploads.get(), equalTo(0)); assertThat(allow410Gone.get(), is(false)); } public void testDeleteBatchesAreSentIncrementally() throws Exception { // See com.google.cloud.storage.spi.v1.HttpStorageRpc.DefaultRpcBatch.MAX_BATCH_SIZE final int sdkMaxBatchSize = 100; final AtomicInteger receivedBatchRequests = new AtomicInteger(); final int totalDeletes = randomIntBetween(MAX_DELETES_PER_BATCH - 1, MAX_DELETES_PER_BATCH * 2); final AtomicInteger pendingDeletes = new AtomicInteger(); final Iterator<String> blobNamesIterator = new Iterator<>() { int totalDeletesSent = 0; @Override public boolean hasNext() { return totalDeletesSent < totalDeletes; } @Override public String next() { if (pendingDeletes.get() == MAX_DELETES_PER_BATCH) { // Check that once MAX_DELETES_PER_BATCH deletes are enqueued the pending batch requests are sent assertThat(receivedBatchRequests.get(), is(greaterThan(0))); assertThat(receivedBatchRequests.get(), is(lessThanOrEqualTo(MAX_DELETES_PER_BATCH / sdkMaxBatchSize))); receivedBatchRequests.set(0); pendingDeletes.set(0); } pendingDeletes.incrementAndGet(); return Integer.toString(totalDeletesSent++); } }; final BlobContainer blobContainer = blobContainerBuilder().maxRetries(1).build(); httpServer.createContext("/batch/storage/v1", safeHandler(exchange -> { assert pendingDeletes.get() <= MAX_DELETES_PER_BATCH; receivedBatchRequests.incrementAndGet(); final StringBuilder batch = new StringBuilder(); for (String line : Streams.readAllLines(exchange.getRequestBody())) { if (line.length() == 0 || line.startsWith("--") || line.toLowerCase(Locale.ROOT).startsWith("content")) { batch.append(line).append("\r\n"); } else if (line.startsWith("DELETE")) { batch.append("HTTP/1.1 204 NO_CONTENT").append("\r\n"); batch.append("\r\n"); } } byte[] response = batch.toString().getBytes(UTF_8); exchange.getResponseHeaders().add("Content-Type", exchange.getRequestHeaders().getFirst("Content-Type")); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); })); blobContainer.deleteBlobsIgnoringIfNotExists(randomPurpose(), blobNamesIterator); // Ensure that the remaining deletes are sent in the last batch if (pendingDeletes.get() > 0) { assertThat(receivedBatchRequests.get(), is(greaterThan(0))); assertThat(receivedBatchRequests.get(), is(lessThanOrEqualTo(MAX_DELETES_PER_BATCH / sdkMaxBatchSize))); assertThat(pendingDeletes.get(), is(lessThanOrEqualTo(MAX_DELETES_PER_BATCH))); } } public void testCompareAndExchangeWhenThrottled() throws IOException { final Queue<ResponseInjectingHttpHandler.RequestHandler> requestHandlers = new ConcurrentLinkedQueue<>(); httpServer.createContext("/", new ResponseInjectingHttpHandler(requestHandlers, new GoogleCloudStorageHttpHandler("bucket"))); final int maxRetries = randomIntBetween(1, 3); final BlobContainer container = blobContainerBuilder().maxRetries(maxRetries).build(); final byte[] data = randomBytes(randomIntBetween(1, BlobContainerUtils.MAX_REGISTER_CONTENT_LENGTH)); final String key = randomIdentifier(); final OptionalBytesReference createResult = safeAwait( l -> container.compareAndExchangeRegister(randomPurpose(), key, BytesArray.EMPTY, new BytesArray(data), l) ); assertEquals(createResult, OptionalBytesReference.EMPTY); final byte[] updatedData = randomBytes(randomIntBetween(1, BlobContainerUtils.MAX_REGISTER_CONTENT_LENGTH)); final int failuresToExhaustAttempts = maxRetries + 1; final int numberOfThrottles = randomIntBetween(failuresToExhaustAttempts, (4 * failuresToExhaustAttempts) - 1); for (int i = 0; i < numberOfThrottles; i++) { requestHandlers.offer( new ResponseInjectingHttpHandler.FixedRequestHandler( RestStatus.TOO_MANY_REQUESTS, null, ex -> ex.getRequestURI().getPath().equals("/upload/storage/v1/b/bucket/o") && ex.getRequestMethod().equals("POST") ) ); } final OptionalBytesReference updateResult = safeAwait( l -> container.compareAndExchangeRegister(randomPurpose(), key, new BytesArray(data), new BytesArray(updatedData), l) ); assertThat(updateResult.bytesReference(), equalBytes(new BytesArray(data))); assertEquals(0, requestHandlers.size()); container.delete(randomPurpose()); } public void testContentsChangeWhileStreaming() throws IOException { GoogleCloudStorageHttpHandler handler = new GoogleCloudStorageHttpHandler("bucket"); httpServer.createContext("/", handler); // The blob needs to be large enough that it won't be entirely buffered on the first request final int enoughBytesToNotBeEntirelyBuffered = Math.toIntExact(ByteSizeValue.ofMb(30).getBytes()); final BlobContainer container = createBlobContainer(1, null, null, null, null, null, null); final String key = randomIdentifier(); byte[] initialValue = randomByteArrayOfLength(enoughBytesToNotBeEntirelyBuffered); container.writeBlob(randomPurpose(), key, new BytesArray(initialValue), true); BytesReference reference = readFully(container.readBlob(randomPurpose(), key)); assertThat(reference, equalBytes(new BytesArray(initialValue))); try (InputStream inputStream = container.readBlob(randomPurpose(), key)) { // Trigger the first chunk to load int read = inputStream.read(); assert read != -1; // Restart the server (this triggers a retry) restartHttpServer(); httpServer.createContext("/", handler); // Update the file byte[] updatedValue = randomByteArrayOfLength(enoughBytesToNotBeEntirelyBuffered); container.writeBlob(randomPurpose(), key, new BytesArray(updatedValue), false); // Read the rest of the stream, it should throw because the contents changed String message = assertThrows(NoSuchFileException.class, () -> readFully(inputStream)).getMessage(); assertThat( message, startsWith( "Blob object [" + container.path().buildAsString() + key + "] generation [1] unavailable on resume (contents changed, or object deleted):" ) ); } } private void restartHttpServer() throws IOException { InetSocketAddress currentAddress = httpServer.getAddress(); httpServer.stop(0); httpServer = MockHttpServer.createHttp(currentAddress, 0); httpServer.start(); } private HttpHandler safeHandler(HttpHandler handler) { final HttpHandler loggingHandler = ESMockAPIBasedRepositoryIntegTestCase.wrap(handler, logger); return exchange -> { try { loggingHandler.handle(exchange); } finally { exchange.close(); } }; } }
GoogleCloudStorageBlobContainerRetriesTests
java
apache__camel
dsl/camel-endpointdsl/src/test/java/org/apache/camel/builder/endpoint/SqlTest.java
{ "start": 1270, "end": 4792 }
class ____ extends BaseEndpointDslTest { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testSqlDataSourceInstance() throws Exception { context.start(); final DataSource ds = new SimpleDriverDataSource(); context.getRegistry().bind("myDS", ds); context.addRoutes(new EndpointRouteBuilder() { @Override public void configure() throws Exception { SqlEndpointBuilderFactory.SqlEndpointBuilder builder = sql("SELECT * FROM FOO").dataSource(ds); Endpoint endpoint = builder.resolve(context); assertNotNull(endpoint); SqlEndpoint se = assertIsInstanceOf(SqlEndpoint.class, endpoint); assertEquals("SELECT * FROM FOO", se.getQuery()); assertSame(ds, se.getDataSource()); } }); context.stop(); } @Test public void testSqlDataSourceRefSyntax() throws Exception { context.start(); final DataSource ds = new SimpleDriverDataSource(); context.getRegistry().bind("myDS", ds); context.addRoutes(new EndpointRouteBuilder() { @Override public void configure() throws Exception { SqlEndpointBuilderFactory.SqlEndpointBuilder builder = sql("SELECT * FROM FOO").dataSource("#myDS"); Endpoint endpoint = builder.resolve(context); assertNotNull(endpoint); SqlEndpoint se = assertIsInstanceOf(SqlEndpoint.class, endpoint); assertEquals("SELECT * FROM FOO", se.getQuery()); assertSame(ds, se.getDataSource()); } }); context.stop(); } @Test public void testSqlDataSourceRefBeanSyntax() throws Exception { context.start(); final DataSource ds = new SimpleDriverDataSource(); context.getRegistry().bind("myDS", ds); context.addRoutes(new EndpointRouteBuilder() { @Override public void configure() throws Exception { SqlEndpointBuilderFactory.SqlEndpointBuilder builder = sql("SELECT * FROM FOO").dataSource("#bean:myDS"); Endpoint endpoint = builder.resolve(context); assertNotNull(endpoint); SqlEndpoint se = assertIsInstanceOf(SqlEndpoint.class, endpoint); assertEquals("SELECT * FROM FOO", se.getQuery()); assertSame(ds, se.getDataSource()); } }); context.stop(); } @Test public void testSqlDataSourceType() throws Exception { context.start(); final DataSource ds = new SimpleDriverDataSource(); context.getRegistry().bind("myDS", ds); context.addRoutes(new EndpointRouteBuilder() { @Override public void configure() throws Exception { SqlEndpointBuilderFactory.SqlEndpointBuilder builder = sql("SELECT * FROM FOO").dataSource("#type:javax.sql.DataSource"); Endpoint endpoint = builder.resolve(context); assertNotNull(endpoint); SqlEndpoint se = assertIsInstanceOf(SqlEndpoint.class, endpoint); assertEquals("SELECT * FROM FOO", se.getQuery()); assertSame(ds, se.getDataSource()); } }); context.stop(); } }
SqlTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/SpatialAggregateFunction.java
{ "start": 2493, "end": 3127 }
class ____ as variation return Objects.hash(getClass(), children(), fieldExtractPreference); } @Override public boolean equals(Object obj) { if (super.equals(obj)) { SpatialAggregateFunction other = (SpatialAggregateFunction) obj; return Objects.equals(other.field(), field()) && Objects.equals(other.parameters(), parameters()) && Objects.equals(other.fieldExtractPreference, fieldExtractPreference); } return false; } public FieldExtractPreference fieldExtractPreference() { return fieldExtractPreference; } }
name
java
micronaut-projects__micronaut-core
management/src/main/java/io/micronaut/management/health/aggregator/HealthAggregator.java
{ "start": 1055, "end": 1653 }
interface ____<T extends HealthResult> { /** * @param indicators The health indicators to aggregate. * @param healthLevelOfDetail The {@link HealthLevelOfDetail} * @return An aggregated response. */ Publisher<T> aggregate(HealthIndicator[] indicators, HealthLevelOfDetail healthLevelOfDetail); /** * @param name The name of the new health result * @param results The health results to aggregate. * @return An aggregated {@link HealthResult}. */ Publisher<HealthResult> aggregate(String name, Publisher<HealthResult> results); }
HealthAggregator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/rescore/QueryRescorer.java
{ "start": 6447, "end": 7784 }
class ____ extends RescoreContext { private ParsedQuery query; private float queryWeight = 1.0f; private float rescoreQueryWeight = 1.0f; private QueryRescoreMode scoreMode; public QueryRescoreContext(int windowSize) { super(windowSize, QueryRescorer.INSTANCE); this.scoreMode = QueryRescoreMode.Total; } public void setQuery(ParsedQuery query) { this.query = query; } @Override public List<ParsedQuery> getParsedQueries() { return Collections.singletonList(query); } public ParsedQuery parsedQuery() { return query; } public float queryWeight() { return queryWeight; } public float rescoreQueryWeight() { return rescoreQueryWeight; } public QueryRescoreMode scoreMode() { return scoreMode; } public void setRescoreQueryWeight(float rescoreQueryWeight) { this.rescoreQueryWeight = rescoreQueryWeight; } public void setQueryWeight(float queryWeight) { this.queryWeight = queryWeight; } public void setScoreMode(QueryRescoreMode scoreMode) { this.scoreMode = scoreMode; } } }
QueryRescoreContext
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/AbstractJavaElement.java
{ "start": 19233, "end": 23536 }
class ____<T> {}" boolean isRaw = typeMirrorArguments != null; for (TypeParameterElement typeParameter : typeParameters) { String variableName = typeParameter.getSimpleName().toString(); resolved.put( variableName, newClassElement(getNativeType(), typeParameter.asType(), parentTypeArguments, visitedTypes, true, isRaw, null, null, null) ); } } return resolved; } private ClassElement resolveTypeVariable(JavaNativeElement owner, Map<String, ClassElement> parentTypeArguments, Set<TypeMirror> visitedTypes, TypeVariable tv, boolean isRawType, String doc) { String variableName = tv.asElement().getSimpleName().toString(); ClassElement resolvedBound = parentTypeArguments.get(variableName); List<JavaClassElement> bounds = null; io.micronaut.inject.ast.Element declaredElement = this; JavaClassElement resolved = null; int arrayDimensions = 0; if (resolvedBound != null) { if (resolvedBound instanceof WildcardElement wildcardElement) { if (wildcardElement.isBounded()) { return wildcardElement; } } else if (resolvedBound instanceof JavaGenericPlaceholderElement javaGenericPlaceholderElement) { bounds = javaGenericPlaceholderElement.getBounds(); declaredElement = javaGenericPlaceholderElement.getRequiredDeclaringElement(); resolved = javaGenericPlaceholderElement.getResolvedInternal(); isRawType = javaGenericPlaceholderElement.isRawType(); arrayDimensions = javaGenericPlaceholderElement.getArrayDimensions(); } else if (resolvedBound instanceof JavaClassElement resolvedClassElement) { resolved = resolvedClassElement; isRawType = resolvedClassElement.isRawType(); arrayDimensions = resolvedClassElement.getArrayDimensions(); } else { // Most likely primitive array return resolvedBound; } } if (bounds == null) { bounds = new ArrayList<>(); TypeMirror upperBound = tv.getUpperBound(); // type variable is still free. List<? extends TypeMirror> boundsUnresolved = upperBound instanceof IntersectionType it ? it.getBounds() : Collections.singletonList(upperBound); boundsUnresolved.stream() .map(tm -> (JavaClassElement) newClassElement(owner, tm, parentTypeArguments, visitedTypes, true, doc)) .forEach(bounds::add); } return new JavaGenericPlaceholderElement(new JavaNativeElement.Placeholder(tv.asElement(), tv, getNativeType()), tv, declaredElement, resolved, bounds, elementAnnotationMetadataFactory, arrayDimensions, isRawType, doc); } private boolean hasModifier(Modifier modifier) { return Objects.requireNonNull(nativeElement.element()).getModifiers().contains(modifier); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof io.micronaut.inject.ast.Element)) { return false; } io.micronaut.inject.ast.Element that = (io.micronaut.inject.ast.Element) o; if (that instanceof TypedElement element && element.isPrimitive()) { return false; } // Do not check if classes match, sometimes it's an anonymous one if (!(that instanceof AbstractJavaElement abstractJavaElement)) { return false; } // We allow to match different subclasses like JavaClassElement, JavaPlaceholder, JavaWildcard etc return Objects.equals(nativeElement.element(), abstractJavaElement.getNativeType().element()); } @Override public int hashCode() { return Objects.requireNonNull(nativeElement.element()).hashCode(); } }
List
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 17309, "end": 17620 }
class ____ extends Parent { public void doTest() { before(42); } } """) .addOutputLines( "Child.java", """ package com.google.test; import java.time.Duration; public final
Child
java
spring-projects__spring-boot
module/spring-boot-gson/src/main/java/org/springframework/boot/gson/autoconfigure/GsonBuilderCustomizer.java
{ "start": 1010, "end": 1183 }
interface ____ { /** * Customize the GsonBuilder. * @param gsonBuilder the GsonBuilder to customize */ void customize(GsonBuilder gsonBuilder); }
GsonBuilderCustomizer
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/list/ListAssert_filteredOn_BaseTest.java
{ "start": 844, "end": 1114 }
class ____ { protected static List<TolkienCharacter> hobbits() { TolkienCharacter frodo = TolkienCharacter.of("Frodo", 33, HOBBIT); TolkienCharacter sam = TolkienCharacter.of("Sam", 35, HOBBIT); return asList(frodo, sam); } }
ListAssert_filteredOn_BaseTest
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/signatures/PublisherSignatureTest.java
{ "start": 3735, "end": 4171 }
class ____ extends Spy { @Outgoing("A") public Publisher<Message<Integer>> produce() { return ReactiveStreams.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) .map(Message::of) .buildRs(); } @Incoming("A") public void consume(Integer item) { items.add(item); } } @ApplicationScoped public static
BeanProducingAPublisherOfMessage
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/node/JsonNodeConversionsTest.java
{ "start": 1244, "end": 1346 }
class ____ { } // Deserializer to trigger the problem described in [JACKSON-554] static
LeafMixIn
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/test/java/io/github/resilience4j/SpringBootCommonTest.java
{ "start": 12757, "end": 12877 }
class ____ extends AbstractRateLimiterConfigurationOnMissingBean { }
RateLimiterConfigurationOnMissingBean
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldBeEqualNormalizingWhitespace_create_Test.java
{ "start": 1284, "end": 1997 }
class ____ { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeEqualNormalizingWhitespace(" my\tfoo bar ", " myfoo bar "); // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting actual:%n" + " \" my\tfoo bar \"%n" + "to be equal to:%n" + " \" myfoo bar \"%n" + "after whitespace differences are normalized")); } }
ShouldBeEqualNormalizingWhitespace_create_Test
java
quarkusio__quarkus
core/devmode-spi/src/main/java/io/quarkus/dev/testing/ExceptionReporting.java
{ "start": 243, "end": 600 }
class ____ { private static volatile Consumer<Throwable> listener; public static void notifyException(Throwable exception) { Consumer<Throwable> l = listener; if (l != null) { l.accept(exception); } } public static void setListener(Consumer<Throwable> l) { listener = l; } }
ExceptionReporting
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
{ "start": 42328, "end": 44935 }
interface ____);</li> * <li>the number of actual and formal parameters differ;</li> * <li>an unwrapping conversion for primitive arguments fails; or</li> * <li>after possible unwrapping, a parameter value can't be converted to the corresponding formal parameter type by a * method invocation conversion.</li> * </ul> * @throws InvocationTargetException Thrown if the underlying method throws an exception. * @throws NullPointerException Thrown if the specified {@code object} is null. * @throws ExceptionInInitializerError Thrown if the initialization provoked by this method fails. * @see SecurityManager#checkPermission * @since 3.5 */ public static Object invokeMethod(final Object object, final boolean forceAccess, final String methodName, final Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { final Object[] actuals = ArrayUtils.nullToEmpty(args); return invokeMethod(object, forceAccess, methodName, actuals, ClassUtils.toClass(actuals)); } /** * Invokes a named method whose parameter type matches the object type. * * <p> * This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a {@link Boolean} object * would match a {@code boolean} primitive. * </p> * * @param object invoke method on this object. * @param forceAccess force access to invoke method even if it's not accessible. * @param methodName get method with this name. * @param args use these arguments - treat null as empty array. * @param parameterTypes match these parameters - treat null as empty array. * @return The value returned by the invoked method. * @throws NoSuchMethodException Thrown if there is no such accessible method. * @throws IllegalAccessException Thrown if this found {@code Method} is enforcing Java language access control and the underlying method is * inaccessible. * @throws IllegalArgumentException Thrown if: * <ul> * <li>the found {@code Method} is an instance method and the specified {@code object} argument is not an instance of * the
implementor
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java
{ "start": 1521, "end": 3923 }
class ____ extends AbstractExpressionTests { private static final List<String> listOfString = List.of("1", "2", "3"); private static final List<Integer> listOfInteger = List.of(4, 5, 6); private static final TypeDescriptor typeDescriptorForListOfString = new TypeDescriptor(ReflectionUtils.findField(ExpressionWithConversionTests.class, "listOfString")); private static final TypeDescriptor typeDescriptorForListOfInteger = new TypeDescriptor(ReflectionUtils.findField(ExpressionWithConversionTests.class, "listOfInteger")); /** * Test the service can convert what we are about to use in the expression evaluation tests. */ @BeforeAll @SuppressWarnings("unchecked") static void verifyConversionsAreSupportedByStandardTypeConverter() { StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); TypeConverter typeConverter = evaluationContext.getTypeConverter(); // List<Integer> to List<String> assertThat(typeDescriptorForListOfString.getElementTypeDescriptor().getType()) .isEqualTo(String.class); List<String> strings = (List<String>) typeConverter.convertValue(listOfInteger, typeDescriptorForListOfInteger, typeDescriptorForListOfString); assertThat(strings).containsExactly("4", "5", "6"); // List<String> to List<Integer> assertThat(typeDescriptorForListOfInteger.getElementTypeDescriptor().getType()) .isEqualTo(Integer.class); List<Integer> integers = (List<Integer>) typeConverter.convertValue(listOfString, typeDescriptorForListOfString, typeDescriptorForListOfInteger); assertThat(integers).containsExactly(1, 2, 3); } @Test void setParameterizedList() { StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); Expression e = parser.parseExpression("listOfInteger.size()"); assertThat(e.getValue(context, Integer.class)).isZero(); // Assign a List<String> to the List<Integer> field - the component elements should be converted parser.parseExpression("listOfInteger").setValue(context, listOfString); // size now 3 assertThat(e.getValue(context, Integer.class)).isEqualTo(3); // element type correctly Integer Class<?> clazz = parser.parseExpression("listOfInteger[1].getClass()").getValue(context, Class.class); assertThat(clazz).isEqualTo(Integer.class); } @Test void coercionToCollectionOfPrimitive() throws Exception {
ExpressionWithConversionTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialIntersectsCartesianPointDocValuesAndSourceEvaluator.java
{ "start": 3960, "end": 4849 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory left; private final EvalOperator.ExpressionEvaluator.Factory right; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory left, EvalOperator.ExpressionEvaluator.Factory right) { this.source = source; this.left = left; this.right = right; } @Override public SpatialIntersectsCartesianPointDocValuesAndSourceEvaluator get(DriverContext context) { return new SpatialIntersectsCartesianPointDocValuesAndSourceEvaluator(source, left.get(context), right.get(context), context); } @Override public String toString() { return "SpatialIntersectsCartesianPointDocValuesAndSourceEvaluator[" + "left=" + left + ", right=" + right + "]"; } } }
Factory
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ReflectionSupport.java
{ "start": 24718, "end": 26073 }
interface ____ which to find the fields; never {@code null} * @param predicate the field filter; never {@code null} * @param traversalMode the hierarchy traversal mode; never {@code null} * @return a stream of all such fields found; never {@code null} * but potentially empty * @since 1.10 */ @API(status = MAINTAINED, since = "1.10") public static Stream<Field> streamFields(Class<?> clazz, Predicate<Field> predicate, HierarchyTraversalMode traversalMode) { Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null"); return ReflectionUtils.streamFields(clazz, predicate, ReflectionUtils.HierarchyTraversalMode.valueOf(traversalMode.name())); } /** * Try to read the value of a potentially inaccessible field. * * <p>If an exception occurs while reading the field, a failed {@link Try} * is returned that contains the corresponding exception. * * @param field the field to read; never {@code null} * @param instance the instance from which the value is to be read; may * be {@code null} for a static field * @since 1.4 */ @API(status = MAINTAINED, since = "1.4") public static Try<@Nullable Object> tryToReadFieldValue(Field field, @Nullable Object instance) { return ReflectionUtils.tryToReadFieldValue(field, instance); } /** * Find the first {@link Method} of the supplied
in
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/retry/TestDefaultRetryPolicy.java
{ "start": 1288, "end": 4104 }
class ____ { /** Verify FAIL < RETRY < FAILOVER_AND_RETRY. */ @Test public void testRetryDecisionOrdering() throws Exception { assertTrue(RetryPolicy.RetryAction.RetryDecision.FAIL.compareTo( RetryPolicy.RetryAction.RetryDecision.RETRY) < 0); assertTrue(RetryPolicy.RetryAction.RetryDecision.RETRY.compareTo( RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY) < 0); assertTrue(RetryPolicy.RetryAction.RetryDecision.FAIL.compareTo( RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY) < 0); } /** * Verify that the default retry policy correctly retries * RetriableException when defaultRetryPolicyEnabled is enabled. * * @throws IOException */ @Test public void testWithRetriable() throws Exception { Configuration conf = new Configuration(); RetryPolicy policy = RetryUtils.getDefaultRetryPolicy( conf, "Test.No.Such.Key", true, // defaultRetryPolicyEnabled = true "Test.No.Such.Key", "10000,6", null); RetryPolicy.RetryAction action = policy.shouldRetry( new RetriableException("Dummy exception"), 0, 0, true); assertThat(action.action) .isEqualTo(RetryPolicy.RetryAction.RetryDecision.RETRY); } /** * Verify that the default retry policy correctly retries * a RetriableException wrapped in a RemoteException when * defaultRetryPolicyEnabled is enabled. * * @throws IOException */ @Test public void testWithWrappedRetriable() throws Exception { Configuration conf = new Configuration(); RetryPolicy policy = RetryUtils.getDefaultRetryPolicy( conf, "Test.No.Such.Key", true, // defaultRetryPolicyEnabled = true "Test.No.Such.Key", "10000,6", null); RetryPolicy.RetryAction action = policy.shouldRetry( new RemoteException(RetriableException.class.getName(), "Dummy exception"), 0, 0, true); assertThat(action.action) .isEqualTo(RetryPolicy.RetryAction.RetryDecision.RETRY); } /** * Verify that the default retry policy does *not* retry * RetriableException when defaultRetryPolicyEnabled is disabled. * * @throws IOException */ @Test public void testWithRetriableAndRetryDisabled() throws Exception { Configuration conf = new Configuration(); RetryPolicy policy = RetryUtils.getDefaultRetryPolicy( conf, "Test.No.Such.Key", false, // defaultRetryPolicyEnabled = false "Test.No.Such.Key", "10000,6", null); RetryPolicy.RetryAction action = policy.shouldRetry( new RetriableException("Dummy exception"), 0, 0, true); assertThat(action.action).isEqualTo( RetryPolicy.RetryAction.RetryDecision.FAIL); } }
TestDefaultRetryPolicy
java
apache__camel
components/camel-aws/camel-aws-secrets-manager/src/generated/java/org/apache/camel/component/aws/secretsmanager/SecretsManagerEndpointUriFactory.java
{ "start": 528, "end": 3022 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":label"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(20); props.add("accessKey"); props.add("binaryPayload"); props.add("label"); props.add("lazyStartProducer"); props.add("operation"); props.add("overrideEndpoint"); props.add("pojoRequest"); props.add("profileCredentialsName"); props.add("proxyHost"); props.add("proxyPort"); props.add("proxyProtocol"); props.add("region"); props.add("secretKey"); props.add("secretsManagerClient"); props.add("sessionToken"); props.add("trustAllCertificates"); props.add("uriEndpointOverride"); props.add("useDefaultCredentialsProvider"); props.add("useProfileCredentialsProvider"); props.add("useSessionCredentials"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(3); secretProps.add("accessKey"); secretProps.add("secretKey"); secretProps.add("sessionToken"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "aws-secrets-manager".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "label", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
SecretsManagerEndpointUriFactory
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/IntoMapTest.java
{ "start": 5261, "end": 5721 }
interface ____ { @Binds @IntoMap @StringKey("hello") Object binds(String value); @dagger.Provides static String world() { return "world"; } } public void testBinds() { Injector injector = Guice.createInjector(DaggerAdapter.from(BindsModule.class)); Map<String, Object> map = injector.getInstance(new Key<Map<String, Object>>() {}); assertThat(map).containsExactly("hello", "world"); } @MapKey @
BindsModule
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/AssertTimeoutPreemptivelyAssertionsTests.java
{ "start": 1416, "end": 8315 }
class ____ { private static final Duration PREEMPTIVE_TIMEOUT = ofMillis(WINDOWS.isCurrentOs() ? 1000 : 100); private static final ThreadLocal<AtomicBoolean> changed = ThreadLocal.withInitial(() -> new AtomicBoolean(false)); private final Executable nix = () -> { }; // --- executable ---------------------------------------------------------- @Test void assertTimeoutPreemptivelyForExecutableThatCompletesBeforeTheTimeout() { changed.get().set(false); assertTimeoutPreemptively(ofMillis(500), () -> changed.get().set(true)); assertFalse(changed.get().get(), "should have executed in a different thread"); assertTimeoutPreemptively(ofMillis(500), nix, "message"); assertTimeoutPreemptively(ofMillis(500), nix, () -> "message"); } @Test void assertTimeoutPreemptivelyForExecutableThatThrowsAnException() { RuntimeException exception = assertThrows(RuntimeException.class, () -> assertTimeoutPreemptively(ofMillis(500), () -> { throw new RuntimeException("not this time"); })); assertMessageEquals(exception, "not this time"); } @Test void assertTimeoutPreemptivelyForExecutableThatThrowsAnAssertionFailedError() { AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> assertTimeoutPreemptively(ofMillis(500), () -> fail("enigma"))); assertMessageEquals(exception, "enigma"); } @Test void assertTimeoutPreemptivelyForExecutableThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, this::waitForInterrupt)); assertMessageEquals(error, "execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyWithMessageForExecutableThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, this::waitForInterrupt, "Tempus Fugit")); assertMessageEquals(error, "Tempus Fugit ==> execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyWithMessageSupplierForExecutableThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, this::waitForInterrupt, () -> "Tempus" + " " + "Fugit")); assertMessageEquals(error, "Tempus Fugit ==> execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyWithMessageSupplierForExecutableThatCompletesBeforeTheTimeout() { assertTimeoutPreemptively(ofMillis(500), nix, () -> "Tempus" + " " + "Fugit"); } // --- supplier ------------------------------------------------------------ @Test void assertTimeoutPreemptivelyForSupplierThatCompletesBeforeTheTimeout() { changed.get().set(false); String result = assertTimeoutPreemptively(ofMillis(500), () -> { changed.get().set(true); return "Tempus Fugit"; }); assertFalse(changed.get().get(), "should have executed in a different thread"); assertEquals("Tempus Fugit", result); assertEquals("Tempus Fugit", assertTimeoutPreemptively(ofMillis(500), () -> "Tempus Fugit", "message")); assertEquals("Tempus Fugit", assertTimeoutPreemptively(ofMillis(500), () -> "Tempus Fugit", () -> "message")); } @Test void assertTimeoutPreemptivelyForSupplierThatThrowsAnException() { RuntimeException exception = assertThrows(RuntimeException.class, () -> { assertTimeoutPreemptively(ofMillis(500), () -> ExceptionUtils.throwAsUncheckedException(new RuntimeException("not this time"))); }); assertMessageEquals(exception, "not this time"); } @Test void assertTimeoutPreemptivelyForSupplierThatThrowsAnAssertionFailedError() { AssertionFailedError exception = assertThrows(AssertionFailedError.class, () -> { assertTimeoutPreemptively(ofMillis(500), () -> { fail("enigma"); return "Tempus Fugit"; }); }); assertMessageEquals(exception, "enigma"); } @Test void assertTimeoutPreemptivelyForSupplierThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> { assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, () -> { waitForInterrupt(); return "Tempus Fugit"; }); }); assertMessageEquals(error, "execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyWithMessageForSupplierThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> { assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, () -> { waitForInterrupt(); return "Tempus Fugit"; }, "Tempus Fugit"); }); assertMessageEquals(error, "Tempus Fugit ==> execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyWithMessageSupplierForSupplierThatCompletesAfterTheTimeout() { AssertionFailedError error = assertThrows(AssertionFailedError.class, () -> { assertTimeoutPreemptively(PREEMPTIVE_TIMEOUT, () -> { waitForInterrupt(); return "Tempus Fugit"; }, () -> "Tempus" + " " + "Fugit"); }); assertMessageEquals(error, "Tempus Fugit ==> execution timed out after " + PREEMPTIVE_TIMEOUT.toMillis() + " ms"); assertMessageStartsWith(error.getCause(), "Execution timed out in "); assertStackTraceContains(error.getCause(), "CountDownLatch", "await"); } @Test void assertTimeoutPreemptivelyUsesThreadsWithSpecificNamePrefix() { AtomicReference<String> threadName = new AtomicReference<>(""); assertTimeoutPreemptively(ofMillis(1000), () -> threadName.set(Thread.currentThread().getName())); assertThat(threadName.get()) // .withFailMessage("Thread name does not match the expected prefix") // .startsWith("junit-timeout-thread-"); } private void waitForInterrupt() { try { assertFalse(Thread.interrupted(), "Already interrupted"); new CountDownLatch(1).await(); } catch (InterruptedException ignore) { // ignore } } /** * Assert the given stack trace elements contain an element with the given
AssertTimeoutPreemptivelyAssertionsTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StGeohashFromFieldAndLiteralEvaluator.java
{ "start": 1092, "end": 3506 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(StGeohashFromFieldAndLiteralEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator wkbBlock; private final int precision; private final DriverContext driverContext; private Warnings warnings; public StGeohashFromFieldAndLiteralEvaluator(Source source, EvalOperator.ExpressionEvaluator wkbBlock, int precision, DriverContext driverContext) { this.source = source; this.wkbBlock = wkbBlock; this.precision = precision; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (BytesRefBlock wkbBlockBlock = (BytesRefBlock) wkbBlock.eval(page)) { return eval(page.getPositionCount(), wkbBlockBlock); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += wkbBlock.baseRamBytesUsed(); return baseRamBytesUsed; } public LongBlock eval(int positionCount, BytesRefBlock wkbBlockBlock) { try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!wkbBlockBlock.isNull(p)) { allBlocksAreNulls = false; } if (allBlocksAreNulls) { result.appendNull(); continue position; } try { StGeohash.fromFieldAndLiteral(result, p, wkbBlockBlock, this.precision); } catch (IllegalArgumentException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "StGeohashFromFieldAndLiteralEvaluator[" + "wkbBlock=" + wkbBlock + ", precision=" + precision + "]"; } @Override public void close() { Releasables.closeExpectNoException(wkbBlock); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
StGeohashFromFieldAndLiteralEvaluator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/NonCanonicalStaticMemberImportTest.java
{ "start": 2614, "end": 2957 }
class ____ {} """) .doTest(); } // We can't test e.g. a.B.Inner.CONST (a double non-canonical reference), because // they're illegal. @Test public void positiveClassAndField() { compilationHelper .addSourceLines( "a/Super.java", """ package a; public
Test