language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/depth/NoDepthTests.java | {
"start": 1287,
"end": 3641
} | class ____ {
@Test
public void testWithMax() {
testIt( true );
}
@Test
public void testNoMax() {
testIt( false );
}
private void testIt(boolean configureMaxDepth) {
try ( final SessionFactoryImplementor sf = buildSessionFactory( configureMaxDepth ) ) {
inTransaction( sf, (session) -> {
session.createSelectionQuery( "from SysModule" ).getResultList();
session.createSelectionQuery( "from SysModule2" ).getResultList();
} );
}
}
private static SessionFactoryImplementor buildSessionFactory(boolean configureMax) {
final StandardServiceRegistryBuilder registryBuilder = ServiceRegistryUtil.serviceRegistryBuilder();
registryBuilder.applySetting( FORMAT_SQL, "true" );
registryBuilder.applySetting( HBM2DDL_AUTO, Action.CREATE_DROP );
registryBuilder.applySetting( MAX_FETCH_DEPTH, configureMax ? "10" : "" );
return new MetadataSources( registryBuilder.build() )
.addAnnotatedClasses( SysModule.class, SysModule2.class )
.buildMetadata()
.buildSessionFactory()
.unwrap( SessionFactoryImplementor.class );
}
@Test
public void testWithMaxJpa() {
testItJpa( true );
}
@Test
public void testNoMaxJpa() {
testItJpa( false );
}
private void testItJpa(boolean configureMax) {
final JavaArchive par = ShrinkWrap.create( JavaArchive.class, "fetch-depth.par" );
par.addClasses( SysModule.class );
par.addAsResource( "units/many2many/fetch-depth.xml", "META-INF/persistence.xml" );
try ( final ShrinkWrapClassLoader classLoader = new ShrinkWrapClassLoader( par ) ) {
final Map<String, Object> settings = new HashMap<>( Map.of(
CLASSLOADERS, Arrays.asList( classLoader, getClass().getClassLoader() ),
MAX_FETCH_DEPTH, configureMax ? "10" : "",
HBM2DDL_AUTO, Action.CREATE_DROP,
FORMAT_SQL, "true"
) );
ServiceRegistryUtil.applySettings( settings );
final EntityManagerFactory emf = createEntityManagerFactory( "fetch-depth", settings );
try ( final SessionFactoryImplementor sf = emf.unwrap( SessionFactoryImplementor.class ) ) {
// play around with the SF and make sure it is operable
inTransaction( sf, (s) -> {
s.createSelectionQuery( "from SysModule" ).list();
s.createSelectionQuery( "from SysModule2" ).list();
});
}
}
catch (IOException e) {
throw new RuntimeException( "re-throw", e );
}
}
}
| NoDepthTests |
java | netty__netty | example/src/main/java/io/netty/example/spdy/server/SpdyServerHandler.java | {
"start": 1929,
"end": 3504
} | class ____ extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest req = (HttpRequest) msg;
if (is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER));
}
boolean keepAlive = isKeepAlive(req);
ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
if (keepAlive) {
if (req.protocolVersion().equals(HTTP_1_0)) {
response.headers().set(CONNECTION, KEEP_ALIVE);
}
ctx.write(response);
} else {
// Tell the client we're going to close the connection.
response.headers().set(CONNECTION, CLOSE);
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
| SpdyServerHandler |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/JobStatusInfoHeaders.java | {
"start": 1513,
"end": 2643
} | class ____
implements RuntimeMessageHeaders<EmptyRequestBody, JobStatusInfo, JobMessageParameters> {
private static final JobStatusInfoHeaders INSTANCE = new JobStatusInfoHeaders();
@Override
public Class<EmptyRequestBody> getRequestClass() {
return EmptyRequestBody.class;
}
@Override
public Class<JobStatusInfo> getResponseClass() {
return JobStatusInfo.class;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
}
@Override
public JobMessageParameters getUnresolvedMessageParameters() {
return new JobMessageParameters();
}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.GET;
}
@Override
public String getTargetRestEndpointURL() {
return "/jobs/:" + JobIDPathParameter.KEY + "/status";
}
public static JobStatusInfoHeaders getInstance() {
return INSTANCE;
}
@Override
public String getDescription() {
return "Returns the current status of a job execution.";
}
}
| JobStatusInfoHeaders |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java | {
"start": 1298,
"end": 2755
} | class ____ extends ProxyProcessorSupport
implements SmartInstantiationAwareBeanPostProcessor {
protected @Nullable Advisor advisor;
protected boolean beforeExistingAdvisors = false;
private final Map<Class<?>, Boolean> eligibleBeans = new ConcurrentHashMap<>(256);
/**
* Set whether this post-processor's advisor is supposed to apply before
* existing advisors when encountering a pre-advised object.
* <p>Default is "false", applying the advisor after existing advisors, i.e.
* as close as possible to the target method. Switch this to "true" in order
* for this post-processor's advisor to wrap existing advisors as well.
* <p>Note: Check the concrete post-processor's javadoc whether it possibly
* changes this flag by default, depending on the nature of its advisor.
*/
public void setBeforeExistingAdvisors(boolean beforeExistingAdvisors) {
this.beforeExistingAdvisors = beforeExistingAdvisors;
}
@Override
public Class<?> determineBeanType(Class<?> beanClass, String beanName) {
if (this.advisor != null && isEligible(beanClass)) {
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
proxyFactory.setTargetClass(beanClass);
if (!proxyFactory.isProxyTargetClass()) {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
proxyFactory.addAdvisor(this.advisor);
customizeProxyFactory(proxyFactory);
// Use original ClassLoader if bean | AbstractAdvisingBeanPostProcessor |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/main/java/org/hibernate/processor/HibernateProcessor.java | {
"start": 5985,
"end": 34585
} | class ____ extends AbstractProcessor {
/**
* Debug logging from the processor
*/
public static final String DEBUG_OPTION = "debug";
/**
* Path to a {@code persistence.xml} file
*/
public static final String PERSISTENCE_XML_OPTION = "persistenceXml";
/**
* Path to an {@code orm.xml} file
*/
public static final String ORM_XML_OPTION = "ormXml";
/**
* Controls whether the processor should consider XML files
*/
public static final String FULLY_ANNOTATION_CONFIGURED_OPTION = "fullyAnnotationConfigured";
/**
* Controls whether the processor should only load XML files when there have been changes
*/
public static final String LAZY_XML_PARSING = "lazyXmlParsing";
/**
* Whether the {@code jakarta.annotation.Generated} annotation should be added to
* the generated classes
*/
public static final String ADD_GENERATED_ANNOTATION = "addGeneratedAnnotation";
/**
* Assuming that {@linkplain #ADD_GENERATED_ANNOTATION} is enabled, this option controls
* whether {@code @Generated#date} should be populated.
*/
public static final String ADD_GENERATION_DATE = "addGenerationDate";
/**
* A comma-separated list of warnings to suppress, or simply {@code true}
* if {@code @SuppressWarnings({"deprecation","rawtypes"})} should be
* added to the generated classes.
*/
public static final String ADD_SUPPRESS_WARNINGS_ANNOTATION = "addSuppressWarningsAnnotation";
/**
* Option to suppress generation of the Jakarta Data static metamodel,
* even when Jakarta Data is available on the build path.
*/
public static final String SUPPRESS_JAKARTA_DATA_METAMODEL = "suppressJakartaDataMetamodel";
/**
* Option to include only certain types, according to a list of patterns.
* The wildcard character is {@code *}, and patterns are comma-separated.
* For example: {@code *.entity.*,*Repository}. The default include is
* simply {@code *}, meaning that all types are included.
*/
public static final String INCLUDE = "include";
/**
* Option to exclude certain types, according to a list of patterns.
* The wildcard character is {@code *}, and patterns are comma-separated.
* For example: {@code *.framework.*,*$$}. The default exclude is
* empty.
*/
public static final String EXCLUDE = "exclude";
/**
* Option to suppress creation of a filesystem-based index of entity
* types and enums for use by the query validator. By default, and
* index is created.
*/
public static final String INDEX = "index";
private static final boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = false;
// dupe of ProcessorSessionFactory.ENTITY_INDEX for reasons of modularity
public static final String ENTITY_INDEX = "entity.index";
private Context context;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init( processingEnvironment );
context = new Context( processingEnvironment );
context.logMessage(
Diagnostic.Kind.NOTE,
"Hibernate compile-time tooling " + Version.getVersionString()
);
final boolean fullyAnnotationConfigured = handleSettings( processingEnvironment );
if ( !fullyAnnotationConfigured ) {
new JpaDescriptorParser( context ).parseMappingXml();
if ( context.isFullyXmlConfigured() ) {
createMetaModelClasses();
}
}
}
private boolean handleSettings(ProcessingEnvironment environment) {
final PackageElement jakartaInjectPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.inject" );
final PackageElement jakartaAnnotationPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.annotation" );
final PackageElement jakartaContextPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.enterprise.context" );
final PackageElement jakartaTransactionPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.transaction" );
final PackageElement jakartaDataPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.data" );
final PackageElement quarkusOrmPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.orm" );
final PackageElement quarkusReactivePackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.reactive.runtime" );
final PackageElement dataEventPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "jakarta.data.event" );
PackageElement quarkusOrmPanachePackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.orm.panache" );
PackageElement quarkusPanache2Package =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.panache" );
PackageElement quarkusReactivePanachePackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.reactive.panache" );
// This is imported automatically by Quarkus extensions when HR is also imported
PackageElement quarkusReactivePanacheCommonPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "io.quarkus.hibernate.reactive.panache.common" );
if ( packagePresent(quarkusReactivePanachePackage)
&& packagePresent(quarkusOrmPanachePackage) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
"Both Quarkus Hibernate ORM and Hibernate Reactive with Panache detected: this is not supported, so will proceed as if none were there"
);
quarkusOrmPanachePackage = quarkusReactivePanachePackage = null;
}
final PackageElement springBeansPackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "org.springframework.beans.factory" );
final PackageElement springStereotypePackage =
context.getProcessingEnvironment().getElementUtils()
.getPackageElement( "org.springframework.stereotype" );
context.setAddInjectAnnotation( packagePresent(jakartaInjectPackage) );
context.setAddNonnullAnnotation( packagePresent(jakartaAnnotationPackage) );
context.setAddGeneratedAnnotation( packagePresent(jakartaAnnotationPackage) );
context.setAddDependentAnnotation( packagePresent(jakartaContextPackage) );
context.setAddTransactionScopedAnnotation( packagePresent(jakartaTransactionPackage) );
context.setDataEventPackageAvailable( packagePresent(dataEventPackage) );
context.setQuarkusInjection( packagePresent(quarkusOrmPackage) || packagePresent(quarkusReactivePackage) );
context.setUsesQuarkusOrm( packagePresent(quarkusOrmPanachePackage) );
context.setUsesQuarkusReactive( packagePresent(quarkusReactivePanachePackage) );
context.setSpringInjection( packagePresent(springBeansPackage) );
context.setAddComponentAnnotation( packagePresent(springStereotypePackage) );
context.setUsesQuarkusPanache2( packagePresent(quarkusPanache2Package) );
context.setUsesQuarkusReactiveCommon( packagePresent(quarkusReactivePanacheCommonPackage) );
final Map<String, String> options = environment.getOptions();
final boolean suppressJakartaData = parseBoolean( options.get( SUPPRESS_JAKARTA_DATA_METAMODEL ) );
context.setGenerateJakartaDataStaticMetamodel( !suppressJakartaData && packagePresent(jakartaDataPackage) );
final String setting = options.get( ADD_GENERATED_ANNOTATION );
if ( setting != null ) {
context.setAddGeneratedAnnotation( parseBoolean( setting ) );
}
context.setAddGenerationDate( parseBoolean( options.get( ADD_GENERATION_DATE ) ) );
final String suppressedWarnings = options.get( ADD_SUPPRESS_WARNINGS_ANNOTATION );
if ( suppressedWarnings != null ) {
context.setSuppressedWarnings( parseBoolean( suppressedWarnings )
? new String[] {"deprecation", "rawtypes"} // legacy behavior from HHH-12068
: suppressedWarnings.replace( " ", "" ).split( ",\\s*" ) );
}
context.setInclude( options.getOrDefault( INCLUDE, "*" ) );
context.setExclude( options.getOrDefault( EXCLUDE, "" ) );
context.setIndexing( parseBoolean( options.getOrDefault( INDEX, "true" ) ) );
return parseBoolean( options.get( FULLY_ANNOTATION_CONFIGURED_OPTION ) );
}
private static boolean packagePresent(@Nullable PackageElement pack) {
return pack != null
//HHH-18019 ecj always returns a non-null PackageElement
&& !pack.getEnclosedElements().isEmpty();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
// https://hibernate.atlassian.net/browse/METAGEN-45 claims that we need
// if ( roundEnvironment.processingOver() || annotations.size() == 0)
// but that was back on JDK 6 and I don't see why it should be necessary
// - in fact we want to use the last round to run the 'elementsToRedo'
if ( roundEnvironment.processingOver() ) {
final Set<CharSequence> elementsToRedo = context.getElementsToRedo();
if ( !elementsToRedo.isEmpty() ) {
context.logMessage( Diagnostic.Kind.ERROR, "Failed to generate code for " + elementsToRedo );
}
writeIndex();
}
else if ( context.isFullyXmlConfigured() ) {
context.logMessage(
Diagnostic.Kind.OTHER,
"Skipping the processing of annotations since persistence unit is purely XML configured."
);
}
else {
context.logMessage( Diagnostic.Kind.OTHER, "Starting new round" );
try {
processClasses( roundEnvironment );
createMetaModelClasses();
}
catch (Exception e) {
final StringWriter stack = new StringWriter();
e.printStackTrace( new PrintWriter(stack) );
final Throwable cause = e.getCause();
final String message =
cause != null && cause != e
? e.getMessage() + " caused by " + cause.getMessage()
: e.getMessage();
context.logMessage( Diagnostic.Kind.ERROR, "Error running Hibernate processor: " + message );
context.logMessage( Diagnostic.Kind.ERROR, stack.toString() );
}
}
return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}
private boolean included(Element element) {
if ( element instanceof TypeElement || element instanceof PackageElement ) {
final QualifiedNameable nameable = (QualifiedNameable) element;
return context.isIncluded( nameable.getQualifiedName().toString() );
}
else {
return false;
}
}
private void processClasses(RoundEnvironment roundEnvironment) {
for ( CharSequence elementName : new HashSet<>( context.getElementsToRedo() ) ) {
context.logMessage( Diagnostic.Kind.OTHER, "Redoing element '" + elementName + "'" );
final TypeElement typeElement = context.getElementUtils().getTypeElement( elementName );
try {
final AnnotationMetaEntity metaEntity =
AnnotationMetaEntity.create( typeElement, context,
parentMetadata( typeElement, context::getMetaEntity ) );
context.addMetaAuxiliary( metaEntity.getQualifiedName(), metaEntity );
context.removeElementToRedo( elementName );
}
catch (ProcessLaterException processLaterException) {
// leave it there for next time
}
}
for ( Element element : roundEnvironment.getRootElements() ) {
processElement( element, null );
}
}
private void processElement(Element element, @Nullable Element parent) {
try {
inspectRootElement(element, parent, null);
}
catch ( ProcessLaterException processLaterException ) {
if ( element instanceof TypeElement typeElement ) {
context.logMessage(
Diagnostic.Kind.OTHER,
"Could not process '" + element + "' (will redo in next round)"
);
context.addElementToRedo( typeElement.getQualifiedName() );
}
}
}
private @Nullable AnnotationMetaEntity parentMetadata(
@Nullable Element parent, Function<String, @Nullable Object> metamodel) {
if ( parent instanceof TypeElement parentElement
&& metamodel.apply( parentElement.getQualifiedName().toString() )
instanceof AnnotationMetaEntity parentMetaEntity ) {
return parentMetaEntity;
}
else {
return null;
}
}
private boolean hasPackageAnnotation(Element element, String annotation) {
final PackageElement pack = context.getElementUtils().getPackageOf( element ); // null for module descriptor
return pack != null && hasAnnotation( pack, annotation );
}
private void inspectRootElement(Element element, @Nullable Element parent, @Nullable TypeElement primaryEntity) {
if ( !included( element )
|| hasAnnotation( element, Constants.EXCLUDE )
|| hasPackageAnnotation( element, Constants.EXCLUDE )
|| element.getModifiers().contains( Modifier.PRIVATE ) ) {
// skip it completely
return;
}
else if ( isEntityOrEmbeddable( element )
&& !element.getModifiers().contains( Modifier.PRIVATE ) ) {
context.logMessage( Diagnostic.Kind.OTHER, "Processing annotated entity class '" + element + "'" );
handleRootElementAnnotationMirrors( element, parent );
}
else if ( hasAuxiliaryAnnotations( element ) ) {
context.logMessage( Diagnostic.Kind.OTHER, "Processing annotated class '" + element + "'" );
handleRootElementAuxiliaryAnnotationMirrors( element );
}
else if ( element instanceof TypeElement typeElement ) {
final AnnotationMirror repository = getAnnotationMirror( element, JD_REPOSITORY );
if ( repository != null ) {
final AnnotationValue provider = getAnnotationValue( repository, "provider" );
if ( provider == null
|| provider.getValue().toString().isEmpty()
|| provider.getValue().toString().equalsIgnoreCase("hibernate") ) {
context.logMessage( Diagnostic.Kind.OTHER, "Processing repository class '" + element + "'" );
final AnnotationMetaEntity metaEntity =
AnnotationMetaEntity.create( typeElement, context,
parentMetadata( parent, context::getMetaEntity ),
primaryEntity );
if ( metaEntity.isInitialized() ) {
context.addMetaAuxiliary( metaEntity.getQualifiedName(), metaEntity );
}
// otherwise discard it (assume it has query by magical method name stuff)
}
}
else {
for ( Element member : typeElement.getEnclosedElements() ) {
if ( hasAnnotation( member, HQL, SQL, FIND ) ) {
context.logMessage( Diagnostic.Kind.OTHER, "Processing annotated class '" + element + "'" );
final AnnotationMetaEntity metaEntity =
AnnotationMetaEntity.create( typeElement, context,
parentMetadata( parent, context::getMetaEntity ),
primaryEntity );
context.addMetaAuxiliary( metaEntity.getQualifiedName(), metaEntity );
break;
}
}
if ( enclosesEntityOrEmbeddable( element ) ) {
final NonManagedMetamodel metaEntity =
NonManagedMetamodel.create( typeElement, context, false,
parentMetadata( parent, context::getMetamodel ) );
context.addMetaEntity( metaEntity.getQualifiedName(), metaEntity );
if ( context.generateJakartaDataStaticMetamodel() ) {
final NonManagedMetamodel dataMetaEntity =
NonManagedMetamodel.create( typeElement, context, true,
parentMetadata( parent, context::getDataMetaEntity ) );
context.addDataMetaEntity( dataMetaEntity.getQualifiedName(), dataMetaEntity );
}
}
}
}
if ( isClassRecordOrInterfaceType( element ) ) {
for ( final Element child : element.getEnclosedElements() ) {
if ( isClassRecordOrInterfaceType( child ) ) {
processElement( child, element );
}
}
}
}
private void createMetaModelClasses() {
for ( Metamodel aux : context.getMetaAuxiliaries() ) {
if ( !context.isAlreadyGenerated(aux)
&& !isClassRecordOrInterfaceType( aux.getElement().getEnclosingElement() ) ) {
context.logMessage( Diagnostic.Kind.OTHER,
"Writing metamodel for auxiliary '" + aux + "'" );
ClassWriter.writeFile( aux, context );
context.markGenerated(aux);
}
}
for ( Metamodel entity : context.getMetaEntities() ) {
if ( !context.isAlreadyGenerated( entity ) && !isMemberType( entity.getElement() ) ) {
context.logMessage( Diagnostic.Kind.OTHER,
"Writing Jakarta Persistence metamodel for entity '" + entity + "'" );
ClassWriter.writeFile( entity, context );
context.markGenerated(entity);
}
}
for ( Metamodel entity : context.getDataMetaEntities() ) {
if ( !context.isAlreadyGenerated( entity ) && !isMemberType( entity.getElement() ) ) {
context.logMessage( Diagnostic.Kind.OTHER,
"Writing Jakarta Data metamodel for entity '" + entity + "'" );
ClassWriter.writeFile( entity, context );
context.markGenerated(entity);
}
}
processEmbeddables( context.getMetaEmbeddables() );
processEmbeddables( context.getDataMetaEmbeddables() );
}
/**
* We cannot process the delayed classes in any order.
* There might be dependencies between them.
* We need to process the toplevel classes first.
*/
private void processEmbeddables(Collection<Metamodel> models) {
while ( !models.isEmpty() ) {
final Set<Metamodel> processed = new HashSet<>();
final int toProcessCountBeforeLoop = models.size();
for ( Metamodel metamodel : models ) {
// see METAGEN-36
if ( context.isAlreadyGenerated(metamodel) ) {
processed.add( metamodel );
}
else if ( !modelGenerationNeedsToBeDeferred(models, metamodel ) ) {
context.logMessage(
Diagnostic.Kind.OTHER,
"Writing metamodel for embeddable " + metamodel
);
ClassWriter.writeFile( metamodel, context );
context.markGenerated(metamodel);
processed.add( metamodel );
}
}
models.removeAll( processed );
if ( models.size() >= toProcessCountBeforeLoop ) {
context.logMessage(
Diagnostic.Kind.ERROR,
"Potential endless loop in generation of entities."
);
}
}
}
private boolean modelGenerationNeedsToBeDeferred(Collection<Metamodel> entities, Metamodel containedEntity) {
final Element element = containedEntity.getElement();
if ( element instanceof TypeElement ) {
final ContainsAttributeTypeVisitor visitor =
new ContainsAttributeTypeVisitor( (TypeElement) element, context );
for ( Metamodel entity : entities ) {
if ( !entity.equals( containedEntity ) ) {
final List<? extends Element> enclosedElements =
entity.getElement().getEnclosedElements();
for ( Element subElement : fieldsIn(enclosedElements) ) {
final TypeMirror mirror = subElement.asType();
if ( TypeKind.DECLARED == mirror.getKind() ) {
if ( mirror.accept( visitor, subElement ) ) {
return true;
}
}
}
for ( Element subElement : methodsIn(enclosedElements) ) {
final TypeMirror mirror = subElement.asType();
if ( TypeKind.DECLARED == mirror.getKind() ) {
if ( mirror.accept( visitor, subElement ) ) {
return true;
}
}
}
}
}
}
return false;
}
private static boolean enclosesEntityOrEmbeddable(Element element) {
if ( element instanceof TypeElement typeElement ) {
for ( final Element enclosedElement : typeElement.getEnclosedElements() ) {
if ( isEntityOrEmbeddable( enclosedElement )
|| enclosesEntityOrEmbeddable( enclosedElement ) ) {
return true;
}
}
return false;
}
else {
return false;
}
}
private static boolean isEntityOrEmbeddable(Element element) {
return hasAnnotation(
element,
ENTITY,
MAPPED_SUPERCLASS,
EMBEDDABLE
);
}
private boolean hasAuxiliaryAnnotations(Element element) {
return containsAnnotation(
element,
NAMED_QUERY,
NAMED_QUERIES,
NAMED_NATIVE_QUERY,
NAMED_NATIVE_QUERIES,
SQL_RESULT_SET_MAPPING,
SQL_RESULT_SET_MAPPINGS,
NAMED_ENTITY_GRAPH,
NAMED_ENTITY_GRAPHS,
HIB_NAMED_QUERY,
HIB_NAMED_QUERIES,
HIB_NAMED_NATIVE_QUERY,
HIB_NAMED_NATIVE_QUERIES,
HIB_FETCH_PROFILE,
HIB_FETCH_PROFILES,
HIB_FILTER_DEF,
HIB_FILTER_DEFS
);
}
private void handleRootElementAnnotationMirrors(final Element element, @Nullable Element parent) {
if ( isClassRecordOrInterfaceType( element ) ) {
if ( isEntityOrEmbeddable( element ) ) {
final TypeElement typeElement = (TypeElement) element;
indexEntityName( typeElement );
indexEnumFields( typeElement );
indexQueryInterfaces( typeElement );
final String qualifiedName = typeElement.getQualifiedName().toString();
final Metamodel alreadyExistingMetaEntity =
tryGettingExistingEntityFromContext( typeElement, qualifiedName );
if ( alreadyExistingMetaEntity != null && alreadyExistingMetaEntity.isMetaComplete() ) {
context.logMessage(
Diagnostic.Kind.OTHER,
"Skipping processing of annotations for '" + qualifiedName
+ "' since XML configuration is metadata complete.");
}
else {
final AnnotationMetaEntity parentMetaEntity =
parentMetadata( parent, context::getMetamodel );
final boolean requiresLazyMemberInitialization
= hasAnnotation( element, EMBEDDABLE, MAPPED_SUPERCLASS );
final AnnotationMetaEntity metaEntity =
AnnotationMetaEntity.create( typeElement, context,
requiresLazyMemberInitialization,
true, false, parentMetaEntity, typeElement );
if ( alreadyExistingMetaEntity != null ) {
metaEntity.mergeInMembers( alreadyExistingMetaEntity );
}
addMetamodelToContext( typeElement, metaEntity );
if ( context.generateJakartaDataStaticMetamodel()
// no static metamodel for embeddable classes in Jakarta Data
&& hasAnnotation( element, ENTITY, MAPPED_SUPERCLASS )
// don't generate a Jakarta Data metamodel
// if this entity was partially mapped in XML
&& alreadyExistingMetaEntity == null
// let a handwritten metamodel "override" the generated one
// (this is used in the Jakarta Data TCK)
&& !hasHandwrittenMetamodel(element) ) {
final AnnotationMetaEntity parentDataEntity =
parentMetadata( parent, context::getDataMetaEntity );
final AnnotationMetaEntity dataMetaEntity =
AnnotationMetaEntity.create( typeElement, context,
requiresLazyMemberInitialization,
true, true, parentDataEntity, typeElement );
// final Metamodel alreadyExistingDataMetaEntity =
// tryGettingExistingDataEntityFromContext( mirror, '_' + qualifiedName );
// if ( alreadyExistingDataMetaEntity != null ) {
// dataMetaEntity.mergeInMembers( alreadyExistingDataMetaEntity );
// }
addDataMetamodelToContext( typeElement, dataMetaEntity );
}
}
}
}
}
private static boolean hasHandwrittenMetamodel(Element element) {
return element.getEnclosingElement().getEnclosedElements()
.stream().anyMatch(e -> e.getSimpleName()
.contentEquals('_' + element.getSimpleName().toString()));
}
private void indexQueryInterfaces(TypeElement typeElement) {
for ( Element element : typeElement.getEnclosedElements() ) {
if( element.getKind() == ElementKind.INTERFACE ) {
inspectRootElement( element, typeElement, typeElement );
}
}
}
private void indexEntityName(TypeElement typeElement) {
final AnnotationMirror mirror = getAnnotationMirror( typeElement, ENTITY );
if ( mirror != null ) {
context.addEntityNameMapping( entityName( typeElement, mirror ),
typeElement.getQualifiedName().toString() );
}
}
private static String entityName(TypeElement entityType, AnnotationMirror mirror) {
final String className = entityType.getSimpleName().toString();
final AnnotationValue name = getAnnotationValue(mirror, "name" );
if (name != null) {
final String explicitName = name.getValue().toString();
if ( !explicitName.isEmpty() ) {
return explicitName;
}
}
return className;
}
private void indexEnumFields(TypeElement typeElement) {
for ( Element member : context.getAllMembers(typeElement) ) {
switch ( member.getKind() ) {
case FIELD:
indexEnumValues( member.asType() );
break;
case METHOD:
indexEnumValues( ((ExecutableElement) member).getReturnType() );
break;
}
}
}
private void indexEnumValues(TypeMirror type) {
if ( type.getKind() == TypeKind.DECLARED ) {
final DeclaredType declaredType = (DeclaredType) type;
final TypeElement fieldType = (TypeElement) declaredType.asElement();
if ( fieldType.getKind() == ElementKind.ENUM ) {
for ( Element enumMember : fieldType.getEnclosedElements() ) {
if ( enumMember.getKind() == ElementKind.ENUM_CONSTANT ) {
final Element enclosingElement = fieldType.getEnclosingElement();
final boolean hasOuterType =
enclosingElement.getKind().isClass() || enclosingElement.getKind().isInterface();
context.addEnumValue( fieldType.getQualifiedName().toString(),
fieldType.getSimpleName().toString(),
hasOuterType ? ((TypeElement) enclosingElement).getQualifiedName().toString() : null,
hasOuterType ? enclosingElement.getSimpleName().toString() : null,
enumMember.getSimpleName().toString() );
}
}
}
}
}
private void handleRootElementAuxiliaryAnnotationMirrors(final Element element) {
if ( element instanceof TypeElement ) {
final AnnotationMetaEntity metaEntity =
AnnotationMetaEntity.create( (TypeElement) element, context,
parentMetadata( element.getEnclosingElement(), context::getMetaEntity ) );
context.addMetaAuxiliary( metaEntity.getQualifiedName(), metaEntity );
}
else if ( element instanceof PackageElement ) {
final AnnotationMetaPackage metaEntity =
AnnotationMetaPackage.create( (PackageElement) element, context );
context.addMetaAuxiliary( metaEntity.getQualifiedName(), metaEntity );
}
//TODO: handle PackageElement
}
private @Nullable Metamodel tryGettingExistingEntityFromContext(TypeElement typeElement, String qualifiedName) {
if ( hasAnnotation( typeElement, ENTITY, MAPPED_SUPERCLASS ) ) {
return context.getMetaEntity( qualifiedName );
}
else if ( hasAnnotation( typeElement, EMBEDDABLE ) ) {
return context.getMetaEmbeddable( qualifiedName );
}
return null;
}
private void addMetamodelToContext(TypeElement typeElement, AnnotationMetaEntity entity) {
final String key = entity.getQualifiedName();
if ( hasAnnotation( typeElement, ENTITY ) ) {
context.addMetaEntity( key, entity );
}
else if ( hasAnnotation( typeElement, MAPPED_SUPERCLASS ) ) {
context.addMetaEntity( key, entity );
}
else if ( hasAnnotation( typeElement, EMBEDDABLE ) ) {
context.addMetaEmbeddable( key, entity );
}
}
private void addDataMetamodelToContext(TypeElement typeElement, AnnotationMetaEntity entity) {
final String key = entity.getQualifiedName();
if ( hasAnnotation( typeElement, ENTITY ) ) {
context.addDataMetaEntity( key, entity );
}
else if ( hasAnnotation( typeElement, MAPPED_SUPERCLASS ) ) {
context.addDataMetaEntity( key, entity );
}
else if ( hasAnnotation( typeElement, EMBEDDABLE ) ) {
context.addDataMetaEmbeddable( key, entity );
}
}
private void writeIndex() {
if ( context.isIndexing() ) {
final ProcessingEnvironment processingEnvironment = context.getProcessingEnvironment();
final Elements elementUtils = processingEnvironment.getElementUtils();
context.getEntityNameMappings().forEach( (entityName, className) -> {
try (Writer writer = processingEnvironment.getFiler()
.createResource(
StandardLocation.SOURCE_OUTPUT,
ENTITY_INDEX,
entityName,
elementUtils.getTypeElement( className )
)
.openWriter()) {
writer.append( className );
}
catch (IOException e) {
processingEnvironment.getMessager()
.printMessage( Diagnostic.Kind.WARNING,
"could not write entity index " + e.getMessage() );
}
} );
context.getEnumTypesByValue().forEach( (valueName, enumTypeNames) -> {
try (Writer writer = processingEnvironment.getFiler()
.createResource(
StandardLocation.SOURCE_OUTPUT,
ENTITY_INDEX,
'.' + valueName,
elementUtils.getTypeElement( enumTypeNames.iterator().next() )
)
.openWriter()) {
for ( String enumTypeName : enumTypeNames ) {
writer.append( enumTypeName ).append( " " );
}
}
catch (IOException e) {
processingEnvironment.getMessager()
.printMessage( Diagnostic.Kind.WARNING,
"could not write entity index " + e.getMessage() );
}
} );
}
}
}
| HibernateProcessor |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/ApplicationContextBuilder.java | {
"start": 12462,
"end": 13641
} | class ____ resource resolver
* @return This builder
* @since 5.0
*/
@NonNull ApplicationContextBuilder resourceResolver(@Nullable ClassPathResourceLoader resourceResolver);
/**
* Starts the {@link ApplicationContext}.
*
* @return The running {@link ApplicationContext}
*/
default @NonNull ApplicationContext start() {
return build().start();
}
/**
* Run the {@link ApplicationContext} with the given type. Returning an instance of the type.
*
* @param type The type of the bean to run
* @param <T> The type, a subclass of {@link AutoCloseable}. The close method of the implementation should shut down the context.
* @return The running bean
*/
default @NonNull <T extends AutoCloseable> T run(@NonNull Class<T> type) {
ArgumentUtils.requireNonNull("type", type);
ApplicationContext applicationContext = start();
T bean = applicationContext.getBean(type);
if (bean instanceof LifeCycle<?> lifeCycle) {
if (!lifeCycle.isRunning()) {
lifeCycle.start();
}
}
return bean;
}
}
| path |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ChildListener.java | {
"start": 888,
"end": 976
} | interface ____ {
void childChanged(String path, List<String> children);
}
| ChildListener |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/bean/AutowireConstructorBean.java | {
"start": 916,
"end": 1207
} | class ____ {
private final MyBeanCounter counter;
public AutowireConstructorBean(@Autowired MyBeanCounter counter) {
this.counter = counter;
}
public String hello(String name) {
return "Hello " + name + " at " + counter.count();
}
}
| AutowireConstructorBean |
java | google__gson | gson/src/main/java/com/google/gson/FieldAttributes.java | {
"start": 1820,
"end": 2428
} | class ____ {
* private String bar;
* private List<String> red;
* }
*
* Type listParameterizedType = new TypeToken<List<String>>() {}.getType();
* </pre>
*
* <p>This method would return {@code String.class} for the {@code bar} field and {@code
* listParameterizedType} for the {@code red} field.
*
* @return the specific type declared for this field
*/
public Type getDeclaredType() {
return field.getGenericType();
}
/**
* Returns the {@code Class} object that was declared for this field.
*
* <p>For example, assume the following | Foo |
java | quarkusio__quarkus | extensions/narayana-jta/deployment/src/test/java/io/quarkus/narayana/quarkus/QuarkusTransactionTest.java | {
"start": 1872,
"end": 14863
} | class ____ {
private static final AtomicInteger counter = new AtomicInteger();
@Inject
TransactionSynchronizationRegistry tsr;
@Inject
TransactionManager transactionManager;
@Inject
ThreadContext threadContext;
@Inject
TransactionScopedTestBean testBean;
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class));
@Test
public void testBeginRequestScopeNotActive() {
Assertions.assertThrows(ContextNotActiveException.class, QuarkusTransaction::begin);
}
@Test
@ActivateRequestContext
public void testBeginCommit() {
QuarkusTransaction.begin();
var sync = register();
QuarkusTransaction.commit();
Assertions.assertEquals(Status.STATUS_COMMITTED, sync.completionStatus);
}
@Test
@ActivateRequestContext
public void testBeginRollback() {
QuarkusTransaction.begin();
var sync = register();
QuarkusTransaction.rollback();
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.completionStatus);
}
@Test
@ActivateRequestContext
public void testBeginSetRollbackOnly() {
QuarkusTransaction.begin();
var sync = register();
QuarkusTransaction.setRollbackOnly();
Assertions.assertThrows(QuarkusTransactionException.class, QuarkusTransaction::commit);
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.completionStatus);
}
@Test
@ActivateRequestContext
public void testBeginTimeout() throws InterruptedException {
QuarkusTransaction.begin(beginOptions().timeout(1));
var sync = register();
Thread.sleep(1200);
Assertions.assertThrows(QuarkusTransactionException.class, QuarkusTransaction::commit);
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.completionStatus);
}
@Test
@ActivateRequestContext
public void testBeginSuspendExistingFalse() {
QuarkusTransaction.begin();
var sync = register();
Assertions.assertThrows(QuarkusTransactionException.class, QuarkusTransaction::begin);
Assertions.assertTrue(QuarkusTransaction.isActive());
QuarkusTransaction.commit();
Assertions.assertEquals(Status.STATUS_COMMITTED, sync.completionStatus);
}
@Test
public void testBeginRollbackOnRequestScopeEnd() {
var context = Arc.container().requestContext();
context.activate();
TestSync sync = null;
try {
QuarkusTransaction.begin();
sync = register();
} finally {
context.terminate();
}
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.completionStatus);
}
@Test
public void testBeginCommitOnRequestScopeEnd() {
var context = Arc.container().requestContext();
context.activate();
TestSync sync = null;
try {
QuarkusTransaction.begin(beginOptions().commitOnRequestScopeEnd());
sync = register();
} finally {
context.terminate();
}
Assertions.assertEquals(Status.STATUS_COMMITTED, sync.completionStatus);
}
@Test
public void testCallCommit() {
Assertions.assertEquals(Status.STATUS_COMMITTED, QuarkusTransaction.call(this::register).completionStatus);
}
@Test
public void testCallRollback() {
AtomicReference<TestSync> sync = new AtomicReference<>();
Assertions.assertThrows(QuarkusTransactionException.class, () -> QuarkusTransaction.call(() -> {
sync.set(register());
QuarkusTransaction.rollback();
return null;
}));
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.get().completionStatus);
}
@Test
public void testCallRollbackOnly() {
AtomicReference<TestSync> sync = new AtomicReference<>();
Assertions.assertThrows(QuarkusTransactionException.class, () -> QuarkusTransaction.call(() -> {
sync.set(register());
QuarkusTransaction.setRollbackOnly();
return null;
}));
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.get().completionStatus);
}
@Test
public void testCallTimeout() {
AtomicReference<TestSync> sync = new AtomicReference<>();
Assertions.assertThrows(QuarkusTransactionException.class,
() -> QuarkusTransaction.call(runOptions().timeout(1), () -> {
sync.set(register());
Thread.sleep(1200);
return null;
}));
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.get().completionStatus);
}
@Test
public void testCallException() {
AtomicReference<TestSync> sync = new AtomicReference<>();
Assertions.assertThrows(IllegalArgumentException.class, () -> QuarkusTransaction.call(() -> {
sync.set(register());
throw new IllegalArgumentException("foo");
}));
Assertions.assertEquals(Status.STATUS_ROLLEDBACK, sync.get().completionStatus);
}
@Test
public void testCallExceptionHandler() {
AtomicReference<TestSync> sync = new AtomicReference<>();
Assertions.assertThrows(IllegalArgumentException.class,
() -> QuarkusTransaction.call(runOptions().exceptionHandler((e) -> RunOptions.ExceptionResult.COMMIT), () -> {
sync.set(register());
throw new IllegalArgumentException("foo");
}));
Assertions.assertEquals(Status.STATUS_COMMITTED, sync.get().completionStatus);
}
@Test
public void testCallSuspendExisting() {
QuarkusTransaction.call(runOptions().semantic(RunOptions.Semantic.SUSPEND_EXISTING), () -> {
Assertions.assertFalse(QuarkusTransaction.isActive());
return null;
});
}
@Test
@ActivateRequestContext
public void testCallDisallowExisting() {
RunOptions options = runOptions().semantic(RunOptions.Semantic.DISALLOW_EXISTING);
Assertions.assertEquals(Status.STATUS_COMMITTED, QuarkusTransaction.call(options, this::register).completionStatus);
QuarkusTransaction.begin();
Assertions.assertThrows(QuarkusTransactionException.class, () -> QuarkusTransaction.call(options, this::register));
}
@Test
@ActivateRequestContext
public void testCallRequiresNew() throws SystemException {
RunOptions options = runOptions().semantic(RunOptions.Semantic.REQUIRE_NEW);
QuarkusTransaction.begin();
var tx = transactionManager.getTransaction();
QuarkusTransaction.call(options, () -> {
Assertions.assertTrue(QuarkusTransaction.isActive());
if (tx == transactionManager.getTransaction()) {
throw new RuntimeException("Running in same transaction");
}
return null;
});
}
@Test
@ActivateRequestContext
public void testCallJoinExisting() throws SystemException {
RunOptions options = runOptions().semantic(RunOptions.Semantic.JOIN_EXISTING);
QuarkusTransaction.begin();
var tx = transactionManager.getTransaction();
QuarkusTransaction.call(options, () -> {
Assertions.assertTrue(QuarkusTransaction.isActive());
if (tx != transactionManager.getTransaction()) {
throw new RuntimeException("Running in different transaction");
}
return null;
});
}
@Test
public void testConcurrentTransactionScopedBeanCreation() {
counter.set(0);
// 1. A Transaction is activated in a parent thread.
QuarkusTransaction.run(() -> {
ExecutorService executor = Executors.newCachedThreadPool();
try {
// 2. The parent thread starts 2 child threads, and propagates the transaction.
// 3. The child threads access a @TransactionScoped bean concurrently,
// which has resource intensive producer simulated by sleep.
var f1 = executor.submit(threadContext.contextualRunnable(() -> testBean.doWork()));
var f2 = executor.submit(threadContext.contextualRunnable(() -> testBean.doWork()));
f1.get();
f2.get();
} catch (Throwable e) {
throw new AssertionError("Should not have thrown", e);
} finally {
executor.shutdownNow();
}
});
// 4. The race condition is handled correctly, the bean is only created once.
Assertions.assertEquals(1, counter.get());
}
@Test
public void testConcurrentTransactionScopedBeanCreationWithSynchronization() {
// test that propagating a transaction to other threads and use of Synchronizations do not interfere
counter.set(0);
// 1. A Transaction is activated in a parent thread.
QuarkusTransaction.run(() -> {
ExecutorService executor = Executors.newCachedThreadPool();
try {
Transaction txn = testBean.doWorkWithSynchronization(tsr, transactionManager);
// 2. The parent thread starts 2 child threads, and propagates the transaction.
// 3. The child threads access a @TransactionScoped bean concurrently,
Future<Transaction> f1 = executor
.submit(threadContext
.contextualCallable(() -> testBean.doWorkWithSynchronization(tsr, transactionManager)));
Future<Transaction> f2 = executor
.submit(threadContext
.contextualCallable(() -> testBean.doWorkWithSynchronization(tsr, transactionManager)));
Transaction t1 = f1.get();
Transaction t2 = f2.get();
// the Synchronization callbacks for the parent thread and the two child threads should
// all have run with the same transaction context
Assertions.assertEquals(t1, txn);
Assertions.assertEquals(t2, txn);
} catch (Throwable e) {
throw new AssertionError("Should not have thrown", e);
} finally {
executor.shutdownNow();
}
});
}
@Test
public void testConcurrentWithSynchronization() {
// test that Synchronizations registered with concurrent transactions do not interfere
Collection<Callable<Void>> callables = new ArrayList<>();
IntStream.rangeClosed(1, 8)
.forEach(i -> callables.add(() -> {
try {
// start a txn
// then register an interposed Synchronization
// then commit the txn
// and then verify the Synchronization ran with the same transaction
TestInterposedSync t = new TestInterposedSync(tsr, transactionManager);
transactionManager.begin();
Transaction txn = transactionManager.getTransaction();
tsr.registerInterposedSynchronization(t);
transactionManager.commit();
// check that the transaction seen by the Synchronization is same as the one we just started
Assertions.assertEquals(txn, t.getContext(), "Synchronization ran with the wrong context");
} catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
| HeuristicRollbackException | SecurityException | IllegalStateException e) {
throw new RuntimeException(e);
}
return null;
}));
ExecutorService executor = Executors.newCachedThreadPool();
try {
List<Future<Void>> futures = executor.invokeAll(callables);
futures.forEach(f -> {
try {
// verify that the task did not throw an exception
f.get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError("Should not have thrown", e);
}
});
} catch (InterruptedException e) {
throw new AssertionError("Should not have thrown", e);
} finally {
executor.shutdownNow();
}
}
TestSync register() {
TestSync t = new TestSync();
try {
transactionManager.getTransaction().registerSynchronization(t);
} catch (RollbackException | SystemException e) {
throw new RuntimeException(e);
}
return t;
}
static | QuarkusTransactionTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/executor/TaskFinishedListener.java | {
"start": 763,
"end": 948
} | interface ____ extends TaskListener {
/**
* Invoked when task finished
*
* @param taskId - id of task
*/
void onFinished(String taskId);
}
| TaskFinishedListener |
java | apache__avro | lang/java/avro/src/test/java/org/apache/avro/message/TestGenerateInteropSingleObjectEncoding.java | {
"start": 1404,
"end": 2607
} | class ____ {
private static final String RESOURCES_FOLDER = System.getProperty("share.dir", "target/test-classes/share")
+ "/test/data/messageV1";
private static final File SCHEMA_FILE = new File(RESOURCES_FOLDER + "/test_schema.avsc");
private static final File MESSAGE_FILE = new File(RESOURCES_FOLDER + "/test_message.bin");
private static Schema SCHEMA;
private static GenericRecordBuilder BUILDER;
@BeforeAll
public static void setup() throws IOException {
try (FileInputStream fileInputStream = new FileInputStream(SCHEMA_FILE)) {
SCHEMA = new Schema.Parser().parse(fileInputStream);
BUILDER = new GenericRecordBuilder(SCHEMA);
}
}
@Test
void generateData() throws IOException {
MessageEncoder<GenericData.Record> encoder = new BinaryMessageEncoder<>(GenericData.get(), SCHEMA);
BUILDER.set("id", 42L).set("name", "Bill").set("tags", Arrays.asList("dog_lover", "cat_hater")).build();
ByteBuffer buffer = encoder.encode(
BUILDER.set("id", 42L).set("name", "Bill").set("tags", Arrays.asList("dog_lover", "cat_hater")).build());
new FileOutputStream(MESSAGE_FILE).write(buffer.array());
}
}
| TestGenerateInteropSingleObjectEncoding |
java | apache__flink | flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoadersTest.java | {
"start": 4611,
"end": 5888
} | class ____ with RocksDB related code: the state backend and
// RocksDB itself
final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();
final URLClassLoader childClassLoader =
createChildFirstClassLoader(childCodePath, parentClassLoader);
final String className = FlinkUserCodeClassLoadersTest.class.getName();
final Class<?> clazz1 = Class.forName(className, false, parentClassLoader);
final Class<?> clazz2 = Class.forName(className, false, childClassLoader);
final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
final Class<?> clazz4 = Class.forName(className, false, childClassLoader);
assertThat(clazz2).isNotEqualTo(clazz1);
assertThat(clazz3).isEqualTo(clazz2);
assertThat(clazz4).isEqualTo(clazz2);
childClassLoader.close();
}
@Test
void testRepeatedParentFirstPatternClass() throws Exception {
final String className = FlinkUserCodeClassLoadersTest.class.getName();
final String parentFirstPattern = className.substring(0, className.lastIndexOf('.'));
final ClassLoader parentClassLoader = getClass().getClassLoader();
// collect the libraries / | folders |
java | apache__camel | tooling/camel-tooling-model/src/main/java/org/apache/camel/tooling/model/ComponentModel.java | {
"start": 994,
"end": 5484
} | class ____ extends ArtifactModel<ComponentModel.ComponentOptionModel> {
protected String scheme;
protected String extendsScheme;
protected String alternativeSchemes;
protected String syntax;
protected String alternativeSyntax;
protected boolean async;
protected boolean api;
protected String apiSyntax;
protected boolean consumerOnly;
protected boolean producerOnly;
protected boolean lenientProperties;
protected boolean browsable;
protected boolean remote;
protected String verifiers;
protected final List<EndpointOptionModel> endpointOptions = new ArrayList<>();
protected final List<EndpointHeaderModel> headers = new ArrayList<>();
// lets sort apis A..Z so they are always in the same order
protected final Collection<ApiModel> apiOptions = new TreeSet<>(Comparators.apiModelComparator());
public ComponentModel() {
}
@Override
public Kind getKind() {
return Kind.component;
}
public String getScheme() {
return scheme;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
public String getExtendsScheme() {
return extendsScheme;
}
public void setExtendsScheme(String extendsScheme) {
this.extendsScheme = extendsScheme;
}
public String getAlternativeSchemes() {
return alternativeSchemes;
}
public void setAlternativeSchemes(String alternativeSchemes) {
this.alternativeSchemes = alternativeSchemes;
}
public String getSyntax() {
return syntax;
}
public void setSyntax(String syntax) {
this.syntax = syntax;
}
public String getAlternativeSyntax() {
return alternativeSyntax;
}
public void setAlternativeSyntax(String alternativeSyntax) {
this.alternativeSyntax = alternativeSyntax;
}
public boolean isAsync() {
return async;
}
public void setAsync(boolean async) {
this.async = async;
}
public boolean isApi() {
return api;
}
public void setApi(boolean api) {
this.api = api;
}
public String getApiSyntax() {
return apiSyntax;
}
public void setApiSyntax(String apiSyntax) {
this.apiSyntax = apiSyntax;
}
public boolean isConsumerOnly() {
return consumerOnly;
}
public void setConsumerOnly(boolean consumerOnly) {
this.consumerOnly = consumerOnly;
}
public boolean isProducerOnly() {
return producerOnly;
}
public void setProducerOnly(boolean producerOnly) {
this.producerOnly = producerOnly;
}
public boolean isLenientProperties() {
return lenientProperties;
}
public void setLenientProperties(boolean lenientProperties) {
this.lenientProperties = lenientProperties;
}
public boolean isBrowsable() {
return browsable;
}
public void setBrowsable(boolean browsable) {
this.browsable = browsable;
}
public boolean isRemote() {
return remote;
}
public void setRemote(boolean remote) {
this.remote = remote;
}
public String getVerifiers() {
return verifiers;
}
public void setVerifiers(String verifiers) {
this.verifiers = verifiers;
}
public List<ComponentOptionModel> getComponentOptions() {
return super.getOptions();
}
public void addComponentOption(ComponentOptionModel option) {
super.addOption(option);
}
public List<EndpointOptionModel> getEndpointOptions() {
return endpointOptions;
}
public void addEndpointOption(EndpointOptionModel option) {
endpointOptions.add(option);
}
public List<EndpointHeaderModel> getEndpointHeaders() {
return headers;
}
public void addEndpointHeader(EndpointHeaderModel header) {
headers.add(header);
}
public List<EndpointOptionModel> getEndpointParameterOptions() {
return endpointOptions.stream()
.filter(o -> "parameter".equals(o.getKind()))
.collect(Collectors.toList());
}
public List<EndpointOptionModel> getEndpointPathOptions() {
return endpointOptions.stream()
.filter(o -> "path".equals(o.getKind()))
.collect(Collectors.toList());
}
public Collection<ApiModel> getApiOptions() {
return apiOptions;
}
public static | ComponentModel |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ExecEndpointBuilderFactory.java | {
"start": 1444,
"end": 1563
} | interface ____ {
/**
* Builder for endpoint for the Exec component.
*/
public | ExecEndpointBuilderFactory |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/util/TestSocketUtils.java | {
"start": 3027,
"end": 4786
} | class ____ to SpEL's {@code T()} function for each usage.
* Thus, the fact that this constructor is {@code public} allows you to reduce
* boilerplate configuration with SpEL as can be seen in the following example.
* <pre><code>
* <bean id="socketUtils" class="org.springframework.test.util.TestSocketUtils" />
* <bean id="myBean" ... p:port="#{socketUtils.findAvailableTcpPort()}" /></code>
* </pre>
*/
public TestSocketUtils() {
}
/**
* Find an available TCP port randomly selected from the range [1024, 65535].
* @return an available TCP port number
* @throws IllegalStateException if no available port could be found
*/
public static int findAvailableTcpPort() {
return INSTANCE.findAvailableTcpPortInternal();
}
/**
* Internal implementation of {@link #findAvailableTcpPort()}.
* <p>Package-private solely for testing purposes.
*/
int findAvailableTcpPortInternal() {
int candidatePort;
int searchCounter = 0;
do {
Assert.state(++searchCounter <= MAX_ATTEMPTS, () -> String.format(
"Could not find an available TCP port in the range [%d, %d] after %d attempts",
PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS));
candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE_PLUS_ONE);
}
while (!isPortAvailable(candidatePort));
return candidatePort;
}
/**
* Determine if the specified TCP port is currently available on {@code localhost}.
* <p>Package-private solely for testing purposes.
*/
boolean isPortAvailable(int port) {
try {
ServerSocket serverSocket = ServerSocketFactory.getDefault()
.createServerSocket(port, 1, InetAddress.getByName("localhost"));
serverSocket.close();
return true;
}
catch (Exception ex) {
return false;
}
}
}
| name |
java | netty__netty | codec-compression/src/main/java/io/netty/handler/codec/compression/CompressionUtil.java | {
"start": 749,
"end": 1749
} | class ____ {
private CompressionUtil() { }
static void checkChecksum(ByteBufChecksum checksum, ByteBuf uncompressed, int currentChecksum) {
checksum.reset();
checksum.update(uncompressed,
uncompressed.readerIndex(), uncompressed.readableBytes());
final int checksumResult = (int) checksum.getValue();
if (checksumResult != currentChecksum) {
throw new DecompressionException(String.format(
"stream corrupted: mismatching checksum: %d (expected: %d)",
checksumResult, currentChecksum));
}
}
static ByteBuffer safeReadableNioBuffer(ByteBuf buffer) {
return safeNioBuffer(buffer, buffer.readerIndex(), buffer.readableBytes());
}
static ByteBuffer safeNioBuffer(ByteBuf buffer, int index, int length) {
return buffer.nioBufferCount() == 1 ? buffer.internalNioBuffer(index, length)
: buffer.nioBuffer(index, length);
}
}
| CompressionUtil |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/adapter/AwsV1BindingSupport.java | {
"start": 1473,
"end": 2744
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(
AwsV1BindingSupport.class);
/**
* V1 credential provider classname: {@code}.
*/
public static final String CREDENTIAL_PROVIDER_CLASSNAME =
"com.amazonaws.auth.AWSCredentialsProvider";
/**
* SDK availability.
*/
private static final boolean SDK_V1_FOUND = checkForAwsV1Sdk();
private AwsV1BindingSupport() {
}
/**
* Probe for the AWS v1 SDK being available by looking for
* the class {@link #CREDENTIAL_PROVIDER_CLASSNAME}.
* @return true if it was found in the classloader
*/
private static boolean checkForAwsV1Sdk() {
try {
ClassLoader cl = AwsV1BindingSupport.class.getClassLoader();
cl.loadClass(CREDENTIAL_PROVIDER_CLASSNAME);
LOG.debug("v1 SDK class {} found", CREDENTIAL_PROVIDER_CLASSNAME);
return true;
} catch (Exception e) {
LOG.debug("v1 SDK class {} not found", CREDENTIAL_PROVIDER_CLASSNAME, e);
return false;
}
}
/**
* Is the AWS v1 SDK available?
* @return true if it was found in the classloader
*/
public static synchronized boolean isAwsV1SdkAvailable() {
return SDK_V1_FOUND;
}
/**
* Create an AWS credential provider from its | AwsV1BindingSupport |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/refcolnames/misc/Misc0Test.java | {
"start": 1360,
"end": 1700
} | class ____ implements Serializable {
@Id long entityBKey;
@OneToOne
@JoinColumnOrFormula(column = @JoinColumn(name = "entityBKey", referencedColumnName = "entityBKey", insertable = false, updatable = false))
@JoinColumnOrFormula(formula = @JoinFormula(value = "1", referencedColumnName = "flag"))
public EntityA entityA;
}
}
| EntityB |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/builder/impl/DefaultAppenderComponentBuilder.java | {
"start": 1252,
"end": 1897
} | class ____ extends DefaultComponentAndConfigurationBuilder<AppenderComponentBuilder>
implements AppenderComponentBuilder {
public DefaultAppenderComponentBuilder(
final DefaultConfigurationBuilder<? extends Configuration> builder, final String name, final String type) {
super(builder, name, type);
}
@Override
public AppenderComponentBuilder add(final LayoutComponentBuilder builder) {
return addComponent(builder);
}
@Override
public AppenderComponentBuilder add(final FilterComponentBuilder builder) {
return addComponent(builder);
}
}
| DefaultAppenderComponentBuilder |
java | square__retrofit | retrofit/src/main/java/retrofit2/Utils.java | {
"start": 11832,
"end": 14657
} | class ____ {@code typeVariable}, or {@code null} if it was not declared by
* a class.
*/
private static @Nullable Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null;
}
static void checkNotPrimitive(Type type) {
if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
throw new IllegalArgumentException();
}
}
/** Returns true if {@code annotations} contains an instance of {@code cls}. */
static boolean isAnnotationPresent(Annotation[] annotations, Class<? extends Annotation> cls) {
for (Annotation annotation : annotations) {
if (cls.isInstance(annotation)) {
return true;
}
}
return false;
}
static ResponseBody buffer(final ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer);
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
static Type getParameterUpperBound(int index, ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (index < 0 || index >= types.length) {
throw new IllegalArgumentException(
"Index " + index + " not in range [0," + types.length + ") for " + type);
}
Type paramType = types[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
static Type getParameterLowerBound(int index, ParameterizedType type) {
Type paramType = type.getActualTypeArguments()[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getLowerBounds()[0];
}
return paramType;
}
static boolean hasUnresolvableType(@Nullable Type type) {
if (type instanceof Class<?>) {
return false;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
if (hasUnresolvableType(typeArgument)) {
return true;
}
}
return false;
}
if (type instanceof GenericArrayType) {
return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
}
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof WildcardType) {
return true;
}
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException(
"Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <"
+ type
+ "> is of type "
+ className);
}
static final | of |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/repositories/IndexIdTests.java | {
"start": 1046,
"end": 2904
} | class ____ extends AbstractWireSerializingTestCase<IndexId> {
@Override
protected Writeable.Reader<IndexId> instanceReader() {
return IndexId::new;
}
@Override
protected IndexId createTestInstance() {
return new IndexId(randomIdentifier(), UUIDs.randomBase64UUID());
}
@Override
protected IndexId mutateInstance(IndexId instance) {
return switch (randomInt(1)) {
case 0 -> new IndexId(randomValueOtherThan(instance.getName(), ESTestCase::randomIdentifier), instance.getId());
case 1 -> new IndexId(instance.getName(), randomValueOtherThan(instance.getId(), UUIDs::randomBase64UUID));
default -> throw new RuntimeException("unreachable");
};
}
public void testXContent() throws IOException {
IndexId indexId = new IndexId(randomAlphaOfLength(8), UUIDs.randomBase64UUID());
XContentBuilder builder = JsonXContent.contentBuilder();
indexId.toXContent(builder, ToXContent.EMPTY_PARAMS);
String name;
String id;
try (XContentParser parser = createParser(JsonXContent.jsonXContent, BytesReference.bytes(builder))) {
assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
name = null;
id = null;
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
final String currentFieldName = parser.currentName();
parser.nextToken();
if (currentFieldName.equals(IndexId.NAME)) {
name = parser.text();
} else if (currentFieldName.equals(IndexId.ID)) {
id = parser.text();
}
}
}
assertNotNull(name);
assertNotNull(id);
assertEquals(indexId, new IndexId(name, id));
}
}
| IndexIdTests |
java | quarkusio__quarkus | integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/CustomBasicHttpAuthMechanism.java | {
"start": 592,
"end": 999
} | class ____ extends BasicAuthenticationMechanism {
public CustomBasicHttpAuthMechanism() {
super(null, false);
}
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
if (context.request().getHeader("custom") != null) {
return super.getChallenge(context);
}
return Uni.createFrom().nullItem();
}
}
| CustomBasicHttpAuthMechanism |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/NullableSerializerUpgradeTest.java | {
"start": 2812,
"end": 3210
} | class ____
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Long> {
@Override
public TypeSerializer<Long> createPriorSerializer() {
return NullableSerializer.wrap(LongSerializer.INSTANCE, true);
}
@Override
public Long createTestData() {
return null;
}
}
/**
* This | NullablePaddedSerializerSetup |
java | apache__logging-log4j2 | log4j-jpa/src/main/java/org/apache/logging/log4j/core/appender/db/jpa/converter/MessageAttributeConverter.java | {
"start": 1327,
"end": 1894
} | class ____ implements AttributeConverter<Message, String> {
private static final StatusLogger LOGGER = StatusLogger.getLogger();
@Override
public String convertToDatabaseColumn(final Message message) {
if (message == null) {
return null;
}
return message.getFormattedMessage();
}
@Override
public Message convertToEntityAttribute(final String s) {
if (Strings.isEmpty(s)) {
return null;
}
return LOGGER.getMessageFactory().newMessage(s);
}
}
| MessageAttributeConverter |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java | {
"start": 26962,
"end": 27712
} | class ____ {
public int bar() {
return 42;
}
public static void foo() {
// BUG: Diagnostic contains: CheckReturnValue
new Test().bar();
}
}
""")
.doTest();
}
// In the following test methods, we define parallel skeletons of classes like java.util.List,
// because the real java.util.List may have had @CanIgnoreReturnValue annotations inserted.
@Test
public void allMethods_withExternallyConfiguredIgnoreList() {
compileWithExternalApis("my.java.util.List#add(java.lang.Object)")
.addSourceLines(
"Test.java",
"""
import my.java.util.List;
| Test |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/util/HashMapSupplier.java | {
"start": 727,
"end": 1048
} | enum ____ implements Supplier<Map<Object, Object>> {
INSTANCE;
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <K, V> Supplier<Map<K, V>> asSupplier() {
return (Supplier)INSTANCE;
}
@Override public Map<Object, Object> get() {
return new HashMap<>();
}
}
| HashMapSupplier |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/EndpointSchemaGeneratorMojo.java | {
"start": 4543,
"end": 13038
} | class ____ extends AbstractGeneratorMojo {
public static final DotName URI_ENDPOINT = DotName.createSimple(UriEndpoint.class.getName());
public static final DotName COMPONENT = DotName.createSimple(Component.class.getName());
public static final DotName API_PARAMS = DotName.createSimple(ApiParams.class.getName());
private static final String HEADER_FILTER_STRATEGY_JAVADOC
= "To use a custom HeaderFilterStrategy to filter header to and from Camel message.";
@Parameter(defaultValue = "${project.build.outputDirectory}")
protected File classesDirectory;
@Parameter(defaultValue = "${project.basedir}/src/generated/java")
protected File sourcesOutputDir;
@Parameter(defaultValue = "${project.basedir}/src/generated/resources")
protected File resourcesOutputDir;
protected IndexView indexView;
protected Map<String, String> resources = new HashMap<>();
protected List<Path> sourceRoots;
protected Map<String, String> sources = new HashMap<>();
protected Map<String, JavaSource<?>> parsed = new HashMap<>();
@Inject
public EndpointSchemaGeneratorMojo(MavenProjectHelper projectHelper, BuildContext buildContext) {
super(projectHelper, buildContext);
}
// for testing purposes
EndpointSchemaGeneratorMojo() {
this(null, null);
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (classesDirectory == null) {
classesDirectory = new File(project.getBuild().getOutputDirectory());
}
if (sourcesOutputDir == null) {
sourcesOutputDir = new File(project.getBasedir(), "src/generated/java");
}
if (resourcesOutputDir == null) {
resourcesOutputDir = new File(project.getBasedir(), "src/generated/resources");
}
if (!classesDirectory.isDirectory()) {
return;
}
executeUriEndpoint();
}
private void executeUriEndpoint() {
List<Class<?>> classes = new ArrayList<>();
for (AnnotationInstance ai : getIndex().getAnnotations(URI_ENDPOINT)) {
Class<?> classElement = loadClass(ai.target().asClass().name().toString());
final UriEndpoint uriEndpoint = classElement.getAnnotation(UriEndpoint.class);
if (uriEndpoint != null) {
String scheme = uriEndpoint.scheme();
if (!Strings.isNullOrEmpty(scheme)) {
classes.add(classElement);
}
}
}
// make sure we sort the classes in case one inherit from the other
classes.sort(this::compareClasses);
Map<Class<?>, ComponentModel> models = new HashMap<>();
for (Class<?> classElement : classes) {
UriEndpoint uriEndpoint = classElement.getAnnotation(UriEndpoint.class);
String scheme = uriEndpoint.scheme();
String extendsScheme = uriEndpoint.extendsScheme();
String title = uriEndpoint.title();
Category[] categories = uriEndpoint.category();
String label = null;
if (categories.length > 0) {
label = Arrays.stream(categories)
.map(Category::getValue)
.collect(Collectors.joining(","));
}
validateSchemaName(scheme, classElement);
// support multiple schemes separated by comma, which maps to
// the exact same component
// for example camel-mail has a bunch of component schema names
// that does that
String[] schemes = scheme.split(",");
String[] titles = title.split(",");
String[] extendsSchemes = extendsScheme.split(",");
processSchemas(models, classElement, uriEndpoint, label, schemes, titles, extendsSchemes);
}
}
private void processSchemas(
Map<Class<?>, ComponentModel> models, Class<?> classElement, UriEndpoint uriEndpoint, String label,
String[] schemes,
String[] titles, String[] extendsSchemes) {
for (int i = 0; i < schemes.length; i++) {
final String alias = schemes[i];
final String extendsAlias = i < extendsSchemes.length ? extendsSchemes[i] : extendsSchemes[0];
String aTitle = i < titles.length ? titles[i] : titles[0];
// some components offer a secure alternative which we need
// to amend the title accordingly
if (secureAlias(schemes[0], alias)) {
aTitle += " (Secure)";
}
final String aliasTitle = aTitle;
ComponentModel parentData = collectParentData(models, classElement);
ComponentModel model = writeJSonSchemeAndPropertyConfigurer(classElement, uriEndpoint, aliasTitle, alias,
extendsAlias, label, schemes, parentData);
models.put(classElement, model);
}
}
private ComponentModel collectParentData(Map<Class<?>, ComponentModel> models, Class<?> classElement) {
ComponentModel parentData = null;
final Class<?> superclass = classElement.getSuperclass();
if (superclass != null) {
parentData = models.get(superclass);
if (parentData == null) {
UriEndpoint parentUriEndpoint = superclass.getAnnotation(UriEndpoint.class);
if (parentUriEndpoint != null) {
String parentScheme = parentUriEndpoint.scheme().split(",")[0];
String superClassName = superclass.getName();
String packageName = superClassName.substring(0, superClassName.lastIndexOf('.'));
String fileName
= "META-INF/" + packageName.replace('.', '/') + "/" + parentScheme + PackageHelper.JSON_SUFIX;
String json = loadResource(fileName);
parentData = JsonMapper.generateComponentModel(json);
}
}
}
return parentData;
}
private int compareClasses(Class<?> c1, Class<?> c2) {
if (c1.isAssignableFrom(c2)) {
return -1;
} else if (c2.isAssignableFrom(c1)) {
return +1;
} else {
return c1.getName().compareTo(c2.getName());
}
}
private void validateSchemaName(final String schemaName, final Class<?> classElement) {
// our schema name has to be in lowercase
if (!schemaName.equals(schemaName.toLowerCase())) {
getLog().warn(String.format(
"Mixed case schema name in '%s' with value '%s' has been deprecated. Please use lowercase only!",
classElement.getName(), schemaName));
}
}
protected ComponentModel writeJSonSchemeAndPropertyConfigurer(
Class<?> classElement, UriEndpoint uriEndpoint, String title,
String scheme, String extendsScheme, String label,
String[] schemes, ComponentModel parentData) {
// gather component information
ComponentModel componentModel
= findComponentProperties(uriEndpoint, classElement, title, scheme, extendsScheme, label, schemes);
// get endpoint information which is divided into paths and options
// (though there should really only be one path)
// component options
Class<?> componentClassElement = loadClass(componentModel.getJavaType());
String excludedComponentProperties = "";
if (componentClassElement != null) {
findComponentClassProperties(componentModel, componentClassElement, "", null, null);
Metadata componentMetadata = componentClassElement.getAnnotation(Metadata.class);
if (componentMetadata != null) {
excludedComponentProperties = componentMetadata.excludeProperties();
}
}
// component headers
addEndpointHeaders(componentModel, uriEndpoint, scheme);
// endpoint options
findClassProperties(componentModel, classElement, new HashSet<>(), "", null, null, false);
String excludedEndpointProperties = getExcludedEnd(classElement.getAnnotation(Metadata.class));
// enhance and generate
enhanceComponentModel(componentModel, parentData, excludedEndpointProperties, excludedComponentProperties);
// if the component has known | EndpointSchemaGeneratorMojo |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java | {
"start": 5424,
"end": 5496
} | enum ____ {
VALUE1,
VALUE2
}
public static | TestEnum |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/restriction/Restriction.java | {
"start": 3804,
"end": 14138
} | class ____ the given {@linkplain Range range}.
* <p>
* This operation is not compile-time type safe. Prefer the use of
* {@link #restrict(SingularAttribute, Range)}.
*/
static <T> Restriction<T> restrict(Class<T> type, String attributeName, Range<?> range) {
return new NamedAttributeRange<>( type, attributeName, range );
}
/**
* Restrict the given attribute to be exactly equal to the given value.
*
* @see Range#singleValue(Object)
*/
static <T, U> Restriction<T> equal(SingularAttribute<T, U> attribute, U value) {
return restrict( attribute, Range.singleValue( value ) );
}
/**
* Restrict the given attribute to be not equal to the given value.
*/
static <T, U> Restriction<T> unequal(SingularAttribute<T, U> attribute, U value) {
return equal( attribute, value ).negated();
}
/**
* Restrict the given attribute to be equal to the given string, ignoring case.
*
* @see Range#singleCaseInsensitiveValue(String)
*/
static <T> Restriction<T> equalIgnoringCase(SingularAttribute<T, String> attribute, String value) {
return restrict( attribute, Range.singleCaseInsensitiveValue( value ) );
}
/**
* Restrict the given attribute to be exactly equal to one of the given values.
*
* @see Range#valueList(List)
*/
@SafeVarargs
static <T, U> Restriction<T> in(SingularAttribute<T, U> attribute, U... values) {
return in( attribute, List.of(values ) );
}
/**
* Restrict the given attribute to be not equal to any of the given values.
*/
@SafeVarargs
static <T, U> Restriction<T> notIn(SingularAttribute<T, U> attribute, U... values) {
return notIn( attribute, List.of(values ) );
}
/**
* Restrict the given attribute to be exactly equal to one of the given values.
*
* @see Range#valueList(List)
*/
static <T, U> Restriction<T> in(SingularAttribute<T, U> attribute, java.util.List<U> values) {
return restrict( attribute, Range.valueList( values ) );
}
/**
* Restrict the given attribute to be not equal to any of the given values.
*/
static <T, U> Restriction<T> notIn(SingularAttribute<T, U> attribute, java.util.List<U> values) {
return in( attribute, values ).negated();
}
/**
* Restrict the given attribute to fall between the given values.
*
* @see Range#closed(Comparable, Comparable)
*/
static <T, U extends Comparable<U>> Restriction<T> between(SingularAttribute<T, U> attribute, U lowerBound, U upperBound) {
return restrict( attribute, Range.closed( lowerBound, upperBound ) );
}
/**
* Restrict the given attribute to not fall between the given values.
*/
static <T, U extends Comparable<U>> Restriction<T> notBetween(SingularAttribute<T, U> attribute, U lowerBound, U upperBound) {
return between( attribute, lowerBound, upperBound ).negated();
}
/**
* Restrict the given attribute to be strictly greater than the given lower bound.
*
* @see Range#greaterThan(Comparable)
*/
static <T, U extends Comparable<U>> Restriction<T> greaterThan(SingularAttribute<T, U> attribute, U lowerBound) {
return restrict( attribute, Range.greaterThan( lowerBound ) );
}
/**
* Restrict the given attribute to be strictly less than the given upper bound.
*
* @see Range#lessThan(Comparable)
*/
static <T, U extends Comparable<U>> Restriction<T> lessThan(SingularAttribute<T, U> attribute, U upperBound) {
return restrict( attribute, Range.lessThan( upperBound ) );
}
/**
* Restrict the given attribute to be greater than or equal to the given lower bound.
*
* @see Range#greaterThanOrEqualTo(Comparable)
*/
static <T, U extends Comparable<U>> Restriction<T> greaterThanOrEqual(SingularAttribute<T, U> attribute, U lowerBound) {
return restrict( attribute, Range.greaterThanOrEqualTo( lowerBound ) );
}
/**
* Restrict the given attribute to be less than or equal to the given upper bound.
*
* @see Range#lessThanOrEqualTo(Comparable)
*/
static <T, U extends Comparable<U>> Restriction<T> lessThanOrEqual(SingularAttribute<T, U> attribute, U upperBound) {
return restrict( attribute, Range.lessThanOrEqualTo( upperBound ) );
}
/**
* Restrict the given attribute to match the given pattern, explicitly specifying
* case sensitivity, along with single-character and multi-character wildcards.
*
* @param pattern A pattern involving the given wildcard characters
* @param caseSensitive {@code true} if matching is case-sensitive
* @param charWildcard A wildcard character which matches any single character
* @param stringWildcard A wildcard character which matches any string of characters
*
* @see Range#pattern(String, boolean, char, char)
*/
static <T> Restriction<T> like(
SingularAttribute<T, String> attribute,
String pattern, boolean caseSensitive,
char charWildcard, char stringWildcard) {
return restrict( attribute, Range.pattern( pattern, caseSensitive, charWildcard, stringWildcard ) );
}
/**
* Restrict the given attribute to match the given pattern, explicitly specifying
* case sensitivity. The pattern must be expressed in terms of the default wildcard
* characters {@code _} and {@code %}.
*
* @param pattern A pattern involving the default wildcard characters
* @param caseSensitive {@code true} if matching is case-sensitive
*
* @see Range#pattern(String, boolean)
*/
static <T> Restriction<T> like(SingularAttribute<T, String> attribute, String pattern, boolean caseSensitive) {
return restrict( attribute, Range.pattern( pattern, caseSensitive ) );
}
/**
* Restrict the given attribute to match the given pattern. The pattern must be
* expressed in terms of the default wildcard characters {@code _} and {@code %}.
*
* @see Range#pattern(String)
*/
static <T> Restriction<T> like(SingularAttribute<T, String> attribute, String pattern) {
return like( attribute, pattern, true );
}
/**
* Restrict the given attribute to not match the given pattern. The pattern must
* be expressed in terms of the default wildcard characters {@code _} and {@code %}.
*
* @see Range#pattern(String)
*/
static <T> Restriction<T> notLike(SingularAttribute<T, String> attribute, String pattern) {
return like( attribute, pattern, true ).negated();
}
/**
* Restrict the given attribute to not match the given pattern, explicitly specifying
* case sensitivity. The pattern must be expressed in terms of the default wildcard
* characters {@code _} and {@code %}.
*
* @param pattern A pattern involving the default wildcard characters
* @param caseSensitive {@code true} if matching is case-sensitive
*/
static <T> Restriction<T> notLike(SingularAttribute<T, String> attribute, String pattern, boolean caseSensitive) {
return like( attribute, pattern, caseSensitive ).negated();
}
/**
* Restrict the given attribute to start with the given string prefix.
*
* @see Range#prefix(String)
*/
static <T> Restriction<T> startsWith(SingularAttribute<T, String> attribute, String prefix) {
return startsWith( attribute, prefix, true );
}
/**
* Restrict the given attribute to end with the given string suffix.
*
* @see Range#suffix(String)
*/
static <T> Restriction<T> endsWith(SingularAttribute<T, String> attribute, String suffix) {
return endsWith( attribute, suffix, true );
}
/**
* Restrict the given attribute to contain the given substring.
*
* @see Range#containing(String)
*/
static <T> Restriction<T> contains(SingularAttribute<T, String> attribute, String substring) {
return contains( attribute, substring, true );
}
/**
* Restrict the given attribute to not contain the given substring.
*/
static <T> Restriction<T> notContains(SingularAttribute<T, String> attribute, String substring) {
return notContains( attribute, substring, true );
}
/**
* Restrict the given attribute to start with the given string prefix, explicitly
* specifying case sensitivity.
*
* @see Range#prefix(String, boolean)
*/
static <T> Restriction<T> startsWith(SingularAttribute<T, String> attribute, String prefix, boolean caseSensitive) {
return restrict( attribute, Range.prefix( prefix, caseSensitive ) );
}
/**
* Restrict the given attribute to end with the given string suffix, explicitly
* specifying case sensitivity.
*
* @see Range#suffix(String, boolean)
*/
static <T> Restriction<T> endsWith(SingularAttribute<T, String> attribute, String suffix, boolean caseSensitive) {
return restrict( attribute, Range.suffix( suffix, caseSensitive ) );
}
/**
* Restrict the given attribute to contain the given substring, explicitly
* specifying case sensitivity.
*
* @see Range#containing(String, boolean)
*/
static <T> Restriction<T> contains(SingularAttribute<T, String> attribute, String substring, boolean caseSensitive) {
return restrict( attribute, Range.containing( substring, caseSensitive ) );
}
/**
* Restrict the given attribute to not contain the given substring, explicitly
* specifying case sensitivity.
*/
static <T> Restriction<T> notContains(SingularAttribute<T, String> attribute, String substring, boolean caseSensitive) {
return contains( attribute, substring, caseSensitive ).negated();
}
/**
* Restrict the given attribute to be non-null.
*/
static <T, U> Restriction<T> notNull(SingularAttribute<T, U> attribute) {
return restrict( attribute, Range.notNull( attribute.getJavaType() ) );
}
/**
* Combine the given restrictions using logical and.
*/
static <T> Restriction<T> all(List<? extends Restriction<? super T>> restrictions) {
return new Conjunction<>( restrictions );
}
/**
* Combine the given restrictions using logical or.
*/
static <T> Restriction<T> any(List<? extends Restriction<? super T>> restrictions) {
return new Disjunction<>( restrictions );
}
/**
* Combine the given restrictions using logical and.
*/
@SafeVarargs
static <T> Restriction<T> all(Restriction<? super T>... restrictions) {
return new Conjunction<T>( java.util.List.of( restrictions ) );
}
/**
* Combine the given restrictions using logical or.
*/
@SafeVarargs
static <T> Restriction<T> any(Restriction<? super T>... restrictions) {
return new Disjunction<T>( java.util.List.of( restrictions ) );
}
/**
* An empty restriction.
*/
static <T> Restriction<T> unrestricted() {
return new Unrestricted<>();
}
}
| to |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StXMinFromWKBEvaluator.java | {
"start": 4697,
"end": 5281
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory wkb;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory wkb) {
this.source = source;
this.wkb = wkb;
}
@Override
public StXMinFromWKBEvaluator get(DriverContext context) {
return new StXMinFromWKBEvaluator(source, wkb.get(context), context);
}
@Override
public String toString() {
return "StXMinFromWKBEvaluator[" + "wkb=" + wkb + "]";
}
}
}
| Factory |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/datastreams/PutDataStreamOptionsAction.java | {
"start": 1968,
"end": 6295
} | interface ____ {
Request create(@Nullable DataStreamFailureStore dataStreamFailureStore);
}
public static final ConstructingObjectParser<Request, Factory> PARSER = new ConstructingObjectParser<>(
"put_data_stream_options_request",
false,
(args, factory) -> factory.create((DataStreamFailureStore) args[0])
);
static {
PARSER.declareObjectOrNull(
ConstructingObjectParser.optionalConstructorArg(),
(p, c) -> DataStreamFailureStore.PARSER.parse(p, null),
null,
new ParseField("failure_store")
);
}
public static Request parseRequest(XContentParser parser, Factory factory) {
return PARSER.apply(parser, factory);
}
private String[] names;
private IndicesOptions indicesOptions = IndicesOptions.builder()
.concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ERROR_WHEN_UNAVAILABLE_TARGETS)
.wildcardOptions(
IndicesOptions.WildcardOptions.builder().matchOpen(true).matchClosed(true).allowEmptyExpressions(true).resolveAliases(false)
)
.gatekeeperOptions(
IndicesOptions.GatekeeperOptions.builder().allowAliasToMultipleIndices(false).allowClosedIndices(true).allowSelectors(false)
)
.build();
private final DataStreamOptions options;
public Request(StreamInput in) throws IOException {
super(in);
this.names = in.readStringArray();
this.indicesOptions = IndicesOptions.readIndicesOptions(in);
options = DataStreamOptions.read(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArray(names);
indicesOptions.writeIndicesOptions(out);
out.writeWriteable(options);
}
public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, String[] names, DataStreamOptions options) {
super(masterNodeTimeout, ackTimeout);
this.names = names;
this.options = options;
}
public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, String[] names, @Nullable DataStreamFailureStore failureStore) {
super(masterNodeTimeout, ackTimeout);
this.names = names;
this.options = new DataStreamOptions(failureStore);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (options.failureStore() == null) {
validationException = addValidationError("At least one option needs to be provided", validationException);
}
return validationException;
}
public String[] getNames() {
return names;
}
public DataStreamOptions getOptions() {
return options;
}
@Override
public String[] indices() {
return names;
}
@Override
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public Request indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
@Override
public boolean includeDataStreams() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Arrays.equals(names, request.names)
&& Objects.equals(indicesOptions, request.indicesOptions)
&& options.equals(request.options);
}
@Override
public int hashCode() {
int result = Objects.hash(indicesOptions, options);
result = 31 * result + Arrays.hashCode(names);
return result;
}
@Override
public IndicesRequest indices(String... names) {
this.names = names;
return this;
}
}
}
| Factory |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2562Timestamp322Test.java | {
"start": 1235,
"end": 4482
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testitDefaultFormat() throws Exception {
File testDir = extractResources("/mng-2562/default");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Date now = new Date();
Properties props = verifier.loadProperties("target/pom.properties");
String timestamp1 = props.getProperty("project.properties.timestamp1", "");
assertTrue(timestamp1.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z"), timestamp1);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(timestamp1);
assertTrue(Math.abs(now.getTime() - date.getTime()) < 24 * 60 * 60 * 1000, now + " vs " + date);
String timestamp2 = props.getProperty("project.properties.timestamp2", "");
assertEquals(timestamp1, timestamp2);
}
@Test
public void testitCustomFormat() throws Exception {
File testDir = extractResources("/mng-2562/custom");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Date now = new Date();
Properties props = verifier.loadProperties("target/pom.properties");
String timestamp1 = props.getProperty("project.properties.timestamp", "");
Date date = new SimpleDateFormat("mm:HH dd-MM-yyyy").parse(timestamp1);
assertTrue(Math.abs(now.getTime() - date.getTime()) < 24 * 60 * 60 * 1000, now + " vs " + date);
}
@Test
public void testitSameValueAcrossModules() throws Exception {
File testDir = extractResources("/mng-2562/reactor");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.deleteDirectory("child-1/target");
verifier.deleteDirectory("child-2/target");
verifier.deleteDirectory("child-3/target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/pom.properties");
String timestamp = props.getProperty("project.properties.timestamp", "");
Properties props1 = verifier.loadProperties("child-1/target/pom.properties");
String timestamp1 = props1.getProperty("project.properties.timestamp", "");
Properties props2 = verifier.loadProperties("child-2/target/pom.properties");
String timestamp2 = props2.getProperty("project.properties.timestamp", "");
Properties props3 = verifier.loadProperties("child-3/target/pom.properties");
String timestamp3 = props3.getProperty("project.properties.timestamp", "");
assertEquals(timestamp, timestamp1);
assertEquals(timestamp, timestamp2);
assertEquals(timestamp, timestamp3);
}
}
| MavenITmng2562Timestamp322Test |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ExtensionRegistrationViaParametersAndFieldsTests.java | {
"start": 10815,
"end": 11870
} | class ____ {
ConstructorParameterTestCase(@MagicParameter("constructor") String text) {
assertThat(text).isEqualTo("ConstructorParameterTestCase-0-constructor");
}
@BeforeEach
void beforeEach(String text, TestInfo testInfo) {
assertThat(text).isEqualTo("beforeEach-0-enigma");
assertThat(testInfo).isNotNull();
}
@Test
void test(TestInfo testInfo, String text) {
assertThat(testInfo).isNotNull();
assertThat(text).isEqualTo("test-1-enigma");
}
/**
* Redeclaring {@code @MagicParameter} should not result in a
* {@link ParameterResolutionException}.
*/
@AfterEach
void afterEach(Long number, TestInfo testInfo, @MagicParameter("method") String text) {
assertThat(number).isEqualTo(42L);
assertThat(testInfo).isNotNull();
assertThat(text).isEqualTo("afterEach-2-method");
}
}
/**
* The {@link MagicParameter.Extension} is first registered for the constructor
* and then used for lifecycle and test methods.
*/
@Nested
@ExtendWith(LongParameterResolver.class)
| ConstructorParameterTestCase |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/net/DomainPeer.java | {
"start": 1222,
"end": 3670
} | class ____ implements Peer {
private final DomainSocket socket;
private final OutputStream out;
private final InputStream in;
private final ReadableByteChannel channel;
public DomainPeer(DomainSocket socket) {
this.socket = socket;
this.out = socket.getOutputStream();
this.in = socket.getInputStream();
this.channel = socket.getChannel();
}
@Override
public ReadableByteChannel getInputStreamChannel() {
return channel;
}
@Override
public void setReadTimeout(int timeoutMs) throws IOException {
socket.setAttribute(DomainSocket.RECEIVE_TIMEOUT, timeoutMs);
}
@Override
public int getReceiveBufferSize() throws IOException {
return socket.getAttribute(DomainSocket.RECEIVE_BUFFER_SIZE);
}
@Override
public boolean getTcpNoDelay() throws IOException {
/* No TCP, no TCP_NODELAY. */
return false;
}
@Override
public void setWriteTimeout(int timeoutMs) throws IOException {
socket.setAttribute(DomainSocket.SEND_TIMEOUT, timeoutMs);
}
@Override
public boolean isClosed() {
return !socket.isOpen();
}
@Override
public void close() throws IOException {
socket.close();
}
@Override
public String getRemoteAddressString() {
return "unix:" + socket.getPath();
}
@Override
public String getLocalAddressString() {
return "<local>";
}
@Override
public InputStream getInputStream() throws IOException {
return in;
}
@Override
public OutputStream getOutputStream() throws IOException {
return out;
}
@Override
public boolean isLocal() {
/* UNIX domain sockets can only be used for local communication. */
return true;
}
@Override
public String toString() {
return "DomainPeer(" + getRemoteAddressString() + ")";
}
@Override
public DomainSocket getDomainSocket() {
return socket;
}
@Override
public boolean hasSecureChannel() {
//
// Communication over domain sockets is assumed to be secure, since it
// doesn't pass over any network. We also carefully control the privileges
// that can be used on the domain socket inode and its parent directories.
// See #{java.org.apache.hadoop.net.unix.DomainSocket#validateSocketPathSecurity0}
// for details.
//
// So unless you are running as root or the hdfs superuser, you cannot
// launch a man-in-the-middle attach on UNIX domain socket traffic.
//
return true;
}
}
| DomainPeer |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java | {
"start": 11385,
"end": 20991
} | class ____ be checked.
* @since 4.3.3
*/
public @Nullable AnnotatedElement getQualifiedElement() {
return this.qualifiedElement;
}
/**
* Specify a generics-containing target type of this bean definition, if known in advance.
* @since 4.3.3
*/
public void setTargetType(@Nullable ResolvableType targetType) {
this.targetType = targetType;
}
/**
* Specify the target type of this bean definition, if known in advance.
* @since 3.2.2
*/
public void setTargetType(@Nullable Class<?> targetType) {
this.targetType = (targetType != null ? ResolvableType.forClass(targetType) : null);
}
/**
* Return the target type of this bean definition, if known
* (either specified in advance or resolved on first instantiation).
* @since 3.2.2
*/
public @Nullable Class<?> getTargetType() {
if (this.resolvedTargetType != null) {
return this.resolvedTargetType;
}
ResolvableType targetType = this.targetType;
return (targetType != null ? targetType.resolve() : null);
}
/**
* Return a {@link ResolvableType} for this bean definition,
* either from runtime-cached type information or from configuration-time
* {@link #setTargetType(ResolvableType)} or {@link #setBeanClass(Class)},
* also considering resolved factory method definitions.
* @since 5.1
* @see #setTargetType(ResolvableType)
* @see #setBeanClass(Class)
* @see #setResolvedFactoryMethod(Method)
*/
@Override
public ResolvableType getResolvableType() {
ResolvableType targetType = this.targetType;
if (targetType != null) {
return targetType;
}
ResolvableType returnType = this.factoryMethodReturnType;
if (returnType != null) {
return returnType;
}
Method factoryMethod = getResolvedFactoryMethod();
if (factoryMethod != null) {
return ResolvableType.forMethodReturnType(factoryMethod);
}
return super.getResolvableType();
}
/**
* Determine preferred constructors to use for default construction, if any.
* Constructor arguments will be autowired if necessary.
* <p>As of 6.1, the default implementation of this method takes the
* {@link #PREFERRED_CONSTRUCTORS_ATTRIBUTE} attribute into account.
* Subclasses are encouraged to preserve this through a {@code super} call,
* either before or after their own preferred constructor determination.
* @return one or more preferred constructors, or {@code null} if none
* (in which case the regular no-arg default constructor will be called)
* @since 5.1
*/
public Constructor<?> @Nullable [] getPreferredConstructors() {
Object attribute = getAttribute(PREFERRED_CONSTRUCTORS_ATTRIBUTE);
if (attribute == null) {
return null;
}
if (attribute instanceof Constructor<?> constructor) {
return new Constructor<?>[] {constructor};
}
if (attribute instanceof Constructor<?>[] constructors) {
return constructors;
}
throw new IllegalArgumentException("Invalid value type for attribute '" +
PREFERRED_CONSTRUCTORS_ATTRIBUTE + "': " + attribute.getClass().getName());
}
/**
* Specify a factory method name that refers to a non-overloaded method.
*/
public void setUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = true;
}
/**
* Specify a factory method name that refers to an overloaded method.
* @since 5.2
*/
public void setNonUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = false;
}
/**
* Check whether the given candidate qualifies as a factory method.
*/
public boolean isFactoryMethod(Method candidate) {
return candidate.getName().equals(getFactoryMethodName());
}
/**
* Set a resolved Java Method for the factory method on this bean definition.
* @param method the resolved factory method, or {@code null} to reset it
* @since 5.2
*/
public void setResolvedFactoryMethod(@Nullable Method method) {
this.factoryMethodToIntrospect = method;
if (method != null) {
setUniqueFactoryMethodName(method.getName());
}
}
/**
* Return the resolved factory method as a Java Method object, if available.
* @return the factory method, or {@code null} if not found or not resolved yet
*/
public @Nullable Method getResolvedFactoryMethod() {
Method factoryMethod = this.factoryMethodToIntrospect;
if (factoryMethod == null &&
getInstanceSupplier() instanceof InstanceSupplier<?> instanceSupplier) {
factoryMethod = instanceSupplier.getFactoryMethod();
}
return factoryMethod;
}
/**
* Mark this bean definition as post-processed,
* i.e. processed by {@link MergedBeanDefinitionPostProcessor}.
* @since 6.0
*/
public void markAsPostProcessed() {
synchronized (this.postProcessingLock) {
this.postProcessed = true;
}
}
/**
* Register an externally managed configuration method or field.
*/
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedConfigMembers == null) {
this.externallyManagedConfigMembers = new LinkedHashSet<>(1);
}
this.externallyManagedConfigMembers.add(configMember);
}
}
/**
* Determine if the given method or field is an externally managed configuration member.
*/
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null &&
this.externallyManagedConfigMembers.contains(configMember));
}
}
/**
* Get all externally managed configuration methods and fields (as an immutable Set).
* @since 5.3.11
*/
public Set<Member> getExternallyManagedConfigMembers() {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null ?
Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedConfigMembers)) :
Collections.emptySet());
}
}
/**
* Register an externally managed configuration initialization method —
* for example, a method annotated with Jakarta's
* {@link jakarta.annotation.PostConstruct} annotation.
* <p>The supplied {@code initMethod} may be a
* {@linkplain Method#getName() simple method name} or a
* {@linkplain org.springframework.util.ClassUtils#getQualifiedMethodName(Method)
* qualified method name} for package-private and {@code private} methods.
* A qualified name is necessary for package-private and {@code private} methods
* in order to disambiguate between multiple such methods with the same name
* within a type hierarchy.
*/
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedInitMethods == null) {
this.externallyManagedInitMethods = new LinkedHashSet<>(1);
}
this.externallyManagedInitMethods.add(initMethod);
}
}
/**
* Determine if the given method name indicates an externally managed
* initialization method.
* <p>See {@link #registerExternallyManagedInitMethod} for details
* regarding the format for the supplied {@code initMethod}.
*/
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null &&
this.externallyManagedInitMethods.contains(initMethod));
}
}
/**
* Determine if the given method name indicates an externally managed
* initialization method, regardless of method visibility.
* <p>In contrast to {@link #isExternallyManagedInitMethod(String)}, this
* method also returns {@code true} if there is a {@code private} externally
* managed initialization method that has been
* {@linkplain #registerExternallyManagedInitMethod(String) registered}
* using a qualified method name instead of a simple method name.
* @since 5.3.17
*/
boolean hasAnyExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (isExternallyManagedInitMethod(initMethod)) {
return true;
}
return hasAnyExternallyManagedMethod(this.externallyManagedInitMethods, initMethod);
}
}
/**
* Get all externally managed initialization methods (as an immutable Set).
* <p>See {@link #registerExternallyManagedInitMethod} for details
* regarding the format for the initialization methods in the returned set.
* @since 5.3.11
*/
public Set<String> getExternallyManagedInitMethods() {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null ?
Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedInitMethods)) :
Collections.emptySet());
}
}
/**
* Resolve the inferred destroy method if necessary.
* @since 6.0
*/
public void resolveDestroyMethodIfNecessary() {
setDestroyMethodNames(DisposableBeanAdapter
.inferDestroyMethodsIfNecessary(getResolvableType().toClass(), this));
}
/**
* Register an externally managed configuration destruction method —
* for example, a method annotated with JSR-250's
* {@link jakarta.annotation.PreDestroy} annotation.
* <p>The supplied {@code destroyMethod} may be the
* {@linkplain Method#getName() simple method name} for non-private methods or the
* {@linkplain org.springframework.util.ClassUtils#getQualifiedMethodName(Method)
* qualified method name} for {@code private} methods. A qualified name is
* necessary for {@code private} methods in order to disambiguate between
* multiple private methods with the same name within a | will |
java | elastic__elasticsearch | libs/x-content/impl/src/main/java/org/elasticsearch/xcontent/provider/XContentImplUtils.java | {
"start": 673,
"end": 1389
} | class ____ {
public static <F extends JsonFactory, B extends TSFBuilder<F, B>> F configure(TSFBuilder<F, B> builder) {
// jackson 2.15 introduced a max string length. We have other limits in place to constrain max doc size,
// so here we set to max value (2GiB) so as not to constrain further than those existing limits.
// jackson 2.16 further introduced a max name length, which we also relax here temporarily.
// see https://github.com/elastic/elasticsearch/issues/58952
return builder.streamReadConstraints(
StreamReadConstraints.builder().maxStringLength(Integer.MAX_VALUE).maxNameLength(Integer.MAX_VALUE).build()
).build();
}
}
| XContentImplUtils |
java | netty__netty | microbench/src/main/java/io/netty/handler/codec/DateFormatterBenchmark.java | {
"start": 927,
"end": 1638
} | class ____ {
private static final String DATE_STRING = "Sun, 27 Nov 2016 19:18:46 GMT";
private static final Date DATE = new Date(784111777000L);
@Benchmark
public Date parseHttpHeaderDateFormatter() {
return DateFormatter.parseHttpDate(DATE_STRING);
}
@Benchmark
public Date parseHttpHeaderDateFormat() throws Exception {
return HttpHeaderDateFormat.get().parse(DATE_STRING);
}
@Benchmark
public String formatHttpHeaderDateFormatter() {
return DateFormatter.format(DATE);
}
@Benchmark
public String formatHttpHeaderDateFormat() throws Exception {
return HttpHeaderDateFormat.get().format(DATE);
}
}
| DateFormatterBenchmark |
java | apache__camel | dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/MavenDependencyDownloader.java | {
"start": 2300,
"end": 26763
} | class ____ extends ServiceSupport implements DependencyDownloader {
private static final String MINIMUM_QUARKUS_VERSION = "2.0.0";
private static final Logger LOG = LoggerFactory.getLogger(MavenDependencyDownloader.class);
private static final String CP = System.getProperty("java.class.path");
private String[] bootClasspath;
private DownloadThreadPool threadPool;
private boolean verbose;
private ClassLoader classLoader;
private CamelContext camelContext;
private final Set<DownloadListener> downloadListeners = new LinkedHashSet<>();
private final Set<ArtifactDownloadListener> artifactDownloadListeners = new LinkedHashSet<>();
private final Map<String, DownloadRecord> downloadRecords = new HashMap<>();
private KnownReposResolver knownReposResolver;
private VersionResolver versionResolver;
private boolean download = true;
// all maven-resolver work is delegated to camel-tooling-maven
private MavenDownloader mavenDownloader;
// repository URLs set from "camel.jbang.repos" property or --repos option.
private String repositories;
private boolean fresh;
// settings.xml and settings-security.xml locations to be passed to MavenDownloader from camel-tooling-maven
private String mavenSettings;
private String mavenSettingsSecurity;
// to make it easy to turn off maven central/snapshot
boolean mavenCentralEnabled = true;
boolean mavenApacheSnapshotEnabled = true;
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public KnownReposResolver getKnownReposResolver() {
return knownReposResolver;
}
public void setKnownReposResolver(KnownReposResolver knownReposResolver) {
this.knownReposResolver = knownReposResolver;
}
@Override
public RepositoryResolver getRepositoryResolver() {
if (mavenDownloader != null) {
return mavenDownloader.getRepositoryResolver();
} else {
return null;
}
}
@Override
public VersionResolver getVersionResolver() {
return versionResolver;
}
@Override
public void setVersionResolver(VersionResolver versionResolver) {
this.versionResolver = versionResolver;
}
@Override
public void addDownloadListener(DownloadListener downloadListener) {
CamelContextAware.trySetCamelContext(downloadListener, getCamelContext());
downloadListeners.add(downloadListener);
}
@Override
public void addArtifactDownloadListener(ArtifactDownloadListener downloadListener) {
CamelContextAware.trySetCamelContext(downloadListener, getCamelContext());
artifactDownloadListeners.add(downloadListener);
}
@Override
public String getRepositories() {
return repositories;
}
@Override
public void setRepositories(String repositories) {
this.repositories = repositories;
}
@Override
public boolean isFresh() {
return fresh;
}
@Override
public void setFresh(boolean fresh) {
this.fresh = fresh;
}
public boolean isDownload() {
return download;
}
public void setDownload(boolean download) {
this.download = download;
}
@Override
public String getMavenSettings() {
return mavenSettings;
}
@Override
public void setMavenSettings(String mavenSettings) {
this.mavenSettings = mavenSettings;
}
@Override
public String getMavenSettingsSecurity() {
return mavenSettingsSecurity;
}
@Override
public void setMavenSettingsSecurity(String mavenSettingsSecurity) {
this.mavenSettingsSecurity = mavenSettingsSecurity;
}
@Override
public boolean isMavenCentralEnabled() {
return mavenCentralEnabled;
}
@Override
public void setMavenCentralEnabled(boolean mavenCentralEnabled) {
this.mavenCentralEnabled = mavenCentralEnabled;
}
@Override
public boolean isMavenApacheSnapshotEnabled() {
return mavenApacheSnapshotEnabled;
}
@Override
public void setMavenApacheSnapshotEnabled(boolean mavenApacheSnapshotEnabled) {
this.mavenApacheSnapshotEnabled = mavenApacheSnapshotEnabled;
}
@Override
public void downloadDependencyWithParent(String parentGav, String groupId, String artifactId, String version) {
doDownloadDependencyWithParent(parentGav, groupId, artifactId, version, true, false, null);
}
@Override
public void downloadDependency(String groupId, String artifactId, String version) {
downloadDependency(groupId, artifactId, version, true);
}
@Override
public void downloadDependency(String groupId, String artifactId, String version, String extraRepos) {
doDownloadDependency(groupId, artifactId, version, true, false, extraRepos);
}
@Override
public void downloadHiddenDependency(String groupId, String artifactId, String version) {
doDownloadDependency(groupId, artifactId, version, true, true, null);
}
@Override
public void downloadDependency(String groupId, String artifactId, String version, boolean transitively) {
doDownloadDependency(groupId, artifactId, version, transitively, false, null);
}
protected void doDownloadDependency(
String groupId, String artifactId, String version, boolean transitively,
boolean hidden, String extraRepos) {
doDownloadDependencyWithParent(null, groupId, artifactId, version, transitively, hidden, extraRepos);
}
protected void doDownloadDependencyWithParent(
String parentGav,
String groupId, String artifactId, String version, boolean transitively,
boolean hidden, String extraRepos) {
if (versionResolver != null && version != null) {
version = versionResolver.resolve(version);
}
if (!hidden) {
// trigger listener
for (DownloadListener listener : downloadListeners) {
listener.onDownloadDependency(groupId, artifactId, version);
}
}
// when running jbang directly then the CP has some existing camel components
// that essentially is not needed to be downloaded, but we need the listener to trigger
// to capture that the GAV is required for running the application
if (CP != null) {
// is it already on classpath
String target = artifactId;
if (version != null) {
target = target + "-" + version;
}
if (CP.contains(target)) {
// already on classpath
return;
}
}
// we need version to be able to download from maven
if (ObjectHelper.isEmpty(version)) {
return;
}
String gav = groupId + ":" + artifactId + ":" + version;
String targetVersion = version;
threadPool.download(LOG, () -> {
List<String> deps = List.of(gav);
// include Apache snapshot to make it easy to use upcoming releases
boolean useApacheSnapshots = "org.apache.camel".equals(groupId) && targetVersion.contains("SNAPSHOT");
// include extra repositories (if any) - these will be used in addition
// to the ones detected from ~/.m2/settings.xml and configured in
// org.apache.camel.main.download.MavenDependencyDownloader#repos
Set<String> extraRepositories = new LinkedHashSet<>(resolveExtraRepositories(extraRepos));
if (knownReposResolver != null) {
// and from known extra repositories (if any)
String known = knownReposResolver.getRepo(artifactId);
extraRepositories.addAll(resolveExtraRepositories(known));
}
List<MavenArtifact> artifacts = resolveDependenciesViaAether(parentGav, deps, extraRepositories,
transitively, useApacheSnapshots);
List<File> files = new ArrayList<>();
if (verbose) {
LOG.info("Dependencies: {} -> [{}]", gav, artifacts);
} else {
LOG.debug("Dependencies: {} -> [{}]", gav, artifacts);
}
for (MavenArtifact a : artifacts) {
File file = a.getFile();
// only add to classpath if not already present (do not trigger listener)
if (!alreadyOnClasspath(a.getGav().getGroupId(), a.getGav().getArtifactId(),
a.getGav().getVersion(), false)) {
if (classLoader instanceof DependencyDownloaderClassLoader) {
DependencyDownloaderClassLoader ddc = (DependencyDownloaderClassLoader) classLoader;
ddc.addFile(file);
}
files.add(file);
if (verbose) {
LOG.info("Added classpath: {}", a.getGav());
} else {
LOG.debug("Added classpath: {}", a.getGav());
}
}
}
// trigger listeners after downloaded and added to classloader
for (File file : files) {
for (ArtifactDownloadListener listener : artifactDownloadListeners) {
listener.onDownloadedFile(file);
}
}
if (!artifacts.isEmpty()) {
for (DownloadListener listener : downloadListeners) {
listener.onDownloadedDependency(groupId, artifactId, targetVersion);
}
}
if (!extraRepositories.isEmpty()) {
for (String repo : extraRepositories) {
for (DownloadListener listener : downloadListeners) {
listener.onExtraRepository(repo);
}
}
}
}, gav);
}
@Override
public MavenArtifact downloadArtifact(String groupId, String artifactId, String version) {
List<MavenArtifact> artifacts = downloadArtifacts(groupId, artifactId, version, false);
if (artifacts != null && artifacts.size() == 1) {
return artifacts.get(0);
}
return null;
}
@Override
public List<MavenArtifact> downloadArtifacts(String groupId, String artifactId, String version, boolean transitively) {
String gav = groupId + ":" + artifactId + ":" + version;
List<String> deps = List.of(gav);
// include Apache snapshot to make it easy to use upcoming releases
boolean useApacheSnapshots = "org.apache.camel".equals(groupId) && version.contains("SNAPSHOT");
List<MavenArtifact> artifacts = resolveDependenciesViaAether(deps, null, transitively, useApacheSnapshots);
if (verbose) {
LOG.info("Dependencies: {} -> [{}]", gav, artifacts);
} else {
LOG.debug("Dependencies: {} -> [{}]", gav, artifacts);
}
return artifacts;
}
@Override
public List<String[]> resolveAvailableVersions(
String groupId, String artifactId,
String minimumVersion, String repo) {
String gav = groupId + ":" + artifactId;
if (verbose) {
LOG.info("Downloading available versions: {}", gav);
} else {
LOG.debug("Downloading available versions: {}", gav);
}
List<String[]> answer = new ArrayList<>();
try {
List<MavenGav> gavs = mavenDownloader.resolveAvailableVersions(groupId, artifactId, repo);
Set<String> extraRepos = repo == null ? null : Collections.singleton(repo);
for (MavenGav mavenGav : gavs) {
String v = mavenGav.getVersion();
if ("camel-spring-boot".equals(artifactId)) {
resolveSpringBoot(minimumVersion, v, extraRepos, answer);
} else if ("camel-quarkus-catalog".equals(artifactId)) {
resolveQuarkus(minimumVersion, v, extraRepos, answer);
} else {
answer.add(new String[] { v, null });
}
}
} catch (Exception e) {
throw new DownloadException(e.getMessage(), e);
}
return answer;
}
private void resolveQuarkus(String minimumVersion, String v, Set<String> extraRepos, List<String[]> answer)
throws Exception {
if (VersionHelper.isGE(v, MINIMUM_QUARKUS_VERSION)) {
String cv = resolveCamelVersionByQuarkusVersion(v, extraRepos);
if (cv != null && VersionHelper.isGE(cv, minimumVersion)) {
answer.add(new String[] { cv, v });
}
}
}
private void resolveSpringBoot(String minimumVersion, String v, Set<String> extraRepos, List<String[]> answer)
throws Exception {
String sbv = null;
if (VersionHelper.isGE(v, minimumVersion)) {
sbv = resolveSpringBootVersionByCamelVersion(v, extraRepos);
}
answer.add(new String[] { v, sbv });
}
public boolean alreadyOnClasspath(String groupId, String artifactId, String version) {
return alreadyOnClasspath(groupId, artifactId, version, true);
}
private boolean alreadyOnClasspath(String groupId, String artifactId, String version, boolean listener) {
// if no artifact then regard this as okay
if (artifactId == null) {
return true;
}
if (versionResolver != null && version != null) {
version = versionResolver.resolve(version);
}
String target = artifactId;
if (version != null) {
target = target + "-" + version;
}
if (bootClasspath != null) {
for (String s : bootClasspath) {
if (s.contains(target)) {
if (listener) {
for (DownloadListener dl : downloadListeners) {
dl.onDownloadDependency(groupId, artifactId, version);
}
}
// already on classpath
return true;
}
}
}
if (classLoader instanceof URLClassLoader) {
// create path like target to match against the file url
String urlTarget = groupId + "/" + artifactId;
urlTarget = urlTarget.replace('.', '/');
urlTarget += "/" + version + "/" + target + ".jar";
urlTarget = FileUtil.normalizePath(urlTarget); // windows vs linux
URLClassLoader ucl = (URLClassLoader) classLoader;
for (URL u : ucl.getURLs()) {
String s = u.toString();
s = FileUtil.normalizePath(s);
if (s.contains(urlTarget)) {
// trigger listener
if (listener) {
for (DownloadListener dl : downloadListeners) {
dl.onDownloadDependency(groupId, artifactId, version);
}
}
// already on classpath
return true;
}
}
}
return false;
}
@Override
public void onLoadingKamelet(String name) {
// trigger listener
for (DownloadListener listener : downloadListeners) {
listener.onLoadingKamelet(name);
}
}
@Override
public DownloadRecord getDownloadState(String groupId, String artifactId, String version) {
return downloadRecords.get(groupId + ":" + artifactId + ":" + version);
}
@Override
public Collection<DownloadRecord> downloadRecords() {
return downloadRecords.values();
}
private Set<String> resolveExtraRepositories(String repositoryList) {
Set<String> repositories = new LinkedHashSet<>();
if (repositoryList != null) {
for (String repo : repositoryList.split("\\s*,\\s*")) {
try {
URL url = URI.create(repo).toURL();
if (url.getHost().equals("repo1.maven.org")) {
continue;
}
repositories.add(url.toExternalForm());
} catch (MalformedURLException e) {
LOG.warn("Cannot use {} URL: {}. Skipping.", repo, e.getMessage(), e);
}
}
}
return repositories;
}
@Override
protected void doBuild() {
if (classLoader == null && camelContext != null) {
classLoader = camelContext.getApplicationContextClassLoader();
}
threadPool = new DownloadThreadPool(this);
threadPool.setVerbose(verbose);
threadPool.setCamelContext(camelContext);
ServiceHelper.buildService(threadPool);
MavenDownloaderImpl mavenDownloaderImpl = new MavenDownloaderImpl();
mavenDownloaderImpl.setMavenSettingsLocation(mavenSettings);
mavenDownloaderImpl.setMavenSettingsSecurityLocation(mavenSettingsSecurity);
mavenDownloaderImpl.setMavenCentralEnabled(mavenCentralEnabled);
mavenDownloaderImpl.setMavenApacheSnapshotEnabled(mavenApacheSnapshotEnabled);
mavenDownloaderImpl.setRepos(repositories);
mavenDownloaderImpl.setFresh(fresh);
mavenDownloaderImpl.setOffline(!download);
// use listener to keep track of which JARs was downloaded from a remote Maven repo (and how long time it took)
mavenDownloaderImpl.setRemoteArtifactDownloadListener(new RemoteArtifactDownloadListener() {
@Override
public void artifactDownloading(String groupId, String artifactId, String version, String repoId, String repoUrl) {
String gav = groupId + ":" + artifactId + ":" + version;
if (verbose) {
LOG.info("Downloading: {} from: {}@{}", gav, repoId, repoUrl);
} else {
LOG.debug("Downloading: {} from: {}@{}", gav, repoId, repoUrl);
}
}
@Override
public void artifactDownloaded(
String groupId, String artifactId, String version, String repoId, String repoUrl, long elapsed) {
String gav = groupId + ":" + artifactId + ":" + version;
downloadRecords.put(gav, new DownloadRecord(groupId, artifactId, version, repoId, repoUrl, elapsed));
if (verbose) {
LOG.info("Downloaded: {} (took: {}ms) from: {}@{}", gav, elapsed, repoId, repoUrl);
} else {
LOG.debug("Downloaded: {} (took: {}ms) from: {}@{}", gav, elapsed, repoId, repoUrl);
}
}
});
ServiceHelper.buildService(mavenDownloaderImpl);
mavenDownloader = mavenDownloaderImpl;
}
@Override
protected void doInit() {
RuntimeMXBean mb = ManagementFactory.getRuntimeMXBean();
if (mb != null) {
bootClasspath = mb.getClassPath().split("[:|;]");
}
ServiceHelper.initService(versionResolver, threadPool, mavenDownloader);
}
@Override
protected void doStart() throws Exception {
ServiceHelper.startService(threadPool, mavenDownloader, versionResolver);
}
@Override
protected void doStop() {
ServiceHelper.stopAndShutdownServices(versionResolver, mavenDownloader, threadPool);
}
public List<MavenArtifact> resolveDependenciesViaAether(
List<String> depIds,
Set<String> extraRepositories, boolean transitively, boolean useApacheSnapshots) {
return resolveDependenciesViaAether(null, depIds, extraRepositories, transitively,
useApacheSnapshots);
}
public List<MavenArtifact> resolveDependenciesViaAether(
String parentGav,
List<String> depIds, Set<String> extraRepositories,
boolean transitively, boolean useApacheSnapshots) {
try {
return mavenDownloader.resolveArtifacts(parentGav, depIds, extraRepositories, transitively, useApacheSnapshots);
} catch (MavenResolutionException e) {
String repos = (e.getRepositories() == null || e.getRepositories().isEmpty())
? "(empty URL list)"
: String.join(", ", e.getRepositories());
String msg = "Cannot resolve dependencies in " + repos;
throw new DownloadException(msg, e);
} catch (RuntimeException e) {
throw new DownloadException("Unknown error occurred while trying to resolve dependencies", e);
}
}
private String resolveCamelVersionByQuarkusVersion(String quarkusVersion, Set<String> extraRepos)
throws Exception {
String gav = "org.apache.camel.quarkus" + ":" + "camel-quarkus" + ":pom:" + quarkusVersion;
try {
List<MavenArtifact> artifacts = resolveDependenciesViaAether(List.of(gav), extraRepos, false, false);
if (!artifacts.isEmpty()) {
MavenArtifact ma = artifacts.get(0);
if (ma != null && ma.getFile() != null) {
String name = ma.getFile().getAbsolutePath();
File file = new File(name);
if (file.exists()) {
DocumentBuilderFactory dbf = XmlHelper.createDocumentBuilderFactory();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(file);
// the camel version is in <parent>
NodeList nl = dom.getElementsByTagName("parent");
if (nl.getLength() == 1) {
Element node = (Element) nl.item(0);
return node.getElementsByTagName("version").item(0).getTextContent();
}
}
}
}
} catch (DownloadException ex) {
// Artifact may not exist on repository, just skip it
LOG.debug(ex.getMessage(), ex);
}
return null;
}
private String resolveSpringBootVersionByCamelVersion(String camelVersion, Set<String> extraRepos)
throws Exception {
String gav;
if (VersionHelper.isGE(camelVersion, "4.15.0")) {
gav = "org.apache.camel:camel-parent:pom:" + camelVersion;
} else {
gav = "org.apache.camel.springboot:spring-boot:pom:" + camelVersion;
}
List<MavenArtifact> artifacts = resolveDependenciesViaAether(List.of(gav), extraRepos, false, false);
if (!artifacts.isEmpty()) {
MavenArtifact ma = artifacts.get(0);
if (ma != null && ma.getFile() != null) {
String name = ma.getFile().getAbsolutePath();
File file = new File(name);
if (file.exists()) {
DocumentBuilderFactory dbf = XmlHelper.createDocumentBuilderFactory();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(file);
// the camel version is in <properties>
NodeList nl = dom.getElementsByTagName("properties");
if (nl.getLength() > 0) {
Element node = (Element) nl.item(0);
NodeList springBootVersionNodeList = node.getElementsByTagName("spring-boot-version");
if (springBootVersionNodeList.getLength() > 0) {
return springBootVersionNodeList.item(0).getTextContent();
}
}
}
}
}
return null;
}
}
| MavenDependencyDownloader |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/AsyncCatchFunction.java | {
"start": 6258,
"end": 6882
} | class ____ representing the exception type to catch. The method then completes
* the future with the result of applying this catch function to the input future and the
* specified exception type.
* <p>
* If the input future completes exceptionally with an instance of the specified exception
* type, the catch function is applied to the exception. Otherwise, if the future
* completes with a different type of exception or normally, the original result or
* exception is propagated.
*
* @param in the input {@code CompletableFuture} to which the catch function is applied
* @param eClazz the | object |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java | {
"start": 5554,
"end": 7546
} | class ____.lang.Object!",
e.getMessage());
}
}
@Test
public void mock_with_no_stubbings() {
assertTrue(mockingDetails(mock).getStubbings().isEmpty());
}
@Test
public void provides_stubbings_of_mock_in_declaration_order() {
when(mock.simpleMethod(1)).thenReturn("1");
when(mock.otherMethod()).thenReturn("2");
// when
Collection<Stubbing> stubbings = mockingDetails(mock).getStubbings();
// then
assertEquals(2, stubbings.size());
assertEquals(
"[mock.simpleMethod(1); stubbed with: [Returns: 1], mock.otherMethod(); stubbed with: [Returns: 2]]",
stubbings.toString());
}
@Test
public void manipulating_stubbings_explicitly_is_safe() {
when(mock.simpleMethod(1)).thenReturn("1");
// when somebody manipulates stubbings directly
mockingDetails(mock).getStubbings().clear();
// then it does not affect stubbings of the mock
assertEquals(1, mockingDetails(mock).getStubbings().size());
}
@Test
public void prints_invocations() throws Exception {
// given
given(mock.simpleMethod("different arg")).willReturn("foo");
mock.simpleMethod("arg");
// when
String log = Mockito.mockingDetails(mock).printInvocations();
// then
assertThat(log).containsIgnoringCase("unused");
assertThat(log).containsIgnoringCase("mock.simpleMethod(\"arg\")");
assertThat(log).containsIgnoringCase("mock.simpleMethod(\"different arg\")");
}
@Test
public void fails_when_printin_invocations_from_non_mock() {
try {
// when
mockingDetails(new Object()).printInvocations();
// then
fail();
} catch (NotAMockException e) {
assertEquals(
"Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of | java |
java | apache__camel | tests/camel-itest/src/test/java/org/apache/camel/itest/doc/DataFormatComponentConfigurationAndDocumentationTest.java | {
"start": 1696,
"end": 4328
} | class ____ extends CamelTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
@Test
void testFlatpackDefaultValue() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("flatpack");
assertNotNull(json);
DataFormatModel model = JsonMapper.generateDataFormatModel(json);
assertEquals("flatpack", model.getName());
Map<String, DataFormatOptionModel> options
= model.getOptions().stream().collect(Collectors.toMap(BaseOptionModel::getName, o -> o));
assertEquals(10, options.size());
BaseOptionModel found = options.get("textQualifier");
assertNotNull(found);
assertEquals("textQualifier", found.getName());
assertEquals("attribute", found.getKind());
assertFalse(found.isRequired());
assertEquals("string", found.getType());
assertEquals("java.lang.String", found.getJavaType());
assertFalse(found.isDeprecated());
assertFalse(found.isSecret());
assertEquals("If the text is qualified with a character. Uses quote character by default.", found.getDescription());
}
}
@Test
void testUniVocityTsvEscapeChar() throws Exception {
try (CamelContext context = new DefaultCamelContext()) {
String json = ((CatalogCamelContext) context).getEipParameterJsonSchema("univocity-tsv");
assertNotNull(json);
DataFormatModel model = JsonMapper.generateDataFormatModel(json);
assertEquals("univocity-tsv", model.getName());
Map<String, DataFormatOptionModel> options
= model.getOptions().stream().collect(Collectors.toMap(BaseOptionModel::getName, o -> o));
assertEquals(16, options.size());
BaseOptionModel found = options.get("escapeChar");
assertNotNull(found);
assertEquals("escapeChar", found.getName());
assertEquals("attribute", found.getKind());
assertFalse(found.isRequired());
assertEquals("string", found.getType());
assertEquals("java.lang.String", found.getJavaType());
assertFalse(found.isDeprecated());
assertFalse(found.isSecret());
assertEquals("\\", found.getDefaultValue());
assertEquals("The escape character.", found.getDescription());
}
}
}
| DataFormatComponentConfigurationAndDocumentationTest |
java | quarkusio__quarkus | extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcConfig.java | {
"start": 7966,
"end": 10394
} | class ____ with a scope annotation - this component would be again completely ignored.
*/
@WithDefault("true")
boolean detectWrongAnnotations();
/**
* If set to {@code true}, the container will perform additional validations mandated by the CDI specification.
* Some improvements on top of the CDI specification may be disabled. Applications that work as expected
* in the strict mode should work without a change in the default, non-strict mode.
* <p>
* The strict mode is mainly introduced to allow passing the CDI Lite TCK. Applications are recommended
* to use the default, non-strict mode, which makes CDI more convenient to use. The "strictness" of
* the strict mode (the set of additional validations and the set of disabled improvements on top of
* the CDI specification) may change over time.
* <p>
* Note that {@link #transformUnproxyableClasses} and {@link #removeUnusedBeans} also has effect on specification
* compatibility. You may want to disable these features to get behavior closer to the specification.
*/
@WithDefault("false")
boolean strictCompatibility();
/**
* Dev mode configuration.
*/
ArcDevModeConfig devMode();
/**
* Test mode configuration.
*/
ArcTestConfig test();
/**
* The list of packages that will not be checked for split package issues.
* <p>
* A package string representation can be:
* <ul>
* <li>a full name of the package, i.e. {@code org.acme.foo}</li>
* <li>a package name with suffix {@code .*}, i.e. {@code org.acme.*}, which matches a package that starts with provided
* value</li>
*/
Optional<List<String>> ignoredSplitPackages();
/**
* Context propagation configuration.
*/
ArcContextPropagationConfig contextPropagation();
/**
* If set to {@code true}, the container should try to optimize the contexts for some of the scopes. If set to {@code auto}
* then optimize the contexts if there's less than 1000 beans in the application. If set to {@code false} do not optimize
* the contexts.
* <p>
* Typically, some implementation parts of the context for {@link jakarta.enterprise.context.ApplicationScoped} could be
* pregenerated during build.
*/
@WithDefault("auto")
@ConfigDocIgnore
OptimizeContexts optimizeContexts();
public | annotated |
java | apache__flink | flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/connector/upserttest/sink/UpsertTestSinkBuilder.java | {
"start": 1650,
"end": 3408
} | class ____<IN> {
private File outputFile;
private SerializationSchema<IN> keySerializationSchema;
private SerializationSchema<IN> valueSerializationSchema;
/**
* Sets the output {@link File} to write to.
*
* @param outputFile
* @return {@link UpsertTestSinkBuilder}
*/
public UpsertTestSinkBuilder<IN> setOutputFile(File outputFile) {
this.outputFile = checkNotNull(outputFile);
return this;
}
/**
* Sets the key {@link SerializationSchema} that transforms incoming records to byte[].
*
* @param keySerializationSchema
* @return {@link UpsertTestSinkBuilder}
*/
public UpsertTestSinkBuilder<IN> setKeySerializationSchema(
SerializationSchema<IN> keySerializationSchema) {
this.keySerializationSchema = checkNotNull(keySerializationSchema);
return this;
}
/**
* Sets the value {@link SerializationSchema} that transforms incoming records to byte[].
*
* @param valueSerializationSchema
* @return {@link UpsertTestSinkBuilder}
*/
public UpsertTestSinkBuilder<IN> setValueSerializationSchema(
SerializationSchema<IN> valueSerializationSchema) {
this.valueSerializationSchema = checkNotNull(valueSerializationSchema);
return this;
}
/**
* Constructs the {@link UpsertTestSink} with the configured properties.
*
* @return {@link UpsertTestSink}
*/
public UpsertTestSink<IN> build() {
checkNotNull(outputFile);
checkNotNull(keySerializationSchema);
checkNotNull(valueSerializationSchema);
return new UpsertTestSink<>(outputFile, keySerializationSchema, valueSerializationSchema);
}
}
| UpsertTestSinkBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/named/parsed/entity/DomesticPublishingHouse.java | {
"start": 347,
"end": 436
} | class ____ extends PublishingHouse {
private String taxIdentifier;
}
| DomesticPublishingHouse |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/FailoverFailedException.java | {
"start": 1089,
"end": 1374
} | class ____ extends Exception {
private static final long serialVersionUID = 1L;
public FailoverFailedException(final String message) {
super(message);
}
public FailoverFailedException(String message, Throwable cause) {
super(message, cause);
}
}
| FailoverFailedException |
java | netty__netty | codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicSslEngine.java | {
"start": 1697,
"end": 8773
} | class ____ extends QuicSslEngine {
QuicheQuicSslContext ctx;
private final String peerHost;
private final int peerPort;
private final QuicheQuicSslSession session = new QuicheQuicSslSession();
private volatile Certificate[] localCertificateChain;
private List<SNIServerName> sniHostNames;
private boolean handshakeFinished;
private String applicationProtocol;
private boolean sessionReused;
final String tlsHostName;
volatile QuicheQuicConnection connection;
volatile Consumer<String> sniSelectedCallback;
QuicheQuicSslEngine(QuicheQuicSslContext ctx, @Nullable String peerHost, int peerPort) {
this.ctx = ctx;
this.peerHost = peerHost;
this.peerPort = peerPort;
// Use SNI if peerHost was specified and a valid hostname
// See https://github.com/netty/netty/issues/4746
if (ctx.isClient() && isValidHostNameForSNI(peerHost)) {
tlsHostName = peerHost;
sniHostNames = Collections.singletonList(new SNIHostName(tlsHostName));
} else {
tlsHostName = null;
}
}
long moveTo(String hostname, QuicheQuicSslContext ctx) {
// First of remove the engine from its previous QuicheQuicSslContext.
this.ctx.remove(this);
this.ctx = ctx;
long added = ctx.add(this);
Consumer<String> sniSelectedCallback = this.sniSelectedCallback;
if (sniSelectedCallback != null) {
sniSelectedCallback.accept(hostname);
}
return added;
}
@Nullable
QuicheQuicConnection createConnection(LongFunction<Long> connectionCreator) {
return ctx.createConnection(connectionCreator, this);
}
void setLocalCertificateChain(Certificate[] localCertificateChain) {
this.localCertificateChain = localCertificateChain;
}
/**
* Validate that the given hostname can be used in SNI extension.
*/
static boolean isValidHostNameForSNI(@Nullable String hostname) {
return hostname != null &&
hostname.indexOf('.') > 0 &&
!hostname.endsWith(".") &&
!NetUtil.isValidIpV4Address(hostname) &&
!NetUtil.isValidIpV6Address(hostname);
}
@Override
public SSLParameters getSSLParameters() {
SSLParameters parameters = super.getSSLParameters();
parameters.setServerNames(sniHostNames);
return parameters;
}
// These method will override the method defined by Java 8u251 and later. As we may compile with an earlier
// java8 version we don't use @Override annotations here.
public synchronized String getApplicationProtocol() {
return applicationProtocol;
}
// These method will override the method defined by Java 8u251 and later. As we may compile with an earlier
// java8 version we don't use @Override annotations here.
public synchronized String getHandshakeApplicationProtocol() {
return applicationProtocol;
}
@Override
public SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst) {
throw new UnsupportedOperationException();
}
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) {
throw new UnsupportedOperationException();
}
@Override
@Nullable
public Runnable getDelegatedTask() {
return null;
}
@Override
public void closeInbound() {
throw new UnsupportedOperationException();
}
@Override
public boolean isInboundDone() {
return false;
}
@Override
public void closeOutbound() {
throw new UnsupportedOperationException();
}
@Override
public boolean isOutboundDone() {
return false;
}
@Override
public String[] getSupportedCipherSuites() {
return ctx.cipherSuites().toArray(new String[0]);
}
@Override
public String[] getEnabledCipherSuites() {
return getSupportedCipherSuites();
}
@Override
public void setEnabledCipherSuites(String[] suites) {
throw new UnsupportedOperationException();
}
@Override
public String[] getSupportedProtocols() {
// QUIC only supports TLSv1.3
return new String[] { "TLSv1.3" };
}
@Override
public String[] getEnabledProtocols() {
return getSupportedProtocols();
}
@Override
public void setEnabledProtocols(String[] protocols) {
throw new UnsupportedOperationException();
}
@Override
public SSLSession getSession() {
return session;
}
@Override
@Nullable
public SSLSession getHandshakeSession() {
if (handshakeFinished) {
return null;
}
return session;
}
@Override
public void beginHandshake() {
// NOOP
}
@Override
public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
if (handshakeFinished) {
return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
}
return SSLEngineResult.HandshakeStatus.NEED_WRAP;
}
@Override
public void setUseClientMode(boolean clientMode) {
if (clientMode != ctx.isClient()) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean getUseClientMode() {
return ctx.isClient();
}
@Override
public void setNeedClientAuth(boolean b) {
throw new UnsupportedOperationException();
}
@Override
public boolean getNeedClientAuth() {
return ctx.clientAuth == ClientAuth.REQUIRE;
}
@Override
public void setWantClientAuth(boolean b) {
throw new UnsupportedOperationException();
}
@Override
public boolean getWantClientAuth() {
return ctx.clientAuth == ClientAuth.OPTIONAL;
}
@Override
public void setEnableSessionCreation(boolean flag) {
throw new UnsupportedOperationException();
}
@Override
public boolean getEnableSessionCreation() {
return false;
}
synchronized void handshakeFinished(byte[] id, String cipher, String protocol, byte[] peerCertificate,
byte[][] peerCertificateChain,
long creationTime, long timeout,
byte @Nullable [] applicationProtocol, boolean sessionReused) {
if (applicationProtocol == null) {
this.applicationProtocol = null;
} else {
this.applicationProtocol = new String(applicationProtocol);
}
session.handshakeFinished(id, cipher, protocol, peerCertificate, peerCertificateChain, creationTime, timeout);
this.sessionReused = sessionReused;
handshakeFinished = true;
}
void removeSessionFromCacheIfInvalid() {
session.removeFromCacheIfInvalid();
}
synchronized boolean isSessionReused() {
return sessionReused;
}
private final | QuicheQuicSslEngine |
java | google__guava | android/guava-tests/test/com/google/common/cache/TestingCacheLoaders.java | {
"start": 3709,
"end": 4294
} | class ____<K, V> extends CacheLoader<K, V> {
private final V constant;
ConstantLoader(V constant) {
this.constant = constant;
}
@Override
public V load(K key) {
return constant;
}
}
/**
* Returns a {@code new Object()} for every request, and increments a counter for every request.
* An {@code Integer} loader that returns the key for {@code load} requests, and increments the
* old value on {@code reload} requests. The load counts are accessible via {@link #getLoadCount}
* and {@link #getReloadCount}.
*/
static | ConstantLoader |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java | {
"start": 18284,
"end": 18812
} | class ____ annotation
* @return If the specified annotation type is present, return <code>true</code>, or <code>false</code>
*/
@SuppressWarnings("unchecked")
static boolean isAnnotationPresent(Class<?> type, Class<? extends Annotation> annotationType) {
return isAnnotationPresent(type, true, annotationType);
}
/**
* Tests the annotated element is present any specified annotation types
*
* @param annotatedElement the annotated element
* @param annotationClassName the | of |
java | google__dagger | dagger-runtime/test/javatests/dagger/internal/SingleCheckTest.java | {
"start": 970,
"end": 1434
} | class ____ {
@Test
public void create_nullPointerException() {
assertThrows(NullPointerException.class, () -> SingleCheck.provider(null));
}
@Test
public void get() {
AtomicInteger integer = new AtomicInteger();
Provider<Integer> provider = SingleCheck.provider(integer::getAndIncrement);
assertThat(provider.get()).isEqualTo(0);
assertThat(provider.get()).isEqualTo(0);
assertThat(provider.get()).isEqualTo(0);
}
}
| SingleCheckTest |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java | {
"start": 4034,
"end": 4608
} | interface ____ {
/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}.
*/
boolean proxyTargetClass() default false;
/**
* Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
* for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
* Off by default, i.e. no guarantees that {@code AopContext} access will work.
* @since 4.3.1
*/
boolean exposeProxy() default false;
}
| EnableAspectJAutoProxy |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/HazelcastSetComponentBuilderFactory.java | {
"start": 1389,
"end": 1894
} | interface ____ {
/**
* Hazelcast Set (camel-hazelcast)
* Perform operations on Hazelcast distributed set.
*
* Category: cache,clustering
* Since: 2.7
* Maven coordinates: org.apache.camel:camel-hazelcast
*
* @return the dsl builder
*/
static HazelcastSetComponentBuilder hazelcastSet() {
return new HazelcastSetComponentBuilderImpl();
}
/**
* Builder for the Hazelcast Set component.
*/
| HazelcastSetComponentBuilderFactory |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/Magnitude.java | {
"start": 3833,
"end": 3950
} | interface ____ evaluating the scalar value of the underlying float array.
*/
@FunctionalInterface
public | for |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/ShortValueSerializer.java | {
"start": 1247,
"end": 2950
} | class ____ extends TypeSerializerSingleton<ShortValue> {
private static final long serialVersionUID = 1L;
public static final ShortValueSerializer INSTANCE = new ShortValueSerializer();
@Override
public boolean isImmutableType() {
return false;
}
@Override
public ShortValue createInstance() {
return new ShortValue();
}
@Override
public ShortValue copy(ShortValue from) {
return copy(from, new ShortValue());
}
@Override
public ShortValue copy(ShortValue from, ShortValue reuse) {
reuse.setValue(from.getValue());
return reuse;
}
@Override
public int getLength() {
return 2;
}
@Override
public void serialize(ShortValue record, DataOutputView target) throws IOException {
record.write(target);
}
@Override
public ShortValue deserialize(DataInputView source) throws IOException {
return deserialize(new ShortValue(), source);
}
@Override
public ShortValue deserialize(ShortValue reuse, DataInputView source) throws IOException {
reuse.read(source);
return reuse;
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
target.writeShort(source.readShort());
}
@Override
public TypeSerializerSnapshot<ShortValue> snapshotConfiguration() {
return new ShortValueSerializerSnapshot();
}
// ------------------------------------------------------------------------
/** Serializer configuration snapshot for compatibility and format evolution. */
@SuppressWarnings("WeakerAccess")
public static final | ShortValueSerializer |
java | google__auto | value/src/main/java/com/google/auto/value/processor/AutoValueishTemplateVars.java | {
"start": 2346,
"end": 3215
} | class ____ the {@code @AutoValue} or {@code AutoOneOf}
* annotation and any generated subclass. This is empty, or contains type variables with optional
* bounds, for example {@code <K, V extends K>}.
*/
String formalTypes;
/**
* The generic signature used by any generated subclass for its superclass reference. This is
* empty, or contains only type variables with no bounds, for example {@code <K, V>}.
*/
String actualTypes;
/**
* The generic signature in {@link #actualTypes} where every variable has been replaced by a
* wildcard, for example {@code <?, ?>}.
*/
String wildcardTypes;
/**
* The text of the complete serialVersionUID declaration, or empty if there is none. When
* non-empty, it will be something like {@code private static final long serialVersionUID =
* 123L;}.
*/
String serialVersionUID;
}
| with |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/PropertiesPersister.java | {
"start": 1331,
"end": 4105
} | interface ____ {
/**
* Load properties from the given InputStream into the given
* Properties object.
* @param props the Properties object to load into
* @param is the InputStream to load from
* @throws IOException in case of I/O errors
* @see java.util.Properties#load
*/
void load(Properties props, InputStream is) throws IOException;
/**
* Load properties from the given Reader into the given
* Properties object.
* @param props the Properties object to load into
* @param reader the Reader to load from
* @throws IOException in case of I/O errors
*/
void load(Properties props, Reader reader) throws IOException;
/**
* Write the contents of the given Properties object to the
* given OutputStream.
* @param props the Properties object to store
* @param os the OutputStream to write to
* @param header the description of the property list
* @throws IOException in case of I/O errors
* @see java.util.Properties#store
*/
void store(Properties props, OutputStream os, String header) throws IOException;
/**
* Write the contents of the given Properties object to the
* given Writer.
* @param props the Properties object to store
* @param writer the Writer to write to
* @param header the description of the property list
* @throws IOException in case of I/O errors
*/
void store(Properties props, Writer writer, String header) throws IOException;
/**
* Load properties from the given XML InputStream into the
* given Properties object.
* @param props the Properties object to load into
* @param is the InputStream to load from
* @throws IOException in case of I/O errors
* @see java.util.Properties#loadFromXML(java.io.InputStream)
*/
void loadFromXml(Properties props, InputStream is) throws IOException;
/**
* Write the contents of the given Properties object to the
* given XML OutputStream.
* @param props the Properties object to store
* @param os the OutputStream to write to
* @param header the description of the property list
* @throws IOException in case of I/O errors
* @see java.util.Properties#storeToXML(java.io.OutputStream, String)
*/
void storeToXml(Properties props, OutputStream os, String header) throws IOException;
/**
* Write the contents of the given Properties object to the
* given XML OutputStream.
* @param props the Properties object to store
* @param os the OutputStream to write to
* @param encoding the encoding to use
* @param header the description of the property list
* @throws IOException in case of I/O errors
* @see java.util.Properties#storeToXML(java.io.OutputStream, String, String)
*/
void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException;
}
| PropertiesPersister |
java | grpc__grpc-java | okhttp/src/main/java/io/grpc/okhttp/OkHttpServerTransport.java | {
"start": 44736,
"end": 45260
} | class ____ implements KeepAliveManager.KeepAlivePinger {
@Override
public void ping() {
synchronized (lock) {
frameWriter.ping(false, 0, KEEPALIVE_PING);
frameWriter.flush();
}
tracer.reportKeepAliveSent();
}
@Override
public void onPingTimeout() {
synchronized (lock) {
goAwayStatus = Status.UNAVAILABLE
.withDescription("Keepalive failed. Considering connection dead");
GrpcUtil.closeQuietly(socket);
}
}
}
| KeepAlivePinger |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/LifecycleMethodExecutionExceptionHandlerTests.java | {
"start": 14087,
"end": 14395
} | class ____ extends BaseTestCase {
}
@SuppressWarnings("JUnitMalformedDeclaration")
@ExtendWith(ShouldNotBeCalledHandler.class)
@ExtendWith(SwallowExceptionHandler.class)
@ExtendWith(RethrowExceptionHandler.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
static | UnrecoverableExceptionTestCase |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/AnySetterTest.java | {
"start": 4641,
"end": 5404
} | class ____<T>
{
private String staticallyMappedProperty;
private Map<T, Integer> dynamicallyMappedProperties = new HashMap<T, Integer>();
public String getStaticallyMappedProperty() {
return staticallyMappedProperty;
}
@JsonAnySetter
public void addDynamicallyMappedProperty(T key, int value) {
dynamicallyMappedProperties.put(key, value);
}
public void setStaticallyMappedProperty(String staticallyMappedProperty) {
this.staticallyMappedProperty = staticallyMappedProperty;
}
@JsonAnyGetter
public Map<T, Integer> getDynamicallyMappedProperties() {
return dynamicallyMappedProperties;
}
}
static | MyGeneric |
java | square__retrofit | retrofit-adapters/rxjava3/src/main/java/retrofit2/adapter/rxjava3/ResultObservable.java | {
"start": 973,
"end": 1335
} | class ____<T> extends Observable<Result<T>> {
private final Observable<Response<T>> upstream;
ResultObservable(Observable<Response<T>> upstream) {
this.upstream = upstream;
}
@Override
protected void subscribeActual(Observer<? super Result<T>> observer) {
upstream.subscribe(new ResultObserver<>(observer));
}
private static | ResultObservable |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointSerializationTests.java | {
"start": 18479,
"end": 18717
} | class ____ {
private final Cycle cycle;
Alpha(Cycle cycle) {
this.cycle = cycle;
}
public Cycle getCycle() {
return this.cycle;
}
}
}
@Configuration(proxyBeanMethods = false)
@Import(Base.class)
static | Alpha |
java | apache__hadoop | hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/server/services/MicroZookeeperService.java | {
"start": 2863,
"end": 10118
} | class ____
extends AbstractService
implements RegistryBindingSource, RegistryConstants,
ZookeeperConfigOptions,
MicroZookeeperServiceKeys{
private static final Logger
LOG = LoggerFactory.getLogger(MicroZookeeperService.class);
private File instanceDir;
private File dataDir;
private int tickTime;
private int port;
private String host;
private boolean secureServer;
private ServerCnxnFactory factory;
private BindingInformation binding;
private File confDir;
private StringBuilder diagnostics = new StringBuilder();
/**
* Create an instance
* @param name service name
*/
public MicroZookeeperService(String name) {
super(name);
}
/**
* Get the connection string.
* @return the string
* @throws IllegalStateException if the connection is not yet valid
*/
public String getConnectionString() {
Preconditions.checkState(factory != null, "service not started");
InetSocketAddress addr = factory.getLocalAddress();
return String.format("%s:%d", addr.getHostName(), addr.getPort());
}
/**
* Get the connection address
* @return the connection as an address
* @throws IllegalStateException if the connection is not yet valid
*/
public InetSocketAddress getConnectionAddress() {
Preconditions.checkState(factory != null, "service not started");
return factory.getLocalAddress();
}
/**
* Create an inet socket addr from the local host + port number
* @param port port to use
* @return a (hostname, port) pair
* @throws UnknownHostException if the server cannot resolve the host
*/
private InetSocketAddress getAddress(int port) throws UnknownHostException {
return new InetSocketAddress(host, port <= 0 ? getRandomAvailablePort() : port);
}
/**
* Initialize the service, including choosing a path for the data
* @param conf configuration
* @throws Exception
*/
@Override
protected void serviceInit(Configuration conf) throws Exception {
port = conf.getInt(KEY_ZKSERVICE_PORT, 0);
tickTime = conf.getInt(KEY_ZKSERVICE_TICK_TIME,
ZooKeeperServer.DEFAULT_TICK_TIME);
String instancedirname = conf.getTrimmed(
KEY_ZKSERVICE_DIR, "");
host = conf.getTrimmed(KEY_ZKSERVICE_HOST, DEFAULT_ZKSERVICE_HOST);
if (instancedirname.isEmpty()) {
File testdir = new File(System.getProperty("test.dir", "target"));
instanceDir = new File(testdir, "zookeeper" + getName());
} else {
instanceDir = new File(instancedirname);
FileUtil.fullyDelete(instanceDir);
}
LOG.debug("Instance directory is {}", instanceDir);
mkdirStrict(instanceDir);
dataDir = new File(instanceDir, "data");
confDir = new File(instanceDir, "conf");
mkdirStrict(dataDir);
mkdirStrict(confDir);
super.serviceInit(conf);
}
/**
* Create a directory, ignoring if the dir is already there,
* and failing if a file or something else was at the end of that
* path
* @param dir dir to guarantee the existence of
* @throws IOException IO problems, or path exists but is not a dir
*/
private void mkdirStrict(File dir) throws IOException {
if (!dir.mkdirs()) {
if (!dir.isDirectory()) {
throw new IOException("Failed to mkdir " + dir);
}
}
}
/**
* Append a formatted string to the diagnostics.
* <p>
* A newline is appended afterwards.
* @param text text including any format commands
* @param args arguments for the forma operation.
*/
protected void addDiagnostics(String text, Object ... args) {
diagnostics.append(String.format(text, args)).append('\n');
}
/**
* Get the diagnostics info
* @return the diagnostics string built up
*/
public String getDiagnostics() {
return diagnostics.toString();
}
/**
* set up security. this must be done prior to creating
* the ZK instance, as it sets up JAAS if that has not been done already.
*
* @return true if the cluster has security enabled.
*/
public boolean setupSecurity() throws IOException {
Configuration conf = getConfig();
String jaasContext = conf.getTrimmed(KEY_REGISTRY_ZKSERVICE_JAAS_CONTEXT);
secureServer = StringUtils.isNotEmpty(jaasContext);
if (secureServer) {
RegistrySecurity.validateContext(jaasContext);
RegistrySecurity.bindZKToServerJAASContext(jaasContext);
// policy on failed auth
System.setProperty(PROP_ZK_ALLOW_FAILED_SASL_CLIENTS,
conf.get(KEY_ZKSERVICE_ALLOW_FAILED_SASL_CLIENTS,
"true"));
//needed so that you can use sasl: strings in the registry
System.setProperty(RegistryInternalConstants.ZOOKEEPER_AUTH_PROVIDER +".1",
RegistryInternalConstants.SASLAUTHENTICATION_PROVIDER);
String serverContext =
System.getProperty(PROP_ZK_SERVER_SASL_CONTEXT);
addDiagnostics("Server JAAS context s = %s", serverContext);
return true;
} else {
return false;
}
}
/**
* Startup: start ZK. It is only after this that
* the binding information is valid.
* @throws Exception
*/
@Override
protected void serviceStart() throws Exception {
setupSecurity();
FileTxnSnapLog ftxn = new FileTxnSnapLog(dataDir, dataDir);
ZooKeeperServer zkServer = new ZooKeeperServer(ftxn, tickTime, "");
LOG.info("Starting Local Zookeeper service");
factory = ServerCnxnFactory.createFactory();
factory.configure(getAddress(port), -1);
factory.startup(zkServer);
String connectString = getConnectionString();
LOG.info("In memory ZK started at {}\n", connectString);
if (LOG.isDebugEnabled()) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
zkServer.dumpConf(pw);
pw.flush();
LOG.debug("ZooKeeper config:\n" + sw.toString());
}
binding = new BindingInformation();
binding.ensembleProvider = new FixedEnsembleProvider(connectString);
binding.description =
getName() + " reachable at \"" + connectString + "\"";
addDiagnostics(binding.description);
// finally: set the binding information in the config
getConfig().set(KEY_REGISTRY_ZK_QUORUM, connectString);
}
/**
* When the service is stopped, it deletes the data directory
* and its contents
* @throws Exception
*/
@Override
protected void serviceStop() throws Exception {
if (factory != null) {
factory.shutdown();
factory = null;
}
if (dataDir != null) {
FileUtil.fullyDelete(dataDir);
}
}
@Override
public BindingInformation supplyBindingInformation() {
Preconditions.checkNotNull(binding,
"Service is not started: binding information undefined");
return binding;
}
/**
* Returns with a random open port can be used to set as server port for ZooKeeper.
* @return a random open port or 0 (in case of error)
*/
private int getRandomAvailablePort() {
port = 0;
try {
final ServerSocket s = new ServerSocket(0);
port = s.getLocalPort();
s.close();
} catch (IOException e) {
LOG.warn("ERROR during selecting random port for ZooKeeper server to bind." , e);
}
return port;
}
}
| MicroZookeeperService |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/SimpleStringDecoder.java | {
"start": 1413,
"end": 2029
} | class ____ implements Decoder<String> {
private BufferedReader reader;
@Override
public void open(InputStream input) throws IOException {
this.reader = new BufferedReader(new InputStreamReader(input));
}
@Override
public String decodeNext() throws IOException {
String nextLine = reader.readLine();
// String read will be write directly to the compacted file, so the '\n' should be appended.
return nextLine == null ? null : (nextLine + '\n');
}
@Override
public void close() throws IOException {
reader.close();
}
}
| SimpleStringDecoder |
java | apache__camel | components/camel-ai/camel-weaviate/src/main/java/org/apache/camel/component/weaviate/WeaviateVectorDb.java | {
"start": 1259,
"end": 4178
} | class ____ {
@Metadata(description = "The action to be performed.", javaType = "String",
enums = "CREATE_COLLECTION,CREATE_INDEX,UPSERT,INSERT,SEARCH,DELETE,UPDATE,QUERY,QUERY_BY_ID")
public static final String ACTION = "CamelWeaviateAction";
@Metadata(description = "Text Field Name for Insert/Upsert operation", javaType = "String")
public static final String TEXT_FIELD_NAME = "CamelWeaviateTextFieldName";
@Metadata(description = "Vector Field Name for Insert/Upsert operation", javaType = "String")
public static final String VECTOR_FIELD_NAME = "CamelweaviateVectorFieldName";
@Metadata(description = "Collection Name for Insert/Upsert operation", javaType = "String")
public static final String COLLECTION_NAME = "CamelWeaviateCollectionName";
@Metadata(description = "Collection Similarity Metric", javaType = "String", enums = "cosine,euclidean,dotproduct")
public static final String COLLECTION_SIMILARITY_METRIC = "CamelWeaviateCollectionSimilarityMetric";
@Metadata(description = "Collection Dimension", javaType = "int")
public static final String COLLECTION_DIMENSION = "CamelWeaviateCollectionDimension";
@Metadata(description = "Collection Cloud Vendor", javaType = "String", enums = "aws,gcp,azure")
public static final String COLLECTION_CLOUD = "CamelWeaviateCollectionCloud";
@Metadata(description = "Collection Cloud Vendor Region", javaType = "String", enums = "aws,gcp,azure")
public static final String COLLECTION_CLOUD_REGION = "CamelWeaviateCollectionCloudRegion";
@Metadata(description = "Index Name", javaType = "String")
public static final String INDEX_NAME = "CamelWeaviateIndexName";
@Metadata(description = "Weaviate Object fields", javaType = "HashMap")
public static final String FIELDS = "CamelWeaviateFields";
@Metadata(description = "Weaviate Object properties", javaType = "HashMap")
public static final String PROPERTIES = "CamelWeaviateProperties";
@Metadata(description = "Index Id", javaType = "String")
public static final String INDEX_ID = "CamelWeaviateIndexId";
@Metadata(description = "Query Top K", javaType = "Integer")
public static final String QUERY_TOP_K = "CamelWeaviateQueryTopK";
@Metadata(description = "Merges properties into the object", javaType = "Boolean", defaultValue = "true")
public static final String UPDATE_WITH_MERGE = "CamelWeaviateUpdateWithMerge";
@Metadata(description = "Key Name for Insert/Upsert operation", javaType = "String")
public static final String KEY_NAME = "CamelWeaviateKeyName";
@Metadata(description = "Key Value for Insert/Upsert operation", javaType = "String")
public static final String KEY_VALUE = "CamelWeaviateKeyValue";
}
}
| Headers |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/Generation.java | {
"start": 243,
"end": 769
} | class ____ {
private String age;
private String culture;
private SubGeneration subGeneration;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCulture() {
return culture;
}
public void setCulture(String culture) {
this.culture = culture;
}
public SubGeneration getSubGeneration() {
return subGeneration;
}
public void setSubGeneration(SubGeneration subGeneration) {
this.subGeneration = subGeneration;
}
@Embeddable
public static | Generation |
java | elastic__elasticsearch | x-pack/plugin/kql/src/yamlRestTest/java/org/elasticsearch/xpack/kql/KqlRestIT.java | {
"start": 669,
"end": 1369
} | class ____ extends ESClientYamlSuiteTestCase {
@ClassRule
public static ElasticsearchCluster cluster = ElasticsearchCluster.local()
.setting("xpack.security.enabled", "false")
.setting("xpack.security.http.ssl.enabled", "false")
.distribution(DistributionType.DEFAULT)
.build();
public KqlRestIT(final ClientYamlTestCandidate testCandidate) {
super(testCandidate);
}
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
@ParametersFactory
public static Iterable<Object[]> parameters() throws Exception {
return ESClientYamlSuiteTestCase.createParameters();
}
}
| KqlRestIT |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java | {
"start": 1851,
"end": 5464
} | class ____ {
private static final String AUTHORIZATION_URI = "/oauth2/device_authorization";
private static final String CLIENT_ID = "client-1";
private OAuth2DeviceAuthorizationRequestAuthenticationConverter converter;
@BeforeEach
public void setUp() {
this.converter = new OAuth2DeviceAuthorizationRequestAuthenticationConverter();
}
@AfterEach
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
public void convertWhenMultipleScopeParametersThenInvalidRequestError() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.CLIENT_ID, CLIENT_ID);
request.addParameter(OAuth2ParameterNames.SCOPE, "message.read");
request.addParameter(OAuth2ParameterNames.SCOPE, "message.write");
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.converter.convert(request))
.withMessageContaining(OAuth2ParameterNames.SCOPE)
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void convertWhenMissingScopeThenReturnDeviceAuthorizationRequestAuthenticationToken() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.CLIENT_ID, CLIENT_ID);
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken(CLIENT_ID, null));
SecurityContextHolder.setContext(securityContext);
OAuth2DeviceAuthorizationRequestAuthenticationToken authentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) this.converter
.convert(request);
assertThat(authentication).isNotNull();
assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class);
assertThat(authentication.getAuthorizationUri()).endsWith(AUTHORIZATION_URI);
assertThat(authentication.getScopes()).isEmpty();
assertThat(authentication.getAdditionalParameters()).isEmpty();
}
@Test
public void convertWhenAllParametersThenReturnDeviceAuthorizationRequestAuthenticationToken() {
MockHttpServletRequest request = createRequest();
request.addParameter(OAuth2ParameterNames.CLIENT_ID, CLIENT_ID);
request.addParameter(OAuth2ParameterNames.SCOPE, "message.read message.write");
request.addParameter("param-1", "value-1");
request.addParameter("param-2", "value-1", "value-2");
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken(CLIENT_ID, null));
SecurityContextHolder.setContext(securityContext);
OAuth2DeviceAuthorizationRequestAuthenticationToken authentication = (OAuth2DeviceAuthorizationRequestAuthenticationToken) this.converter
.convert(request);
assertThat(authentication).isNotNull();
assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class);
assertThat(authentication.getAuthorizationUri()).endsWith(AUTHORIZATION_URI);
assertThat(authentication.getScopes()).containsExactly("message.read", "message.write");
assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"),
Map.entry("param-2", new String[] { "value-1", "value-2" }));
}
private static MockHttpServletRequest createRequest() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod(HttpMethod.POST.name());
request.setRequestURI(AUTHORIZATION_URI);
return request;
}
}
| OAuth2DeviceAuthorizationRequestAuthenticationConverterTests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/URLConnectionFactory.java | {
"start": 1726,
"end": 7645
} | class ____ {
private static final Logger LOG = LoggerFactory
.getLogger(URLConnectionFactory.class);
/**
* Timeout for socket connects and reads
*/
public final static int DEFAULT_SOCKET_TIMEOUT = 60 * 1000; // 1 minute
private final ConnectionConfigurator connConfigurator;
private static final ConnectionConfigurator DEFAULT_TIMEOUT_CONN_CONFIGURATOR
= new ConnectionConfigurator() {
@Override
public HttpURLConnection configure(HttpURLConnection conn)
throws IOException {
URLConnectionFactory.setTimeouts(conn,
DEFAULT_SOCKET_TIMEOUT,
DEFAULT_SOCKET_TIMEOUT);
return conn;
}
};
/**
* The URLConnectionFactory that sets the default timeout and it only trusts
* Java's SSL certificates.
*/
public static final URLConnectionFactory DEFAULT_SYSTEM_CONNECTION_FACTORY =
new URLConnectionFactory(DEFAULT_TIMEOUT_CONN_CONFIGURATOR);
/**
* Construct a new URLConnectionFactory based on the configuration. It will
* try to load SSL certificates when it is specified.
*/
public static URLConnectionFactory newDefaultURLConnectionFactory(
Configuration conf) {
ConnectionConfigurator conn = getSSLConnectionConfiguration(
DEFAULT_SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT, conf);
return new URLConnectionFactory(conn);
}
/**
* Construct a new URLConnectionFactory based on the configuration. It will
* hornor connecTimeout and readTimeout when they are specified.
*/
public static URLConnectionFactory newDefaultURLConnectionFactory(
int connectTimeout, int readTimeout, Configuration conf) {
ConnectionConfigurator conn = getSSLConnectionConfiguration(
connectTimeout, readTimeout, conf);
return new URLConnectionFactory(conn);
}
private static ConnectionConfigurator getSSLConnectionConfiguration(
final int connectTimeout, final int readTimeout, Configuration conf) {
ConnectionConfigurator conn;
try {
conn = new SSLConnectionConfigurator(connectTimeout, readTimeout, conf);
} catch (Exception e) {
LOG.warn(
"Cannot load customized ssl related configuration. Fallback to" +
" system-generic settings.",
e);
if (connectTimeout == DEFAULT_SOCKET_TIMEOUT &&
readTimeout == DEFAULT_SOCKET_TIMEOUT) {
conn = DEFAULT_TIMEOUT_CONN_CONFIGURATOR;
} else {
conn = new ConnectionConfigurator() {
@Override
public HttpURLConnection configure(HttpURLConnection connection)
throws IOException {
URLConnectionFactory.setTimeouts(connection,
connectTimeout,
readTimeout);
return connection;
}
};
}
}
return conn;
}
/**
* Construct a new URLConnectionFactory that supports OAut-based connections.
* It will also try to load the SSL configuration when they are specified.
*/
public static URLConnectionFactory newOAuth2URLConnectionFactory(
int connectTimeout, int readTimeout, Configuration conf)
throws IOException {
ConnectionConfigurator conn;
try {
ConnectionConfigurator sslConnConfigurator
= new SSLConnectionConfigurator(connectTimeout, readTimeout, conf);
conn = new OAuth2ConnectionConfigurator(conf, sslConnConfigurator);
} catch (Exception e) {
throw new IOException("Unable to load OAuth2 connection factory.", e);
}
return new URLConnectionFactory(conn);
}
@VisibleForTesting
URLConnectionFactory(ConnectionConfigurator connConfigurator) {
this.connConfigurator = connConfigurator;
}
/**
* Opens a url with read and connect timeouts
*
* @param url
* to open
* @return URLConnection
* @throws IOException
*/
public URLConnection openConnection(URL url) throws IOException {
try {
return openConnection(url, false);
} catch (AuthenticationException e) {
// Unreachable
LOG.error("Open connection {} failed", url, e);
return null;
}
}
/**
* Opens a url with read and connect timeouts
*
* @param url
* URL to open
* @param isSpnego
* whether the url should be authenticated via SPNEGO
* @return URLConnection
* @throws IOException
* @throws AuthenticationException
*/
public URLConnection openConnection(URL url, boolean isSpnego)
throws IOException, AuthenticationException {
if (isSpnego) {
LOG.debug("open AuthenticatedURL connection {}", url);
UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
final AuthenticatedURL.Token authToken = new AuthenticatedURL.Token();
return new AuthenticatedURL(new KerberosUgiAuthenticator(),
connConfigurator).openConnection(url, authToken);
} else {
LOG.debug("open URL connection");
URLConnection connection = url.openConnection();
if (connection instanceof HttpURLConnection) {
connConfigurator.configure((HttpURLConnection) connection);
}
return connection;
}
}
/**
* Sets timeout parameters on the given URLConnection.
*
* @param connection
* URLConnection to set
* @param connectTimeout
* @param readTimeout
* the connection and read timeout of the connection.
*/
private static void setTimeouts(URLConnection connection,
int connectTimeout,
int readTimeout) {
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
}
public void destroy() {
if (connConfigurator instanceof SSLConnectionConfigurator) {
((SSLConnectionConfigurator) connConfigurator).destroy();
}
}
}
| URLConnectionFactory |
java | apache__maven | compat/maven-model-builder/src/main/java/org/apache/maven/model/building/ModelBuildingListener.java | {
"start": 1402,
"end": 1692
} | interface ____ {
/**
* Notifies the listener that the model has been constructed to the extent where build extensions can be processed.
*
* @param event The details about the event.
*/
void buildExtensionsAssembled(ModelBuildingEvent event);
}
| ModelBuildingListener |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/arrow/sources/ArrowTableSourceOptions.java | {
"start": 1030,
"end": 1488
} | class ____ {
public static final ConfigOption<String> DATA =
ConfigOptions.key("data")
.stringType()
.noDefaultValue()
.withDescription(
"This is the data serialized by Arrow with a byte two-dimensional array. "
+ "Note: The byte two-dimensional array is converted into a string using base64.");
}
| ArrowTableSourceOptions |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.java | {
"start": 5946,
"end": 6389
} | class ____ {
public static StringBuilder append(StringBuilder input, String name) {
input.append(name);
return input;
}
}
""")
.addOutputLines(
"ReturnInputParam.java",
"""
package com.google.frobber;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
public final | ReturnInputParam |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/util/ReflectionUtils.java | {
"start": 43725,
"end": 43838
} | class ____
visitAllNestedClasses(clazz.getSuperclass(), predicate, consumer, errorHandling);
// Search | hierarchy |
java | apache__maven | api/maven-api-spi/src/main/java/org/apache/maven/api/spi/ProjectScopeProvider.java | {
"start": 1138,
"end": 1341
} | interface ____ plugins and extensions to define and register additional project scopes
* beyond the standard {@link ProjectScope#MAIN} and {@link ProjectScope#TEST} scopes.
* Implementations of this | allows |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/authentication/ott/GenerateOneTimeTokenRequestResolver.java | {
"start": 1027,
"end": 1352
} | interface ____ {
/**
* Resolves {@link GenerateOneTimeTokenRequest} from {@link HttpServletRequest}
* @param request {@link HttpServletRequest} to resolve
* @return {@link GenerateOneTimeTokenRequest}
*/
@Nullable
GenerateOneTimeTokenRequest resolve(HttpServletRequest request);
}
| GenerateOneTimeTokenRequestResolver |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/inject/JacksonInject4218Test.java | {
"start": 483,
"end": 711
} | class ____ {
@JacksonInject("id")
String id;
@JsonCreator
Dto(@JacksonInject("id")
@JsonProperty("id")
String id
) {
this.id = id;
}
}
| Dto |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/CronComponentBuilderFactory.java | {
"start": 1417,
"end": 1508
} | interface ____ {
/**
* Cron (camel-cron)
* A generic | CronComponentBuilderFactory |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/TaskStateManagerImpl.java | {
"start": 2425,
"end": 2739
} | class ____ the default implementation of {@link TaskStateManager} and collaborates with the
* job manager through {@link CheckpointResponder}) as well as a task-manager-local state store.
* Like this, client code does not have to deal with the differences between remote or local state
* on recovery because this | is |
java | apache__logging-log4j2 | log4j-core-java9/src/main/java/org/apache/logging/log4j/core/impl/ExtendedStackTraceElement.java | {
"start": 1464,
"end": 7996
} | class ____ implements Serializable {
static final ExtendedStackTraceElement[] EMPTY_ARRAY = {};
private static final long serialVersionUID = -2171069569241280505L;
;
private final ExtendedClassInfo extraClassInfo;
private final StackTraceElement stackTraceElement;
public ExtendedStackTraceElement(
final StackTraceElement stackTraceElement, final ExtendedClassInfo extraClassInfo) {
this.stackTraceElement = stackTraceElement;
this.extraClassInfo = extraClassInfo;
}
/**
* Called from Jackson for XML and JSON IO.
*/
public ExtendedStackTraceElement(
final String classLoaderName,
final String moduleName,
final String moduleVersion,
final String declaringClass,
final String methodName,
final String fileName,
final int lineNumber,
final boolean exact,
final String location,
final String version) {
this(
new StackTraceElement(
classLoaderName, moduleName, moduleVersion, declaringClass, methodName, fileName, lineNumber),
new ExtendedClassInfo(exact, location, version));
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ExtendedStackTraceElement)) {
return false;
}
final ExtendedStackTraceElement other = (ExtendedStackTraceElement) obj;
if (!Objects.equals(this.extraClassInfo, other.extraClassInfo)) {
return false;
}
if (!Objects.equals(this.stackTraceElement, other.stackTraceElement)) {
return false;
}
return true;
}
public String getClassLoaderName() {
return this.stackTraceElement.getClassLoaderName();
}
public String getModuleName() {
return this.stackTraceElement.getModuleName();
}
public String getModuleVersion() {
return this.stackTraceElement.getModuleVersion();
}
public String getClassName() {
return this.stackTraceElement.getClassName();
}
public boolean getExact() {
return this.extraClassInfo.getExact();
}
public ExtendedClassInfo getExtraClassInfo() {
return this.extraClassInfo;
}
public String getFileName() {
return this.stackTraceElement.getFileName();
}
public int getLineNumber() {
return this.stackTraceElement.getLineNumber();
}
public String getLocation() {
return this.extraClassInfo.getLocation();
}
public String getMethodName() {
return this.stackTraceElement.getMethodName();
}
public StackTraceElement getStackTraceElement() {
return this.stackTraceElement;
}
public String getVersion() {
return this.extraClassInfo.getVersion();
}
@Override
public int hashCode() {
return Objects.hash(extraClassInfo, stackTraceElement);
}
public boolean isNativeMethod() {
return this.stackTraceElement.isNativeMethod();
}
void renderOn(final StringBuilder output, final TextRenderer textRenderer) {
render(this.stackTraceElement, output, textRenderer);
textRenderer.render(" ", output, "Text");
this.extraClassInfo.renderOn(output, textRenderer);
}
private void render(
final StackTraceElement stElement, final StringBuilder output, final TextRenderer textRenderer) {
final String classLoaderName = getClassLoaderName();
if (Strings.isNotEmpty(classLoaderName)) {
switch (classLoaderName) {
case "app":
case "boot":
case "platform":
break;
default:
textRenderer.render(classLoaderName, output, "StackTraceElement.ClassLoaderName");
textRenderer.render("/", output, "StackTraceElement.ClassLoaderSeparator");
}
}
final String fileName = stElement.getFileName();
final int lineNumber = stElement.getLineNumber();
final String moduleName = getModuleName();
final String moduleVersion = getModuleVersion();
if (Strings.isNotEmpty(moduleName)) {
textRenderer.render(moduleName, output, "StackTraceElement.ModuleName");
if (Strings.isNotEmpty(moduleVersion) && !moduleName.startsWith("java")) {
textRenderer.render("@", output, "StackTraceElement.ModuleVersionSeparator");
textRenderer.render(moduleVersion, output, "StackTraceElement.ModuleVersion");
}
textRenderer.render("/", output, "StackTraceElement.ModuleNameSeparator");
}
textRenderer.render(getClassName(), output, "StackTraceElement.ClassName");
textRenderer.render(".", output, "StackTraceElement.ClassMethodSeparator");
textRenderer.render(stElement.getMethodName(), output, "StackTraceElement.MethodName");
if (stElement.isNativeMethod()) {
textRenderer.render("(Native Method)", output, "StackTraceElement.NativeMethod");
} else if (fileName != null && lineNumber >= 0) {
textRenderer.render("(", output, "StackTraceElement.Container");
textRenderer.render(fileName, output, "StackTraceElement.FileName");
textRenderer.render(":", output, "StackTraceElement.ContainerSeparator");
textRenderer.render(Integer.toString(lineNumber), output, "StackTraceElement.LineNumber");
textRenderer.render(")", output, "StackTraceElement.Container");
} else if (fileName != null) {
textRenderer.render("(", output, "StackTraceElement.Container");
textRenderer.render(fileName, output, "StackTraceElement.FileName");
textRenderer.render(")", output, "StackTraceElement.Container");
} else {
textRenderer.render("(", output, "StackTraceElement.Container");
textRenderer.render("Unknown Source", output, "StackTraceElement.UnknownSource");
textRenderer.render(")", output, "StackTraceElement.Container");
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
renderOn(sb, PlainTextRenderer.getInstance());
return sb.toString();
}
}
| ExtendedStackTraceElement |
java | quarkusio__quarkus | extensions/datasource/runtime/src/main/java/io/quarkus/datasource/runtime/DatabaseKindConverter.java | {
"start": 161,
"end": 332
} | class ____ implements Converter<String> {
@Override
public String convert(String value) {
return DatabaseKind.normalize(value);
}
}
| DatabaseKindConverter |
java | spring-projects__spring-boot | module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/humio/HumioPropertiesTests.java | {
"start": 1030,
"end": 1505
} | class ____ extends StepRegistryPropertiesTests {
@Test
void defaultValuesAreConsistent() {
HumioProperties properties = new HumioProperties();
HumioConfig config = (key) -> null;
assertStepRegistryDefaultValues(properties, config);
assertThat(properties.getApiToken()).isEqualTo(config.apiToken());
assertThat(properties.getTags()).isEmpty();
assertThat(config.tags()).isNull();
assertThat(properties.getUri()).isEqualTo(config.uri());
}
}
| HumioPropertiesTests |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecCorrelate.java | {
"start": 2263,
"end": 4138
} | class ____ extends CommonExecCorrelate implements StreamExecNode<RowData> {
public StreamExecCorrelate(
ReadableConfig tableConfig,
FlinkJoinType joinType,
RexCall invocation,
@Nullable RexNode condition,
InputProperty inputProperty,
RowType outputType,
String description) {
this(
ExecNodeContext.newNodeId(),
ExecNodeContext.newContext(StreamExecCorrelate.class),
ExecNodeContext.newPersistedConfig(StreamExecCorrelate.class, tableConfig),
joinType,
invocation,
condition,
Collections.singletonList(inputProperty),
outputType,
description);
}
@JsonCreator
public StreamExecCorrelate(
@JsonProperty(FIELD_NAME_ID) int id,
@JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context,
@JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig,
@JsonProperty(FIELD_NAME_JOIN_TYPE) FlinkJoinType joinType,
@JsonProperty(FIELD_NAME_FUNCTION_CALL) RexNode invocation,
@JsonProperty(FIELD_NAME_CONDITION) @Nullable RexNode condition,
@JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties,
@JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType,
@JsonProperty(FIELD_NAME_DESCRIPTION) String description) {
super(
id,
context,
persistedConfig,
joinType,
(RexCall) invocation,
condition,
TableStreamOperator.class,
true, // retainHeader
inputProperties,
outputType,
description);
}
}
| StreamExecCorrelate |
java | dropwizard__dropwizard | dropwizard-jersey/src/test/java/io/dropwizard/jersey/jackson/CustomDeserialization.java | {
"start": 694,
"end": 1463
} | class ____ extends StdDeserializer<CustomRepresentation> {
public CustomDeserialization() {
super((Class<?>) null);
}
@Override
public CustomRepresentation deserialize(
JsonParser jsonParser,
DeserializationContext deserializationContext
) throws IOException {
final Object ss = jsonParser.readValueAs(Object.class);
if (ss.equals("SQL_INECTION")) {
throw new RuntimeException("Database fell over due to sql injection");
} else {
throw new MyNastyException(jsonParser);
}
}
/**
* We can't get a regular {@link JsonMappingException} to report a null message, so we'll derive
* our own for our devious plan.
*/
public static | CustomDeserialization |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/generic/GenericDatumReader.java | {
"start": 9146,
"end": 9457
} | enum ____. May be overridden for alternate enum
* representations. By default, returns a GenericEnumSymbol.
*/
protected Object readEnum(Schema expected, Decoder in) throws IOException {
return createEnum(expected.getEnumSymbols().get(in.readEnum()), expected);
}
/**
* Called to create an | value |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/QueueInfo.java | {
"start": 1487,
"end": 5954
} | class ____ implements Writable {
private String queueName = "";
//The scheduling Information object is read back as String.
//Once the scheduling information is set there is no way to recover it.
private String schedulingInfo;
private QueueState queueState;
// Jobs submitted to the queue
private JobStatus[] stats;
private List<QueueInfo> children;
private Properties props;
/**
* Default constructor for QueueInfo.
*
*/
public QueueInfo() {
// make it running by default.
this.queueState = QueueState.RUNNING;
children = new ArrayList<QueueInfo>();
props = new Properties();
}
/**
* Construct a new QueueInfo object using the queue name and the
* scheduling information passed.
*
* @param queueName Name of the job queue
* @param schedulingInfo Scheduling Information associated with the job
* queue
*/
public QueueInfo(String queueName, String schedulingInfo) {
this();
this.queueName = queueName;
this.schedulingInfo = schedulingInfo;
}
/**
*
* @param queueName
* @param schedulingInfo
* @param state
* @param stats
*/
public QueueInfo(String queueName, String schedulingInfo, QueueState state,
JobStatus[] stats) {
this(queueName, schedulingInfo);
this.queueState = state;
this.stats = stats;
}
/**
* Set the queue name of the JobQueueInfo
*
* @param queueName Name of the job queue.
*/
protected void setQueueName(String queueName) {
this.queueName = queueName;
}
/**
* Get the queue name from JobQueueInfo
*
* @return queue name
*/
public String getQueueName() {
return queueName;
}
/**
* Set the scheduling information associated to particular job queue
*
* @param schedulingInfo
*/
protected void setSchedulingInfo(String schedulingInfo) {
this.schedulingInfo = schedulingInfo;
}
/**
* Gets the scheduling information associated to particular job queue.
* If nothing is set would return <b>"N/A"</b>
*
* @return Scheduling information associated to particular Job Queue
*/
public String getSchedulingInfo() {
if(schedulingInfo != null) {
return schedulingInfo;
}else {
return "N/A";
}
}
/**
* Set the state of the queue
* @param state state of the queue.
*/
protected void setState(QueueState state) {
queueState = state;
}
/**
* Return the queue state
* @return the queue state.
*/
public QueueState getState() {
return queueState;
}
protected void setJobStatuses(JobStatus[] stats) {
this.stats = stats;
}
/**
* Get immediate children.
*
* @return list of QueueInfo
*/
public List<QueueInfo> getQueueChildren() {
return children;
}
protected void setQueueChildren(List<QueueInfo> children) {
this.children = children;
}
/**
* Get properties.
*
* @return Properties
*/
public Properties getProperties() {
return props;
}
protected void setProperties(Properties props) {
this.props = props;
}
/**
* Get the jobs submitted to queue
* @return list of JobStatus for the submitted jobs
*/
public JobStatus[] getJobStatuses() {
return stats;
}
@Override
public void readFields(DataInput in) throws IOException {
queueName = StringInterner.weakIntern(Text.readString(in));
queueState = WritableUtils.readEnum(in, QueueState.class);
schedulingInfo = StringInterner.weakIntern(Text.readString(in));
int length = in.readInt();
stats = new JobStatus[length];
for (int i = 0; i < length; i++) {
stats[i] = new JobStatus();
stats[i].readFields(in);
}
int count = in.readInt();
children.clear();
for (int i = 0; i < count; i++) {
QueueInfo childQueueInfo = new QueueInfo();
childQueueInfo.readFields(in);
children.add(childQueueInfo);
}
}
@Override
public void write(DataOutput out) throws IOException {
Text.writeString(out, queueName);
WritableUtils.writeEnum(out, queueState);
if(schedulingInfo!= null) {
Text.writeString(out, schedulingInfo);
}else {
Text.writeString(out, "N/A");
}
out.writeInt(stats.length);
for (JobStatus stat : stats) {
stat.write(out);
}
out.writeInt(children.size());
for(QueueInfo childQueueInfo : children) {
childQueueInfo.write(out);
}
}
}
| QueueInfo |
java | quarkusio__quarkus | integration-tests/maven/src/test/java/io/quarkus/maven/it/NativeAgentIT.java | {
"start": 428,
"end": 1341
} | class ____ extends MojoTestBase {
@Test
public void testRunIntegrationTests() throws MavenInvocationException, IOException, InterruptedException {
final File testDir = initProject("projects/native-agent-integration");
final RunningInvoker running = new RunningInvoker(testDir, false);
MavenProcessInvocationResult runJvmITsWithAgent = running.execute(
List.of("clean", "verify", "-DskipITs=false", "-Dquarkus.test.integration-test-profile=test-with-native-agent"),
Map.of());
assertThat(runJvmITsWithAgent.getProcess().waitFor()).isZero();
MavenProcessInvocationResult runNativeITs = running
.execute(TestUtils.nativeArguments("verify", "-Dnative", "-Dquarkus.native.agent-configuration-apply"),
Map.of());
assertThat(runNativeITs.getProcess().waitFor()).isZero();
}
}
| NativeAgentIT |
java | spring-projects__spring-security | test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java | {
"start": 65098,
"end": 67017
} | class ____ implements OAuth2AuthorizedClientRepository {
static final String TOKEN_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName().concat(".TOKEN");
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName()
.concat(".ENABLED");
private final OAuth2AuthorizedClientRepository delegate;
@NullUnmarked
TestOAuth2AuthorizedClientRepository(@Nullable OAuth2AuthorizedClientRepository delegate) {
this.delegate = delegate;
}
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
if (isEnabled(request)) {
return (T) request.getAttribute(TOKEN_ATTR_NAME);
}
return this.delegate.loadAuthorizedClient(clientRegistrationId, principal, request);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (isEnabled(request)) {
request.setAttribute(TOKEN_ATTR_NAME, authorizedClient);
return;
}
this.delegate.saveAuthorizedClient(authorizedClient, principal, request, response);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (isEnabled(request)) {
request.removeAttribute(TOKEN_ATTR_NAME);
return;
}
this.delegate.removeAuthorizedClient(clientRegistrationId, principal, request, response);
}
static void enable(HttpServletRequest request) {
request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(HttpServletRequest request) {
return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME));
}
}
private static final | TestOAuth2AuthorizedClientRepository |
java | quarkusio__quarkus | integration-tests/jpa-mariadb/src/test/java/io/quarkus/it/jpa/mariadb/OfflineInGraalITCase.java | {
"start": 121,
"end": 172
} | class ____ extends OfflineTest {
}
| OfflineInGraalITCase |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/creation/InterfaceOverrideTest.java | {
"start": 307,
"end": 630
} | interface ____ extends Cloneable {
CloneableInterface clone();
}
@Test
public void inherit_public_method_from_interface() {
CloneableInterface i = Mockito.mock(CloneableInterface.class);
Mockito.when(i.clone()).thenReturn(i);
assertEquals(i, i.clone());
}
}
| CloneableInterface |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/util/LazyX509Certificate.java | {
"start": 1572,
"end": 6776
} | class ____ extends X509Certificate {
static final CertificateFactory X509_CERT_FACTORY;
static {
try {
X509_CERT_FACTORY = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new ExceptionInInitializerError(e);
}
}
private final byte[] bytes;
private X509Certificate wrapped;
/**
* Creates a new instance which will lazy parse the given bytes. Be aware that the bytes will not be cloned.
*/
public LazyX509Certificate(byte[] bytes) {
this.bytes = ObjectUtil.checkNotNull(bytes, "bytes");
}
@Override
public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {
unwrap().checkValidity();
}
@Override
public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {
unwrap().checkValidity(date);
}
@Override
public X500Principal getIssuerX500Principal() {
return unwrap().getIssuerX500Principal();
}
@Override
public X500Principal getSubjectX500Principal() {
return unwrap().getSubjectX500Principal();
}
@Override
public List<String> getExtendedKeyUsage() throws CertificateParsingException {
return unwrap().getExtendedKeyUsage();
}
@Override
public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException {
return unwrap().getSubjectAlternativeNames();
}
@Override
public Collection<List<?>> getIssuerAlternativeNames() throws CertificateParsingException {
return unwrap().getIssuerAlternativeNames();
}
@Override
public void verify(PublicKey key, Provider sigProvider)
throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
unwrap().verify(key, sigProvider);
}
@Override
public int getVersion() {
return unwrap().getVersion();
}
@Override
public BigInteger getSerialNumber() {
return unwrap().getSerialNumber();
}
@Override
public Principal getIssuerDN() {
return unwrap().getIssuerDN();
}
@Override
public Principal getSubjectDN() {
return unwrap().getSubjectDN();
}
@Override
public Date getNotBefore() {
return unwrap().getNotBefore();
}
@Override
public Date getNotAfter() {
return unwrap().getNotAfter();
}
@Override
public byte[] getTBSCertificate() throws CertificateEncodingException {
return unwrap().getTBSCertificate();
}
@Override
public byte[] getSignature() {
return unwrap().getSignature();
}
@Override
public String getSigAlgName() {
return unwrap().getSigAlgName();
}
@Override
public String getSigAlgOID() {
return unwrap().getSigAlgOID();
}
@Override
public byte[] getSigAlgParams() {
return unwrap().getSigAlgParams();
}
@Override
public boolean[] getIssuerUniqueID() {
return unwrap().getIssuerUniqueID();
}
@Override
public boolean[] getSubjectUniqueID() {
return unwrap().getSubjectUniqueID();
}
@Override
public boolean[] getKeyUsage() {
return unwrap().getKeyUsage();
}
@Override
public int getBasicConstraints() {
return unwrap().getBasicConstraints();
}
@Override
public byte[] getEncoded() {
return bytes.clone();
}
@Override
public void verify(PublicKey key)
throws CertificateException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException {
unwrap().verify(key);
}
@Override
public void verify(PublicKey key, String sigProvider)
throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
unwrap().verify(key, sigProvider);
}
@Override
public String toString() {
return unwrap().toString();
}
@Override
public PublicKey getPublicKey() {
return unwrap().getPublicKey();
}
@Override
public boolean hasUnsupportedCriticalExtension() {
return unwrap().hasUnsupportedCriticalExtension();
}
@Override
public Set<String> getCriticalExtensionOIDs() {
return unwrap().getCriticalExtensionOIDs();
}
@Override
public Set<String> getNonCriticalExtensionOIDs() {
return unwrap().getNonCriticalExtensionOIDs();
}
@Override
public byte[] getExtensionValue(String oid) {
return unwrap().getExtensionValue(oid);
}
private X509Certificate unwrap() {
X509Certificate wrapped = this.wrapped;
if (wrapped == null) {
try {
wrapped = this.wrapped = (X509Certificate) X509_CERT_FACTORY.generateCertificate(
new ByteArrayInputStream(bytes));
} catch (CertificateException e) {
throw new IllegalStateException(e);
}
}
return wrapped;
}
}
| LazyX509Certificate |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java | {
"start": 7281,
"end": 7485
} | class ____ extends DynamicMethodMatcher {
@Override
public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
return false;
}
}
}
| TestDynamicMethodMatcherWhichDoesNotMatch |
java | quarkusio__quarkus | integration-tests/resteasy-jackson/src/main/java/io/quarkus/it/resteasy/jackson/BigKeysResource.java | {
"start": 329,
"end": 837
} | class ____ {
private Map<BigDecimal, String> bdMap;
private Map<BigInteger, String> biMap;
public Map<BigDecimal, String> getBdMap() {
return bdMap;
}
public void setBdMap(Map<BigDecimal, String> bdMap) {
this.bdMap = bdMap;
}
public Map<BigInteger, String> getBiMap() {
return biMap;
}
public void setBiMap(Map<BigInteger, String> biMap) {
this.biMap = biMap;
}
}
}
| Payload |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/stats/NodesStatsRequestBuilder.java | {
"start": 838,
"end": 5238
} | class ____ extends NodesOperationRequestBuilder<
NodesStatsRequest,
NodesStatsResponse,
NodesStatsRequestBuilder> {
public NodesStatsRequestBuilder(ElasticsearchClient client, String[] nodeIds) {
super(client, TransportNodesStatsAction.TYPE, new NodesStatsRequest(nodeIds));
}
/**
* Sets all the request flags.
*/
public NodesStatsRequestBuilder all() {
request.all();
return this;
}
/**
* Clears all stats flags.
*/
public NodesStatsRequestBuilder clear() {
request.clear();
return this;
}
/**
* Should the node indices stats be returned.
*/
public NodesStatsRequestBuilder setIndices(boolean indices) {
request.indices(indices);
return this;
}
public NodesStatsRequestBuilder setBreaker(boolean breaker) {
addOrRemoveMetric(breaker, Metric.BREAKER);
return this;
}
public NodesStatsRequestBuilder setScript(boolean script) {
addOrRemoveMetric(script, Metric.SCRIPT);
return this;
}
/**
* Should the node indices stats be returned.
*/
public NodesStatsRequestBuilder setIndices(CommonStatsFlags indices) {
request.indices(indices);
return this;
}
/**
* Should the node OS stats be returned.
*/
public NodesStatsRequestBuilder setOs(boolean os) {
addOrRemoveMetric(os, Metric.OS);
return this;
}
/**
* Should the node OS stats be returned.
*/
public NodesStatsRequestBuilder setProcess(boolean process) {
addOrRemoveMetric(process, Metric.PROCESS);
return this;
}
/**
* Should the node JVM stats be returned.
*/
public NodesStatsRequestBuilder setJvm(boolean jvm) {
addOrRemoveMetric(jvm, Metric.JVM);
return this;
}
/**
* Should the node thread pool stats be returned.
*/
public NodesStatsRequestBuilder setThreadPool(boolean threadPool) {
addOrRemoveMetric(threadPool, Metric.THREAD_POOL);
return this;
}
/**
* Should the node file system stats be returned.
*/
public NodesStatsRequestBuilder setFs(boolean fs) {
addOrRemoveMetric(fs, Metric.FS);
return this;
}
/**
* Should the node Transport stats be returned.
*/
public NodesStatsRequestBuilder setTransport(boolean transport) {
addOrRemoveMetric(transport, Metric.TRANSPORT);
return this;
}
/**
* Should the node HTTP stats be returned.
*/
public NodesStatsRequestBuilder setHttp(boolean http) {
addOrRemoveMetric(http, Metric.HTTP);
return this;
}
/**
* Should the discovery stats be returned.
*/
public NodesStatsRequestBuilder setDiscovery(boolean discovery) {
addOrRemoveMetric(discovery, Metric.DISCOVERY);
return this;
}
/**
* Should ingest statistics be returned.
*/
public NodesStatsRequestBuilder setIngest(boolean ingest) {
addOrRemoveMetric(ingest, Metric.INGEST);
return this;
}
public NodesStatsRequestBuilder setAdaptiveSelection(boolean adaptiveSelection) {
addOrRemoveMetric(adaptiveSelection, Metric.ADAPTIVE_SELECTION);
return this;
}
/**
* Should script context cache statistics be returned
*/
public NodesStatsRequestBuilder setScriptCache(boolean scriptCache) {
addOrRemoveMetric(scriptCache, Metric.SCRIPT_CACHE);
return this;
}
public NodesStatsRequestBuilder setIndexingPressure(boolean indexingPressure) {
addOrRemoveMetric(indexingPressure, Metric.INDEXING_PRESSURE);
return this;
}
public NodesStatsRequestBuilder setRepositoryStats(boolean repositoryStats) {
addOrRemoveMetric(repositoryStats, Metric.REPOSITORIES);
return this;
}
public NodesStatsRequestBuilder setAllocationStats(boolean allocationStats) {
addOrRemoveMetric(allocationStats, Metric.ALLOCATIONS);
return this;
}
/**
* Helper method for adding metrics to a request
*/
private void addOrRemoveMetric(boolean includeMetric, Metric metric) {
if (includeMetric) {
request.addMetric(metric);
} else {
request.removeMetric(metric);
}
}
}
| NodesStatsRequestBuilder |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/SimpleJpaRepositoryUnitTests.java | {
"start": 2399,
"end": 8132
} | class ____ {
private SimpleJpaRepository<User, Integer> repo;
@Mock EntityManager em;
@Mock EntityManagerFactory entityManagerFactory;
@Mock PersistenceUnitUtil persistenceUnitUtil;
@Mock CriteriaBuilder builder;
@Mock CriteriaQuery<User> criteriaQuery;
@Mock CriteriaQuery<Long> countCriteriaQuery;
@Mock TypedQuery<User> query;
@Mock TypedQuery<Long> countQuery;
@Mock JpaEntityInformation<User, Integer> information;
@Mock CrudMethodMetadata metadata;
@Mock EntityGraph<User> entityGraph;
@Mock org.springframework.data.jpa.repository.EntityGraph entityGraphAnnotation;
@BeforeEach
void setUp() {
when(em.getDelegate()).thenReturn(em);
when(em.getEntityManagerFactory()).thenReturn(entityManagerFactory);
when(entityManagerFactory.getPersistenceUnitUtil()).thenReturn(persistenceUnitUtil);
when(information.getJavaType()).thenReturn(User.class);
when(em.getCriteriaBuilder()).thenReturn(builder);
when(builder.createQuery(User.class)).thenReturn(criteriaQuery);
when(builder.createQuery(Long.class)).thenReturn(countCriteriaQuery);
when(em.createQuery(criteriaQuery)).thenReturn(query);
when(em.createQuery(countCriteriaQuery)).thenReturn(countQuery);
MutableQueryHints hints = new MutableQueryHints();
when(metadata.getQueryHints()).thenReturn(hints);
when(metadata.getQueryHintsForCount()).thenReturn(hints);
repo = new SimpleJpaRepository<>(information, em);
repo.setRepositoryMethodMetadata(metadata);
}
@Test // DATAJPA-124, DATAJPA-912
void retrieveObjectsForPageableOutOfRange() {
when(countQuery.getSingleResult()).thenReturn(20L);
repo.findAll(PageRequest.of(2, 10));
verify(query).getResultList();
}
@Test // DATAJPA-912
void doesNotRetrieveCountWithoutOffsetAndResultsWithinPageSize() {
when(query.getResultList()).thenReturn(Arrays.asList(new User(), new User()));
repo.findAll(PageRequest.of(0, 10));
verify(countQuery, never()).getSingleResult();
}
@Test // DATAJPA-912
void doesNotRetrieveCountWithOffsetAndResultsWithinPageSize() {
when(query.getResultList()).thenReturn(Arrays.asList(new User(), new User()));
repo.findAll(PageRequest.of(2, 10));
verify(countQuery, never()).getSingleResult();
}
@Test // DATAJPA-177, gh-2719
void doesNotThrowExceptionIfEntityToDeleteDoesNotExist() {
assertThatNoException().isThrownBy(() -> repo.deleteById(4711));
}
@Test // DATAJPA-689, DATAJPA-696
@SuppressWarnings({ "rawtypes", "unchecked" })
void shouldPropagateConfiguredEntityGraphToFindOne() throws Exception {
String entityGraphName = "User.detail";
when(entityGraphAnnotation.value()).thenReturn(entityGraphName);
when(entityGraphAnnotation.type()).thenReturn(EntityGraphType.LOAD);
when(metadata.getEntityGraph()).thenReturn(entityGraphAnnotation);
when(em.getEntityGraph(entityGraphName)).thenReturn((EntityGraph) entityGraph);
when(information.getEntityName()).thenReturn("User");
when(metadata.getMethod()).thenReturn(CrudRepository.class.getMethod("findById", Object.class));
Integer id = 0;
repo.findById(id);
verify(em).find(User.class, id, singletonMap(EntityGraphType.LOAD.getKey(), (Object) entityGraph));
}
@Test // DATAJPA-931
void mergeGetsCalledWhenDetached() {
User detachedUser = new User();
when(em.contains(detachedUser)).thenReturn(false);
repo.save(detachedUser);
verify(em).merge(detachedUser);
}
@Test // DATAJPA-931, DATAJPA-1261
void mergeGetsCalledWhenAttached() {
User attachedUser = new User();
when(em.contains(attachedUser)).thenReturn(true);
repo.save(attachedUser);
verify(em).merge(attachedUser);
}
@Test // DATAJPA-1535
void doNothingWhenNewInstanceGetsDeleted() {
User newUser = new User();
newUser.setId(null);
when(em.getEntityManagerFactory()).thenReturn(entityManagerFactory);
repo.delete(newUser);
verify(em, never()).find(any(Class.class), any(Object.class));
verify(em, never()).remove(newUser);
verify(em, never()).merge(newUser);
}
@Test // DATAJPA-1535
void doNothingWhenNonExistentInstanceGetsDeleted() {
User newUser = new User();
newUser.setId(23);
when(information.isNew(newUser)).thenReturn(false);
when(em.getEntityManagerFactory()).thenReturn(entityManagerFactory);
when(persistenceUnitUtil.getIdentifier(any())).thenReturn(23);
when(em.find(User.class, 23)).thenReturn(null);
repo.delete(newUser);
verify(em, never()).remove(newUser);
verify(em, never()).merge(newUser);
}
@Test // GH-2054
void applyQueryHintsToCountQueriesForSpecificationPageables() {
when(query.getResultList()).thenReturn(Arrays.asList(new User(), new User()));
repo.findAll(Specification.unrestricted(), PageRequest.of(2, 1));
verify(metadata).getQueryHintsForCount();
}
@ParameterizedTest // GH-3188
@MethodSource("modifyingMethods")
void checkTransactionalAnnotation(Method method) {
Transactional transactional = method.getAnnotation(Transactional.class);
if (transactional == null) {
transactional = method.getDeclaringClass().getAnnotation(Transactional.class);
}
assertThat(transactional).isNotNull();
assertThat(transactional.readOnly()).isFalse();
}
static Stream<Arguments> modifyingMethods() {
return Stream.of(SimpleJpaRepository.class.getDeclaredMethods())
.filter(method -> Modifier.isPublic(method.getModifiers())) //
.filter(method -> !method.isBridge()) //
.filter(method -> method.getName().startsWith("delete") || method.getName().startsWith("save"))
.map(method -> Arguments.argumentSet(formatName(method), method));
}
private static String formatName(Method method) {
return method.toString().replaceAll("public ", "").replaceAll(SimpleJpaRepository.class.getName() + ".", "");
}
}
| SimpleJpaRepositoryUnitTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/inheritance/TypeLevelInheritanceTest.java | {
"start": 3716,
"end": 4024
} | class ____ {
public static int timesInvoked = 0;
@AroundInvoke
Object aroundInvoke(InvocationContext ctx) throws Exception {
timesInvoked++;
return ctx.proceed();
}
}
@SecondaryBinding
@Interceptor
@Priority(1)
static | ThirdInterceptor |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/concurrent/AbstractConcurrentInitializer.java | {
"start": 1382,
"end": 1824
} | class ____<T, E extends Exception> implements ConcurrentInitializer<T> {
/**
* Builds a new instance for subclasses.
*
* @param <I> The type of results supplied by this builder.
* @param <T> The type of the object managed by the initializer class.
* @param <B> The type of builder.
* @param <E> The exception type thrown by {@link #initialize()}.
*/
public abstract static | AbstractConcurrentInitializer |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/resources/org/hibernate/processor/test/packageinfo/Message.java | {
"start": 133,
"end": 184
} | class ____ {
@Id
Integer id;
String key;
}
| Message |
java | apache__flink | flink-clients/src/test/java/org/apache/flink/client/program/rest/RestClusterClientTest.java | {
"start": 67109,
"end": 67855
} | class ____
extends TestHandler<EmptyRequestBody, JobDetailsInfo, JobMessageParameters> {
private final JobDetailsInfo jobDetailsInfo;
private TestJobDetailsInfoHandler(@Nonnull JobDetailsInfo jobDetailsInfo) {
super(JobDetailsHeaders.getInstance());
this.jobDetailsInfo = checkNotNull(jobDetailsInfo);
}
@Override
protected CompletableFuture<JobDetailsInfo> handleRequest(
@Nonnull HandlerRequest<EmptyRequestBody> request,
@Nonnull DispatcherGateway gateway)
throws RestHandlerException {
return CompletableFuture.completedFuture(jobDetailsInfo);
}
}
private abstract | TestJobDetailsInfoHandler |
java | quarkusio__quarkus | extensions/amazon-lambda-http/maven-archetype/src/main/resources/archetype-resources/src/main/java/GreetingFunction.java | {
"start": 59,
"end": 166
} | class ____ {
@Funq
public String funqyHello() {
return "hello funqy";
}
}
| GreetingFunction |
java | resilience4j__resilience4j | resilience4j-micrometer/src/test/java/io/github/resilience4j/micrometer/tagged/TaggedRetryMetricsTest.java | {
"start": 1380,
"end": 8007
} | class ____ {
private MeterRegistry meterRegistry;
private Retry retry;
private RetryRegistry retryRegistry;
private TaggedRetryMetrics taggedRetryMetrics;
@Before
public void setUp() {
meterRegistry = new SimpleMeterRegistry();
retryRegistry = RetryRegistry.ofDefaults();
retry = retryRegistry.retry("backendA");
// record some basic stats
retry.executeRunnable(() -> {
});
taggedRetryMetrics = TaggedRetryMetrics.ofRetryRegistry(retryRegistry);
taggedRetryMetrics.bindTo(meterRegistry);
}
@Test
public void shouldAddMetricsForANewlyCreatedRetry() {
Retry newRetry = retryRegistry.retry("backendB");
assertThat(taggedRetryMetrics.meterIdMap).containsKeys("backendA", "backendB");
assertThat(taggedRetryMetrics.meterIdMap.get("backendA")).hasSize(4);
assertThat(taggedRetryMetrics.meterIdMap.get("backendB")).hasSize(4);
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(8);
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
"successful_without_retry", newRetry.getName());
assertThat(successfulWithoutRetry).isPresent();
assertThat(successfulWithoutRetry.get().count())
.isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
@Test
public void shouldAddCustomTags() {
retryRegistry.retry("backendF", Map.of("key1", "value1"));
assertThat(taggedRetryMetrics.meterIdMap).containsKeys("backendA", "backendF");
assertThat(taggedRetryMetrics.meterIdMap.get("backendA")).hasSize(4);
assertThat(taggedRetryMetrics.meterIdMap.get("backendF")).hasSize(4);
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(8);
assertThat(meterRegistry.get(DEFAULT_RETRY_CALLS).tag("key1", "value1")).isNotNull();
}
@Test
public void shouldRemovedMetricsForRemovedRetry() {
List<Meter> meters = meterRegistry.getMeters();
assertThat(meters).hasSize(4);
assertThat(taggedRetryMetrics.meterIdMap).containsKeys("backendA");
retryRegistry.remove("backendA");
assertThat(taggedRetryMetrics.meterIdMap).isEmpty();
meters = meterRegistry.getMeters();
assertThat(meters).isEmpty();
}
@Test
public void shouldReplaceMetrics() {
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
"successful_without_retry", retry.getName());
assertThat(successfulWithoutRetry).isPresent();
assertThat(successfulWithoutRetry.get().count())
.isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
Retry newRetry = Retry.of(retry.getName(), RetryConfig.custom().maxAttempts(1).build());
retryRegistry.replace(retry.getName(), newRetry);
counters = meterRegistry.get(DEFAULT_RETRY_CALLS).functionCounters();
successfulWithoutRetry = findMeterByKindAndNameTags(counters, "successful_without_retry",
newRetry.getName());
assertThat(successfulWithoutRetry).isPresent();
assertThat(successfulWithoutRetry.get().count())
.isEqualTo(newRetry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
@Test
public void successfulWithoutRetryCallsGaugeReportsCorrespondingValue() {
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> successfulWithoutRetry = findMeterByKindAndNameTags(counters,
"successful_without_retry", retry.getName());
assertThat(successfulWithoutRetry).isPresent();
assertThat(successfulWithoutRetry.get().count())
.isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithoutRetryAttempt());
}
@Test
public void successfulWithRetryCallsGaugeReportsCorrespondingValue() {
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> successfulWithRetry = findMeterByKindAndNameTags(counters,
"successful_with_retry", retry.getName());
assertThat(successfulWithRetry).isPresent();
assertThat(successfulWithRetry.get().count())
.isEqualTo(retry.getMetrics().getNumberOfSuccessfulCallsWithRetryAttempt());
}
@Test
public void failedWithoutRetryCallsGaugeReportsCorrespondingValue() {
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> failedWithoutRetry = findMeterByKindAndNameTags(counters,
"failed_without_retry", retry.getName());
assertThat(failedWithoutRetry).isPresent();
assertThat(failedWithoutRetry.get().count())
.isEqualTo(retry.getMetrics().getNumberOfFailedCallsWithoutRetryAttempt());
}
@Test
public void failedWithRetryCallsGaugeReportsCorrespondingValue() {
Collection<FunctionCounter> counters = meterRegistry.get(DEFAULT_RETRY_CALLS)
.functionCounters();
Optional<FunctionCounter> failedWithRetry = findMeterByKindAndNameTags(counters,
"failed_with_retry", retry.getName());
assertThat(failedWithRetry).isPresent();
assertThat(failedWithRetry.get().count())
.isEqualTo(retry.getMetrics().getNumberOfFailedCallsWithRetryAttempt());
}
@Test
public void metricsAreRegisteredWithCustomNames() {
MeterRegistry meterRegistry = new SimpleMeterRegistry();
RetryRegistry retryRegistry = RetryRegistry.ofDefaults();
retryRegistry.retry("backendA");
TaggedRetryMetrics.ofRetryRegistry(
RetryMetricNames.custom()
.callsMetricName("custom_calls")
.build(),
retryRegistry
).bindTo(meterRegistry);
Set<String> metricNames = meterRegistry.getMeters()
.stream()
.map(Meter::getId)
.map(Meter.Id::getName)
.collect(Collectors.toSet());
assertThat(metricNames).hasSameElementsAs(Collections.singletonList("custom_calls"));
}
}
| TaggedRetryMetricsTest |
java | quarkusio__quarkus | integration-tests/devmode/src/test/java/io/quarkus/test/reload/SomeBeanClient.java | {
"start": 288,
"end": 628
} | class ____ {
@Inject
SomeBean someBean;
void route(@Observes Router router) {
router.route("/test").handler(new Handler<RoutingContext>() {
@Override
public void handle(RoutingContext event) {
event.response().end(someBean.ping());
}
});
}
}
| SomeBeanClient |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.