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
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug2.java
{ "start": 244, "end": 708 }
class ____ extends TestCase { public void test_0() throws Exception { Entity entity = new Entity(); entity.setArticles(Collections.singletonList(new Article())); String jsonString = JSON.toJSONString(entity); System.out.println(jsonString); Entity entity2 = JSON.parseObject(jsonString, Entity.class); Assert.assertEquals(entity.getArticles().size(), entity2.getArticles().size()); } public static
Bug2
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java
{ "start": 20010, "end": 20126 }
class ____ { @ReadOperation @Nullable Object getSomething() { return null; } } }
NonJmxJmxEndpointExtension
java
google__error-prone
check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
{ "start": 21374, "end": 21526 }
interface ____ extends Suppressible { Description matchTypeParameter(TypeParameterTree tree, VisitorState state); } public
TypeParameterTreeMatcher
java
apache__camel
components/camel-web3j/src/test/java/org/apache/camel/component/web3j/integration/Web3jConsumerTransactionsTest.java
{ "start": 1260, "end": 1947 }
class ____ extends Web3jIntegrationTestSupport { @Test public void consumerTest() throws Exception { mockResult.expectedMinimumMessageCount(1); mockError.expectedMessageCount(0); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { errorHandler(deadLetterChannel("mock:error")); from("web3j://" + getUrl() + OPERATION.toLowerCase() + "=" + TRANSACTION_OBSERVABLE) .to("mock:result"); } }; } }
Web3jConsumerTransactionsTest
java
google__guava
android/guava/src/com/google/common/escape/CharEscaper.java
{ "start": 1702, "end": 1913 }
class ____ implement the {@link #escape(char)} method. * * @author Sven Mawson * @since 15.0 */ @GwtCompatible @SuppressWarnings("EscapedEntity") // We do mean for the user to see "<" etc. public abstract
and
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/generics/closest/GlobalExceptionHandler.java
{ "start": 701, "end": 887 }
class ____ implements ExceptionHandler<Throwable, String> { @Override public String handle(Object request, Throwable exception) { return null; } }
GlobalExceptionHandler
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/noclassannotation/NoAnnotationParentResourceWithoutPathImplInterface.java
{ "start": 1432, "end": 4495 }
class ____ implements NoAnnotationInterfaceWithPath { @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + PARENT_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH) public abstract String classPathOnInterface_ImplOnBase_ParentMethodWithPath_NoSecurityAnnotation(JsonObject array); @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnParent_NoSecurityAnnotation() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_PARENT + NO_SECURITY_ANNOTATION_PATH); } @PermitAll @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnParent_MethodPermitAll() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_PARENT + METHOD_PERMIT_ALL_PATH); } @DenyAll @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnParent_MethodDenyAll() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_PARENT + METHOD_DENY_ALL_PATH); } @RolesAllowed("admin") @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnParent_MethodRolesAllowed() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_PARENT + METHOD_ROLES_ALLOWED_PATH); } @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + IMPL_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH) public String classPathOnInterface_ImplOnParent_ImplMethodWithPath_NoSecurityAnnotation(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + IMPL_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH; } @Override public String classPathOnInterface_ImplOnParent_InterfaceMethodWithPath_NoSecurityAnnotation(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + INTERFACE_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH; } @DenyAll @Override public String classPathOnInterface_ImplOnParent_InterfaceMethodWithPath_MethodDenyAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + INTERFACE_METHOD_WITH_PATH + METHOD_DENY_ALL_PATH; } @PermitAll @Override public String classPathOnInterface_ImplOnParent_InterfaceMethodWithPath_MethodPermitAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + INTERFACE_METHOD_WITH_PATH + METHOD_PERMIT_ALL_PATH; } @RolesAllowed("admin") @Override public String classPathOnInterface_ImplOnParent_InterfaceMethodWithPath_MethodRolesAllowed(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_PARENT + INTERFACE_METHOD_WITH_PATH + METHOD_ROLES_ALLOWED_PATH; } }
NoAnnotationParentResourceWithoutPathImplInterface
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java
{ "start": 26342, "end": 26584 }
class ____ { @Bean SecurityContextEndpoint securityContextEndpoint() { return new SecurityContextEndpoint(); } } @Configuration(proxyBeanMethods = false) @Import(BaseConfiguration.class) static
SecurityContextEndpointConfiguration
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/search/MatchQueryParser.java
{ "start": 3144, "end": 11240 }
enum ____ implements Writeable { /** * The text is analyzed and terms are added to a boolean query. */ BOOLEAN(0, org.elasticsearch.index.query.MatchQueryBuilder.NAME), /** * The text is analyzed and used as a phrase query. */ PHRASE(1, MatchPhraseQueryBuilder.NAME), /** * The text is analyzed and used in a phrase query, with the last term acting as a prefix. */ PHRASE_PREFIX(2, MatchPhrasePrefixQueryBuilder.NAME), /** * The text is analyzed, terms are added to a boolean query with the last term acting as a prefix. */ BOOLEAN_PREFIX(3, MatchBoolPrefixQueryBuilder.NAME); private final int ordinal; private final String queryName; Type(int ordinal, String queryName) { this.ordinal = ordinal; this.queryName = queryName; } public static Type readFromStream(StreamInput in) throws IOException { int ord = in.readVInt(); for (Type type : Type.values()) { if (type.ordinal == ord) { return type; } } throw new ElasticsearchException("unknown serialized type [" + ord + "]"); } public String getQueryName() { return queryName; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(this.ordinal); } } public static final int DEFAULT_PHRASE_SLOP = 0; public static final boolean DEFAULT_LENIENCY = false; public static final ZeroTermsQueryOption DEFAULT_ZERO_TERMS_QUERY = ZeroTermsQueryOption.NONE; protected final SearchExecutionContext context; protected Analyzer analyzer; protected BooleanClause.Occur occur = BooleanClause.Occur.SHOULD; protected boolean enablePositionIncrements = true; protected int phraseSlop = DEFAULT_PHRASE_SLOP; protected Fuzziness fuzziness = null; protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength; protected int maxExpansions = FuzzyQuery.defaultMaxExpansions; protected SpanMultiTermQueryWrapper.SpanRewriteMethod spanRewriteMethod = new SpanBooleanQueryRewriteWithMaxClause( FuzzyQuery.defaultMaxExpansions, false ); protected boolean transpositions = FuzzyQuery.defaultTranspositions; protected MultiTermQuery.RewriteMethod fuzzyRewriteMethod; protected boolean lenient = DEFAULT_LENIENCY; protected ZeroTermsQueryOption zeroTermsQuery = DEFAULT_ZERO_TERMS_QUERY; protected boolean autoGenerateSynonymsPhraseQuery = true; public MatchQueryParser(SearchExecutionContext context) { this.context = context; } public void setAnalyzer(String analyzerName) { this.analyzer = context.getIndexAnalyzers().get(analyzerName); if (analyzer == null) { throw new IllegalArgumentException("No analyzer found for [" + analyzerName + "]"); } } public void setAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; } public void setOccur(BooleanClause.Occur occur) { this.occur = occur; } public void setEnablePositionIncrements(boolean enablePositionIncrements) { this.enablePositionIncrements = enablePositionIncrements; } public void setPhraseSlop(int phraseSlop) { this.phraseSlop = phraseSlop; } public void setFuzziness(Fuzziness fuzziness) { this.fuzziness = fuzziness; } public void setFuzzyPrefixLength(int fuzzyPrefixLength) { this.fuzzyPrefixLength = fuzzyPrefixLength; } public void setMaxExpansions(int maxExpansions) { this.maxExpansions = maxExpansions; this.spanRewriteMethod = new SpanBooleanQueryRewriteWithMaxClause(maxExpansions, false); } public void setTranspositions(boolean transpositions) { this.transpositions = transpositions; } public void setFuzzyRewriteMethod(MultiTermQuery.RewriteMethod fuzzyRewriteMethod) { this.fuzzyRewriteMethod = fuzzyRewriteMethod; } public void setLenient(boolean lenient) { this.lenient = lenient; } public void setZeroTermsQuery(ZeroTermsQueryOption zeroTermsQuery) { this.zeroTermsQuery = zeroTermsQuery; } public void setAutoGenerateSynonymsPhraseQuery(boolean enabled) { this.autoGenerateSynonymsPhraseQuery = enabled; } public Query parse(Type type, String fieldName, Object value) throws IOException { final MappedFieldType fieldType = context.getFieldType(fieldName); if (fieldType == null) { return newUnmappedFieldQuery(fieldName); } // We check here that the field supports text searches - // if it doesn't, we can bail out early without doing any further parsing. if (fieldType.getTextSearchInfo() == TextSearchInfo.NONE) { IllegalArgumentException iae; if (fieldType instanceof PlaceHolderFieldMapper.PlaceHolderFieldType) { iae = new IllegalArgumentException( "Field [" + fieldType.name() + "] of type [" + fieldType.typeName() + "] in legacy index does not support " + type.getQueryName() + " queries" ); } else { iae = new IllegalArgumentException( "Field [" + fieldType.name() + "] of type [" + fieldType.typeName() + "] does not support " + type.getQueryName() + " queries" ); } if (lenient) { return newLenientFieldQuery(fieldName, iae); } throw iae; } Analyzer analyzer = getAnalyzer(fieldType, type == Type.PHRASE || type == Type.PHRASE_PREFIX); assert analyzer != null; MatchQueryBuilder builder = new MatchQueryBuilder(analyzer, fieldType, enablePositionIncrements, autoGenerateSynonymsPhraseQuery); String resolvedFieldName = fieldType.name(); String stringValue = value.toString(); /* * If a keyword analyzer is used, we know that further analysis isn't * needed and can immediately return a term query. If the query is a bool * prefix query and the field type supports prefix queries, we return * a prefix query instead */ if (analyzer == Lucene.KEYWORD_ANALYZER && type != Type.PHRASE_PREFIX) { final Term term = new Term(resolvedFieldName, stringValue); if (type == Type.BOOLEAN_PREFIX && (fieldType instanceof TextFieldMapper.TextFieldType || fieldType instanceof KeywordFieldMapper.KeywordFieldType)) { return builder.newPrefixQuery(term); } else { return builder.newTermQuery(term, BoostAttribute.DEFAULT_BOOST); } } Query query = switch (type) { case BOOLEAN -> builder.createBooleanQuery(resolvedFieldName, stringValue, occur); case BOOLEAN_PREFIX -> builder.createBooleanPrefixQuery(resolvedFieldName, stringValue, occur); case PHRASE -> builder.createPhraseQuery(resolvedFieldName, stringValue, phraseSlop); case PHRASE_PREFIX -> builder.createPhrasePrefixQuery(resolvedFieldName, stringValue, phraseSlop); }; return query == null ? zeroTermsQuery.asQuery() : query; } protected Analyzer getAnalyzer(MappedFieldType fieldType, boolean quoted) { TextSearchInfo tsi = fieldType.getTextSearchInfo(); assert tsi != TextSearchInfo.NONE; if (analyzer == null) { return quoted ? tsi.searchQuoteAnalyzer() : tsi.searchAnalyzer(); } else { return analyzer; } }
Type
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/spi/AccessorNamingStrategy.java
{ "start": 390, "end": 2434 }
interface ____ { /** * Initializes the accessor naming strategy with the MapStruct processing environment. * * @param processingEnvironment environment for facilities * * @since 1.3 */ default void init(MapStructProcessingEnvironment processingEnvironment) { } /** * Returns the type of the given method. * * @param method to be analyzed. * * @return the method type. */ MethodType getMethodType(ExecutableElement method); /** * Returns the name of the property represented by the given getter or setter method. * <p> * The default implementation will e.g. return "name" for {@code public String getName()} or {@code public void * setName(String name)}. * * @param getterOrSetterMethod to be analyzed. * * @return property name derived from the getterOrSetterMethod */ String getPropertyName(ExecutableElement getterOrSetterMethod); /** * Returns the element name of the given adder method. * <p> * The default implementation will e.g. return "item" for {@code public void addItem(String item)}. * * @param adderMethod to be getterOrSetterMethod. * * @return getter name for collections */ String getElementName(ExecutableElement adderMethod); /** * Returns the getter name of the given collection property. * <p> * The default implementation will e.g. return "getItems" for "items". * * @param property to be getterOrSetterMethod. * * @return getter name for collection properties * * @deprecated MapStruct will not call this method anymore. Use {@link #getMethodType(ExecutableElement)} to * determine the {@link MethodType}. When collections somehow need to be treated special, it should be done in * {@link #getMethodType(ExecutableElement) } as well. In the future, this method will be removed. */ @Deprecated String getCollectionGetterName(String property); }
AccessorNamingStrategy
java
google__dagger
javatests/dagger/internal/codegen/InaccessibleTypeBindsTest.java
{ "start": 5169, "end": 5621 }
interface ____ {", " @Binds", " Foo bind(FooImpl impl);", "}"); Source component = CompilerTests.javaSource( "test.TestComponent", "package test;", "", "import dagger.Component;", "import other.OtherEntryPoint;", "import other.TestModule;", "", "@Component(modules = TestModule.class)", "
TestModule
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Activemq6ComponentBuilderFactory.java
{ "start": 1439, "end": 1985 }
interface ____ { /** * ActiveMQ 6.x (camel-activemq6) * Send messages to (or consume from) Apache ActiveMQ 6.x. This component * extends the Camel JMS component. * * Category: messaging * Since: 4.7 * Maven coordinates: org.apache.camel:camel-activemq6 * * @return the dsl builder */ static Activemq6ComponentBuilder activemq6() { return new Activemq6ComponentBuilderImpl(); } /** * Builder for the ActiveMQ 6.x component. */
Activemq6ComponentBuilderFactory
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/async/impl/NMClientAsyncImpl.java
{ "start": 17253, "end": 17495 }
enum ____ { START_CONTAINER, STOP_CONTAINER, QUERY_CONTAINER, UPDATE_CONTAINER_RESOURCE, REINITIALIZE_CONTAINER, RESTART_CONTAINER, ROLLBACK_LAST_REINIT, COMMIT_LAST_REINT } protected static
ContainerEventType
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/ThreadsDoTryCatchInterceptSendToAllEndpointIssueTest.java
{ "start": 1057, "end": 2251 }
class ____ extends ContextTestSupport { @Test public void testThreadsTryCatch() throws Exception { getMockEndpoint("mock:log:try").expectedMessageCount(1); getMockEndpoint("mock:log:catch").expectedMessageCount(1); getMockEndpoint("mock:log:world").expectedMessageCount(1); getMockEndpoint("mock:log:other").expectedMessageCount(0); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { // mock all endpoints context.getCamelContextExtension().registerEndpointCallback(new InterceptSendToMockEndpointStrategy("*")); return new RouteBuilder() { @Override public void configure() { from("direct:start").threads().doTry().to("log:try").throwException(new IllegalArgumentException("Forced")) .doCatch(Exception.class).to("log:catch").choice() .when(body().contains("World")).to("log:world").stop().otherwise().to("log:other").stop().end().end(); } }; } }
ThreadsDoTryCatchInterceptSendToAllEndpointIssueTest
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/remote/udp/UdpConnector.java
{ "start": 4978, "end": 6306 }
class ____ implements Runnable { private final AckEntry ackEntry; public UdpRetrySender(AckEntry ackEntry) { this.ackEntry = ackEntry; } @Override public void run() { // Received ack, no need to retry if (!containAck(ackEntry.getKey())) { return; } // Match max retry, push failed. if (ackEntry.getRetryTimes() > Constants.UDP_MAX_RETRY_TIMES) { Loggers.PUSH.warn("max re-push times reached, retry times {}, key: {}", ackEntry.getRetryTimes(), ackEntry.getKey()); ackMap.remove(ackEntry.getKey()); callbackFailed(ackEntry.getKey(), new NoRequiredRetryException()); return; } Loggers.PUSH.info("retry to push data, key: " + ackEntry.getKey()); try { ackEntry.increaseRetryTime(); doSend(ackEntry.getOrigin()); GlobalExecutor.scheduleRetransmitter(this, Constants.ACK_TIMEOUT_NANOS, TimeUnit.NANOSECONDS); } catch (Exception e) { callbackFailed(ackEntry.getKey(), e); ackMap.remove(ackEntry.getKey()); } } } private
UdpRetrySender
java
apache__camel
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/support/MyInOutTestConsumer.java
{ "start": 2816, "end": 4648 }
class ____ handle the messages to the temp queue as well responseConsumer.setMessageListener(this); //Now create the actual message you want to send TextMessage txtMessage = session.createTextMessage(); txtMessage.setText("MyProtocolMessage"); //Set the reply to field to the temp queue you created above, this is the queue the server //will respond to txtMessage.setJMSReplyTo(tempDest); //Set a correlation ID so when you get a response you know which sent message the response is for //If there is never more than one outstanding message to the server then the //same correlation ID can be used for all the messages...if there is more than one outstanding //message to the server you would presumably want to associate the correlation ID with this //message somehow...a Map works good String correlationId = createRandomString(); txtMessage.setJMSCorrelationID(correlationId); producer.send(txtMessage); } catch (JMSException e) { //Handle the exception appropriately } } private String createRandomString() { SecureRandom random = new SecureRandom(); long randomLong = random.nextLong(); return Long.toHexString(randomLong); } @Override public void onMessage(Message message) { String messageText = null; try { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; messageText = textMessage.getText(); LOG.info("messageText = {}", messageText); } } catch (JMSException e) { //Handle the exception appropriately } } }
will
java
apache__camel
components/camel-as2/camel-as2-component/src/main/java/org/apache/camel/component/as2/AS2Endpoint.java
{ "start": 3167, "end": 13172 }
class ____ extends AbstractApiEndpoint<AS2ApiName, AS2Configuration> { @UriParam private AS2Configuration configuration; private Object apiProxy; private AS2ClientConnection as2ClientConnection; private AS2AsyncMDNServerConnection as2AsyncMDNServerConnection; private AS2ServerConnection as2ServerConnection; public AS2Endpoint(String uri, AS2Component component, AS2ApiName apiName, String methodName, AS2Configuration endpointConfiguration) { super(uri, component, apiName, methodName, AS2ApiCollection.getCollection().getHelper(apiName), endpointConfiguration); this.configuration = endpointConfiguration; } public AS2ClientConnection getAS2ClientConnection() { return as2ClientConnection; } public AS2AsyncMDNServerConnection getAS2AsyncMDNServerConnection() { return as2AsyncMDNServerConnection; } public AS2ServerConnection getAS2ServerConnection() { return as2ServerConnection; } @Override public Producer createProducer() throws Exception { return new AS2Producer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { // make sure inBody is not set for consumers if (inBody != null) { throw new IllegalArgumentException("Option inBody is not supported for consumer endpoint"); } Consumer consumer; switch (configuration.getApiName()) { case SERVER: consumer = new AS2Consumer(this, processor); configureConsumer(consumer); break; case RECEIPT: consumer = new AS2AsyncMDNConsumer(this, processor); configureConsumer(consumer); break; default: throw new IllegalArgumentException("Invalid API name " + configuration.getApiName()); } return consumer; } public String getRequestUri() { return configuration.getRequestUri(); } public void setRequestUri(String requestUri) { configuration.setRequestUri(requestUri); } public String getSubject() { return configuration.getSubject(); } public void setSubject(String subject) { configuration.setSubject(subject); } public String getFrom() { return configuration.getFrom(); } public void setFrom(String from) { configuration.setFrom(from); } public String getAs2From() { return configuration.getAs2From(); } public void setAs2From(String as2From) { configuration.setAs2From(as2From); } public String getAs2To() { return configuration.getAs2To(); } public void setAs2To(String as2To) { configuration.setAs2To(as2To); } public AS2MessageStructure getAs2MessageStructure() { return configuration.getAs2MessageStructure(); } public void setAs2MessageStructure(AS2MessageStructure as2MessageStructure) { configuration.setAs2MessageStructure(as2MessageStructure); } public String getEdiMessageType() { return configuration.getEdiMessageType(); } public void setEdiMessageContentType(String ediMessageType) { configuration.setEdiMessageType(ediMessageType); } public String getEdiMessageTransferEncoding() { return configuration.getEdiMessageTransferEncoding(); } public void setEdiMessageTransferEncoding(String ediMessageTransferEncoding) { configuration.setEdiMessageTransferEncoding(ediMessageTransferEncoding); } public AS2SignatureAlgorithm getSigningAlgorithm() { return configuration.getSigningAlgorithm(); } public void setSigningAlgorithm(AS2SignatureAlgorithm signingAlgorithm) { configuration.setSigningAlgorithm(signingAlgorithm); } public Certificate[] getSigningCertificateChain() { return configuration.getSigningCertificateChain(); } public void setSigningCertificateChain(Certificate[] signingCertificateChain) { configuration.setSigningCertificateChain(signingCertificateChain); } public Certificate[] getValidateSigningCertificateChain() { return configuration.getValidateSigningCertificateChain(); } public void setValidateSigningCertificateChain(Certificate[] validateSigningCertificateChain) { configuration.setValidateSigningCertificateChain(validateSigningCertificateChain); } public PrivateKey getDecryptingPrivateKey() { return configuration.getDecryptingPrivateKey(); } public void setDecryptingPrivateKey(PrivateKey decryptingPrivateKey) { configuration.setDecryptingPrivateKey(decryptingPrivateKey); } public PrivateKey getSigningPrivateKey() { return configuration.getSigningPrivateKey(); } public void setSigningPrivateKey(PrivateKey signingPrivateKey) { configuration.setSigningPrivateKey(signingPrivateKey); } public AS2CompressionAlgorithm getCompressionAlgorithm() { return configuration.getCompressionAlgorithm(); } public void setCompressionAlgorithm(AS2CompressionAlgorithm compressionAlgorithm) { configuration.setCompressionAlgorithm(compressionAlgorithm); } public String getDispositionNotificationTo() { return configuration.getDispositionNotificationTo(); } public void setDispositionNotificationTo(String dispositionNotificationTo) { configuration.setDispositionNotificationTo(dispositionNotificationTo); } public String getSignedReceiptMicAlgorithms() { return configuration.getSignedReceiptMicAlgorithms(); } public void setSignedReceiptMicAlgorithms(String signedReceiptMicAlgorithms) { configuration.setSignedReceiptMicAlgorithms(signedReceiptMicAlgorithms); } public AS2EncryptionAlgorithm getEncryptingAlgorithm() { return configuration.getEncryptingAlgorithm(); } public void setEncryptingAlgorithm(AS2EncryptionAlgorithm encryptingAlgorithm) { configuration.setEncryptingAlgorithm(encryptingAlgorithm); } public Certificate[] getEncryptingCertificateChain() { return configuration.getEncryptingCertificateChain(); } public void setEncryptingCertificateChain(Certificate[] encryptingCertificateChain) { configuration.setEncryptingCertificateChain(encryptingCertificateChain); } public SSLContext getSslContext() { return configuration.getSslContext(); } public void setSslContext(SSLContext sslContext) { configuration.setSslContext(sslContext); } @Override protected ApiMethodPropertiesHelper<AS2Configuration> getPropertiesHelper() { return AS2PropertiesHelper.getHelper(getCamelContext()); } @Override protected String getThreadProfileName() { return AS2Constants.THREAD_PROFILE_NAME; } @Override protected void afterConfigureProperties() { // create HTTP connection eagerly, a good way to validate configuration switch (apiName) { case CLIENT: createAS2ClientConnection(); break; case SERVER: createAS2ServerConnection(); break; case RECEIPT: createAS2AsyncMDNServerConnection(); break; default: break; } } @Override public Object getApiProxy(ApiMethod method, Map<String, Object> args) { if (apiProxy == null) { createApiProxy(); } return apiProxy; } private void createApiProxy() { switch (apiName) { case CLIENT: apiProxy = new AS2ClientManager(getAS2ClientConnection()); break; case SERVER: apiProxy = new AS2ServerManager(getAS2ServerConnection()); break; case RECEIPT: apiProxy = new AS2AsyncMDNServerManager(getAS2AsyncMDNServerConnection()); break; default: throw new IllegalArgumentException("Invalid API name " + apiName); } } private void createAS2ClientConnection() { try { as2ClientConnection = AS2ConnectionHelper.createAS2ClientConnection(configuration); } catch (UnknownHostException e) { throw new RuntimeCamelException( String.format("Client HTTP connection failed: Unknown target host '%s'", configuration.getTargetHostname())); } catch (IOException e) { throw new RuntimeCamelException("Client HTTP connection failed", e); } } private void createAS2ServerConnection() { try { as2ServerConnection = AS2ConnectionHelper.createAS2ServerConnection(configuration); } catch (IOException e) { throw new RuntimeCamelException("Server HTTP connection failed", e); } } private void createAS2AsyncMDNServerConnection() { try { as2AsyncMDNServerConnection = AS2ConnectionHelper.createAS2AsyncMDNServerConnection(configuration); } catch (IOException e) { throw new RuntimeCamelException("Async MDN Server HTTP connection failed", e); } } @Override protected void doStart() throws Exception { super.doStart(); if (getSslContext() == null) { SSLContextParameters params = getComponent(AS2Component.class).getSslContextParameters(); if (params == null && getComponent(AS2Component.class).isUseGlobalSslContextParameters()) { params = getComponent(AS2Component.class).retrieveGlobalSslContextParameters(); } if (params != null) { setSslContext(params.createSSLContext(getCamelContext())); } } } }
AS2Endpoint
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/SplitPackagesAuditTask.java
{ "start": 14593, "end": 14936 }
interface ____ extends WorkParameters { Property<String> getProjectPath(); MapProperty<File, String> getProjectBuildDirs(); ConfigurableFileCollection getClasspath(); SetProperty<File> getSrcDirs(); SetProperty<String> getIgnoreClasses(); RegularFileProperty getMarkerFile(); } }
Parameters
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/integration/HibernateOrmIntegrationStaticDescriptor.java
{ "start": 158, "end": 1187 }
class ____ { private final String integrationName; private final Optional<HibernateOrmIntegrationStaticInitListener> initListener; private final boolean xmlMappingRequired; @RecordableConstructor public HibernateOrmIntegrationStaticDescriptor(String integrationName, Optional<HibernateOrmIntegrationStaticInitListener> initListener, boolean xmlMappingRequired) { this.integrationName = integrationName; this.initListener = initListener; this.xmlMappingRequired = xmlMappingRequired; } @Override public String toString() { return HibernateOrmIntegrationStaticDescriptor.class.getSimpleName() + " [" + integrationName + "]"; } public String getIntegrationName() { return integrationName; } public Optional<HibernateOrmIntegrationStaticInitListener> getInitListener() { return initListener; } public boolean isXmlMappingRequired() { return xmlMappingRequired; } }
HibernateOrmIntegrationStaticDescriptor
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/RouteConfigurationPreconditionTest.java
{ "start": 1195, "end": 3610 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test void testRouteConfigurationIncluded() throws Exception { Properties init = new Properties(); init.setProperty("activate", "true"); context.getPropertiesComponent().setInitialProperties(init); context.addRoutes(createRouteBuilder()); context.start(); assertCollectionSize(context.getRouteConfigurationDefinitions(), 2); assertCollectionSize(context.getRouteDefinitions(), 1); assertCollectionSize(context.getRoutes(), 1); getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:error").expectedBodiesReceived("Activated"); template.sendBody("direct:start", "Hello Activated Route Config"); assertMockEndpointsSatisfied(); } @Test void testRouteConfigurationExcluded() throws Exception { Properties init = new Properties(); init.setProperty("activate", "false"); context.getPropertiesComponent().setInitialProperties(init); context.addRoutes(createRouteBuilder()); context.start(); assertCollectionSize(context.getRouteConfigurationDefinitions(), 1); assertCollectionSize(context.getRouteDefinitions(), 1); assertCollectionSize(context.getRoutes(), 1); getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:error").expectedBodiesReceived("Default"); template.sendBody("direct:start", "Hello Not Activated Route Config"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteConfigurationBuilder() { @Override public void configuration() { from("direct:start") .throwException(new IllegalArgumentException("Foo")); routeConfiguration().precondition("{{activate}}").onException(IllegalArgumentException.class).handled(true) .transform(constant("Activated")) .to("mock:error"); routeConfiguration().onException(Exception.class).handled(true) .transform(constant("Default")) .to("mock:error"); } }; } }
RouteConfigurationPreconditionTest
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/main/java/io/quarkus/hibernate/validator/deployment/HibernateValidatorProcessor.java
{ "start": 6937, "end": 29881 }
class ____ { private static final Logger LOG = Logger.getLogger(HibernateValidatorProcessor.class); private static final String META_INF_VALIDATION_XML = "META-INF/validation.xml"; public static final String VALIDATOR_FACTORY_NAME = "quarkus-hibernate-validator-factory"; private static final DotName CDI_INSTANCE = DotName.createSimple(Instance.class); private static final DotName CONSTRAINT_VALIDATOR_FACTORY = DotName .createSimple(ConstraintValidatorFactory.class.getName()); private static final DotName MESSAGE_INTERPOLATOR = DotName.createSimple(MessageInterpolator.class.getName()); private static final DotName LOCAL_RESOLVER_WRAPPER = DotName.createSimple(LocaleResolversWrapper.class); private static final DotName LOCALE_RESOLVER = DotName.createSimple(LocaleResolver.class.getName()); private static final DotName TRAVERSABLE_RESOLVER = DotName.createSimple(TraversableResolver.class.getName()); private static final DotName PARAMETER_NAME_PROVIDER = DotName.createSimple(ParameterNameProvider.class.getName()); private static final DotName CLOCK_PROVIDER = DotName.createSimple(ClockProvider.class.getName()); private static final DotName SCRIPT_EVALUATOR_FACTORY = DotName.createSimple(ScriptEvaluatorFactory.class.getName()); private static final DotName GETTER_PROPERTY_SELECTION_STRATEGY = DotName .createSimple(GetterPropertySelectionStrategy.class.getName()); private static final DotName PROPERTY_NODE_NAME_PROVIDER = DotName .createSimple(PropertyNodeNameProvider.class.getName()); private static final DotName VALIDATOR_FACTORY_CUSTOMIZER = DotName .createSimple(ValidatorFactoryCustomizer.class.getName()); private static final DotName CONSTRAINT_VALIDATOR = DotName.createSimple(ConstraintValidator.class.getName()); private static final DotName VALUE_EXTRACTOR = DotName.createSimple(ValueExtractor.class.getName()); private static final DotName VALIDATE_ON_EXECUTION = DotName.createSimple(ValidateOnExecution.class.getName()); private static final DotName VALID = DotName.createSimple(Valid.class.getName()); private static final DotName REPEATABLE = DotName.createSimple(Repeatable.class.getName()); private static final DotName GRAALVM_FEATURE = DotName.createSimple("org.graalvm.nativeimage.hosted.Feature"); private static final Pattern BUILT_IN_CONSTRAINT_REPEATABLE_CONTAINER_PATTERN = Pattern.compile("\\$List$"); @BuildStep void feature(BuildProducer<FeatureBuildItem> features) { features.produce(new FeatureBuildItem(Feature.HIBERNATE_VALIDATOR)); } @BuildStep HotDeploymentWatchedFileBuildItem configFile() { return new HotDeploymentWatchedFileBuildItem(META_INF_VALIDATION_XML); } @BuildStep LogCleanupFilterBuildItem logCleanup() { return new LogCleanupFilterBuildItem("org.hibernate.validator.internal.util.Version", "HV000001:"); } @BuildStep(onlyIf = NativeOrNativeSourcesBuild.class) NativeImageFeatureBuildItem nativeImageFeature() { return new NativeImageFeatureBuildItem(DisableLoggingFeature.class); } @BuildStep void beanValidationAnnotations( BeanArchiveIndexBuildItem beanArchiveIndexBuildItem, CombinedIndexBuildItem combinedIndexBuildItem, Optional<AdditionalConstrainedClassesIndexBuildItem> additionalConstrainedClassesIndexBuildItem, BuildProducer<BeanValidationAnnotationsBuildItem> beanValidationAnnotations) { IndexView indexView; if (additionalConstrainedClassesIndexBuildItem.isPresent()) { // we use both indexes to support both generated beans and jars that contain no CDI beans but only Validation annotations // we also add the additional constrained classes indexView = CompositeIndex.create(beanArchiveIndexBuildItem.getIndex(), combinedIndexBuildItem.getIndex(), additionalConstrainedClassesIndexBuildItem.get().getIndex()); } else { indexView = CompositeIndex.create(beanArchiveIndexBuildItem.getIndex(), combinedIndexBuildItem.getIndex()); } Set<DotName> constraints = new HashSet<>(); Set<String> builtinConstraints = ConstraintHelper.getBuiltinConstraints(); // Collect the constraint annotations provided by Hibernate Validator and Bean Validation contributeBuiltinConstraints(builtinConstraints, constraints); // Add the constraint annotations present in the application itself for (AnnotationInstance constraint : indexView.getAnnotations(DotName.createSimple(Constraint.class.getName()))) { constraints.add(constraint.target().asClass().name()); if (constraint.target().asClass().annotationsMap().containsKey(REPEATABLE)) { for (AnnotationInstance repeatableConstraint : constraint.target().asClass().annotationsMap() .get(REPEATABLE)) { constraints.add(repeatableConstraint.value().asClass().name()); } } } Set<DotName> allConsideredAnnotations = new HashSet<>(); allConsideredAnnotations.addAll(constraints); // Also consider elements that are marked with @Valid allConsideredAnnotations.add(VALID); // Also consider elements that are marked with @ValidateOnExecution allConsideredAnnotations.add(VALIDATE_ON_EXECUTION); beanValidationAnnotations.produce(new BeanValidationAnnotationsBuildItem( VALID, constraints, allConsideredAnnotations)); } @BuildStep void configValidator( CombinedIndexBuildItem combinedIndex, List<ConfigClassBuildItem> configClasses, BeanValidationAnnotationsBuildItem beanValidationAnnotations, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, BuildProducer<GeneratedClassBuildItem> generatedClass, BuildProducer<GeneratedResourceBuildItem> generatedResource, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<StaticInitConfigBuilderBuildItem> staticInitConfigBuilder, BuildProducer<RunTimeConfigBuilderBuildItem> runTimeConfigBuilder) { Set<DotName> configMappings = new HashSet<>(); Set<DotName> configClassesToValidate = new HashSet<>(); Map<DotName, Map<DotName, ConfigClassBuildItem>> embeddingMap = new HashMap<>(); for (ConfigClassBuildItem configClass : configClasses) { for (String generatedConfigClass : configClass.getGeneratedClasses()) { DotName simple = DotName.createSimple(generatedConfigClass); configClassesToValidate.add(simple); } configClass.getConfigComponentInterfaces().stream().map(DotName::createSimple) .forEach(cm -> { configMappings.add(cm); embeddingMap.computeIfAbsent(cm, c -> new HashMap<>()) .putIfAbsent(configClass.getName(), configClass); }); } Set<DotName> constrainedConfigMappings = new HashSet<>(); Set<String> configMappingsConstraints = new HashSet<>(); for (DotName consideredAnnotation : beanValidationAnnotations.getAllAnnotations()) { Collection<AnnotationInstance> annotationInstances = combinedIndex.getIndex().getAnnotations(consideredAnnotation); if (annotationInstances.isEmpty()) { continue; } for (AnnotationInstance annotation : annotationInstances) { String builtinConstraintCandidate = BUILT_IN_CONSTRAINT_REPEATABLE_CONTAINER_PATTERN .matcher(consideredAnnotation.toString()).replaceAll(""); if (annotation.target().kind() == AnnotationTarget.Kind.METHOD) { MethodInfo methodInfo = annotation.target().asMethod(); ClassInfo declaringClass = methodInfo.declaringClass(); if (configMappings.contains(declaringClass.name())) { configMappingsConstraints.add(builtinConstraintCandidate); constrainedConfigMappings.add(declaringClass.name()); } } else if (annotation.target().kind() == AnnotationTarget.Kind.TYPE) { AnnotationTarget target = annotation.target().asType().enclosingTarget(); if (target.kind() == AnnotationTarget.Kind.METHOD) { MethodInfo methodInfo = target.asMethod(); ClassInfo declaringClass = methodInfo.declaringClass(); if (configMappings.contains(declaringClass.name())) { configMappingsConstraints.add(builtinConstraintCandidate); constrainedConfigMappings.add(declaringClass.name()); } } } else if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) { ClassInfo classInfo = annotation.target().asClass(); if (configMappings.contains(classInfo.name())) { configMappingsConstraints.add(builtinConstraintCandidate); constrainedConfigMappings.add(classInfo.name()); } } } } if (configMappingsConstraints.isEmpty()) { return; } // if in the tree of a ConfigMapping, there is one constraint, we register the whole tree // we might be able to do some more advanced surgery with Jandex evolution but for now // that's the best we can do Set<DotName> configComponentsInterfacesToRegisterForReflection = new HashSet<>(); for (DotName constrainedConfigMapping : constrainedConfigMappings) { if (!embeddingMap.containsKey(constrainedConfigMapping)) { // should never happen but let's be safe continue; } for (ConfigClassBuildItem configClass : embeddingMap.get(constrainedConfigMapping).values()) { unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(configClass.getConfigClass())); configClass.getConfigComponentInterfaces() .stream() .map(DotName::createSimple) .forEach(configComponentsInterfacesToRegisterForReflection::add); } } reflectiveClass.produce(ReflectiveClassBuildItem .builder(configComponentsInterfacesToRegisterForReflection.stream().map(DotName::toString) .toArray(String[]::new)) .reason(getClass().getName()) .methods().build()); String builderClassName = HibernateBeanValidationConfigValidator.class.getName() + "Builder"; Gizmo gizmo = Gizmo.create(new GeneratedClassGizmo2Adaptor(generatedClass, generatedResource, true)) .withDebugInfo(false) .withParameters(false); gizmo.class_(builderClassName, cc -> { cc.final_(); cc.implements_(ConfigBuilder.class); StaticFieldVar configValidator = cc.staticField("configValidator", fc -> { fc.private_(); fc.final_(); fc.setType(BeanValidationConfigValidator.class); fc.setInitializer(bc -> { LocalVar constraints = bc.localVar("constraints", bc.new_(HashSet.class)); for (String configMappingsConstraint : configMappingsConstraints) { bc.withSet(constraints).add(Const.of(configMappingsConstraint)); } LocalVar classes = bc.localVar("classes", bc.new_(HashSet.class)); for (DotName configClassToValidate : configClassesToValidate) { bc.withSet(classes).add(Const.of(classDescOf(configClassToValidate))); } bc.yield(bc.new_(ConstructorDesc.of(HibernateBeanValidationConfigValidator.class, Set.class, Set.class), constraints, classes)); }); }); cc.defaultConstructor(); cc.method("configBuilder", mc -> { mc.returning(SmallRyeConfigBuilder.class); ParamVar builder = mc.parameter("builder", SmallRyeConfigBuilder.class); mc.body(bc -> { MethodDesc withValidator = MethodDesc.of(SmallRyeConfigBuilder.class, "withValidator", SmallRyeConfigBuilder.class, ConfigValidator.class); bc.invokeVirtual(withValidator, builder, configValidator); bc.return_(builder); }); }); }); reflectiveClass.produce(ReflectiveClassBuildItem.builder(builderClassName).build()); staticInitConfigBuilder.produce(new StaticInitConfigBuilderBuildItem(builderClassName)); runTimeConfigBuilder.produce(new RunTimeConfigBuilderBuildItem(builderClassName)); } @BuildStep @Record(ExecutionTime.STATIC_INIT) void shutdownConfigValidator(HibernateValidatorRecorder hibernateValidatorRecorder, ShutdownContextBuildItem shutdownContext) { hibernateValidatorRecorder.shutdownConfigValidator(shutdownContext); } @BuildStep @Record(ExecutionTime.STATIC_INIT) void registerAdditionalBeans(HibernateValidatorRecorder hibernateValidatorRecorder, Optional<ResteasyConfigBuildItem> resteasyConfigBuildItem, BuildProducer<AdditionalBeanBuildItem> additionalBeans, BuildProducer<UnremovableBeanBuildItem> unremovableBean, BuildProducer<AutoAddScopeBuildItem> autoScopes, BuildProducer<SyntheticBeanBuildItem> syntheticBeanBuildItems, BuildProducer<ResteasyJaxrsProviderBuildItem> resteasyJaxrsProvider, Capabilities capabilities) { // The CDI interceptor which will validate the methods annotated with @MethodValidated additionalBeans.produce(new AdditionalBeanBuildItem(MethodValidationInterceptor.class)); additionalBeans.produce(new AdditionalBeanBuildItem( "io.quarkus.hibernate.validator.runtime.locale.LocaleResolversWrapper")); if (capabilities.isPresent(Capability.RESTEASY)) { // The CDI interceptor which will validate the methods annotated with @JaxrsEndPointValidated additionalBeans.produce(new AdditionalBeanBuildItem( "io.quarkus.hibernate.validator.runtime.jaxrs.JaxrsEndPointValidationInterceptor")); additionalBeans.produce(new AdditionalBeanBuildItem( "io.quarkus.hibernate.validator.runtime.locale.ResteasyClassicLocaleResolver")); syntheticBeanBuildItems.produce(SyntheticBeanBuildItem.configure(ResteasyConfigSupport.class) .scope(Singleton.class) .unremovable() .supplier(hibernateValidatorRecorder.resteasyConfigSupportSupplier( resteasyConfigBuildItem.isPresent() ? resteasyConfigBuildItem.get().isJsonDefault() : false)) .done()); resteasyJaxrsProvider.produce(new ResteasyJaxrsProviderBuildItem(ResteasyViolationExceptionMapper.class.getName())); } else if (capabilities.isPresent(Capability.RESTEASY_REACTIVE)) { // The CDI interceptor which will validate the methods annotated with @JaxrsEndPointValidated additionalBeans.produce(new AdditionalBeanBuildItem( "io.quarkus.hibernate.validator.runtime.jaxrs.ResteasyReactiveEndPointValidationInterceptor")); additionalBeans.produce(new AdditionalBeanBuildItem( "io.quarkus.hibernate.validator.runtime.locale.ResteasyReactiveLocaleResolver")); } // A constraint validator with an injection point but no scope is added as @Dependent autoScopes.produce(AutoAddScopeBuildItem.builder().implementsInterface(CONSTRAINT_VALIDATOR) .requiresContainerServices() .defaultScope(BuiltinScope.DEPENDENT).build()); // Do not remove the Bean Validation beans unremovableBean.produce(new UnremovableBeanBuildItem(new Predicate<BeanInfo>() { @Override public boolean test(BeanInfo beanInfo) { return beanInfo.hasType(CONSTRAINT_VALIDATOR) || beanInfo.hasType(CONSTRAINT_VALIDATOR_FACTORY) || beanInfo.hasType(MESSAGE_INTERPOLATOR) || beanInfo.hasType(TRAVERSABLE_RESOLVER) || beanInfo.hasType(PARAMETER_NAME_PROVIDER) || beanInfo.hasType(CLOCK_PROVIDER) || beanInfo.hasType(SCRIPT_EVALUATOR_FACTORY) || beanInfo.hasType(GETTER_PROPERTY_SELECTION_STRATEGY) || beanInfo.hasType(LOCALE_RESOLVER) || beanInfo.hasType(PROPERTY_NODE_NAME_PROVIDER) || beanInfo.hasType(VALIDATOR_FACTORY_CUSTOMIZER); } })); } @BuildStep @Record(STATIC_INIT) public void build( HibernateValidatorRecorder recorder, RecorderContext recorderContext, BeanValidationAnnotationsBuildItem beanValidationAnnotations, BuildProducer<ReflectiveFieldBuildItem> reflectiveFields, BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods, BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformers, BuildProducer<SyntheticBeanBuildItem> syntheticBeans, BeanArchiveIndexBuildItem beanArchiveIndexBuildItem, CombinedIndexBuildItem combinedIndexBuildItem, Optional<AdditionalConstrainedClassesIndexBuildItem> additionalConstrainedClassesIndexBuildItem, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, List<AdditionalJaxRsResourceMethodAnnotationsBuildItem> additionalJaxRsResourceMethodAnnotations, Optional<BeanValidationTraversableResolverBuildItem> beanValidationTraversableResolver, LocalesBuildTimeConfig localesBuildTimeConfig, HibernateValidatorBuildTimeConfig hibernateValidatorBuildTimeConfig) throws Exception { IndexView indexView; if (additionalConstrainedClassesIndexBuildItem.isPresent()) { // we use both indexes to support both generated beans and jars that contain no CDI beans but only Validation annotations // we also add the additional constrained classes indexView = CompositeIndex.create(beanArchiveIndexBuildItem.getIndex(), combinedIndexBuildItem.getIndex(), additionalConstrainedClassesIndexBuildItem.get().getIndex()); } else { indexView = CompositeIndex.create(beanArchiveIndexBuildItem.getIndex(), combinedIndexBuildItem.getIndex()); } Set<DotName> classNamesToBeValidated = new HashSet<>(); Map<DotName, Set<SimpleMethodSignatureKey>> methodsWithInheritedValidation = new HashMap<>(); Set<String> detectedBuiltinConstraints = new HashSet<>(); for (DotName consideredAnnotation : beanValidationAnnotations.getAllAnnotations()) { Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(consideredAnnotation); if (annotationInstances.isEmpty()) { continue; } // we trim the repeatable container suffix if needed String builtinConstraintCandidate = BUILT_IN_CONSTRAINT_REPEATABLE_CONTAINER_PATTERN .matcher(consideredAnnotation.toString()).replaceAll(""); if (beanValidationAnnotations.getConstraintAnnotations() .contains(DotName.createSimple(builtinConstraintCandidate))) { detectedBuiltinConstraints.add(builtinConstraintCandidate); } for (AnnotationInstance annotation : annotationInstances) { if (annotation.target().kind() == AnnotationTarget.Kind.FIELD) { contributeClass(classNamesToBeValidated, indexView, annotation.target().asField().declaringClass()); reflectiveFields.produce(new ReflectiveFieldBuildItem(getClass().getName(), annotation.target().asField())); contributeClassMarkedForCascadingValidation(classNamesToBeValidated, indexView, consideredAnnotation, annotation.target().asField().type()); } else if (annotation.target().kind() == AnnotationTarget.Kind.METHOD) { contributeClass(classNamesToBeValidated, indexView, annotation.target().asMethod().declaringClass()); // we need to register the method for reflection as it could be a getter reflectiveMethods .produce(new ReflectiveMethodBuildItem(getClass().getName(), annotation.target().asMethod())); contributeClassMarkedForCascadingValidation(classNamesToBeValidated, indexView, consideredAnnotation, annotation.target().asMethod().returnType()); contributeMethodsWithInheritedValidation(methodsWithInheritedValidation, indexView, annotation.target().asMethod()); } else if (annotation.target().kind() == AnnotationTarget.Kind.METHOD_PARAMETER) { contributeClass(classNamesToBeValidated, indexView, annotation.target().asMethodParameter().method().declaringClass()); // a getter does not have parameters so it's a pure method: no need for reflection in this case contributeClassMarkedForCascadingValidation(classNamesToBeValidated, indexView, consideredAnnotation, // FIXME this won't work in the case of synthetic parameters annotation.target().asMethodParameter().method().parameterTypes() .get(annotation.target().asMethodParameter().position())); contributeMethodsWithInheritedValidation(methodsWithInheritedValidation, indexView, annotation.target().asMethodParameter().method()); } else if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) { contributeClass(classNamesToBeValidated, indexView, annotation.target().asClass()); // no need for reflection in the case of a
HibernateValidatorProcessor
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionOnCompleteOnlyTest.java
{ "start": 1146, "end": 2707 }
class ____ extends OnCompletionTest { @Override @Test public void testSynchronizeFailure() throws Exception { // do not expect a message since we only do onCompleteOnly getMockEndpoint("mock:sync").expectedMessageCount(0); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); try { template.sendBody("direct:start", "Kaboom"); fail("Should throw exception"); } catch (CamelExecutionException e) { assertEquals("Kaboom", e.getCause().getMessage()); } assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 from("direct:start") // here we qualify onCompletion to only invoke when the // exchange completed with success // if the exchange failed this onCompletion route will NOT // be routed then .onCompletion().onCompleteOnly().to("log:sync").to("mock:sync") // must use end to denote the end of the onCompletion route .end() // here the original route contiues .process(new MyProcessor()).to("mock:result"); // END SNIPPET: e1 } }; } }
OnCompletionOnCompleteOnlyTest
java
quarkusio__quarkus
integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/config/UnknownConfigFilesTest.java
{ "start": 426, "end": 1899 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(EmptyAsset.INSTANCE, "application.properties") .addAsResource(EmptyAsset.INSTANCE, "application-prod.properties") .addAsResource(EmptyAsset.INSTANCE, "application.yaml") .addAsResource(EmptyAsset.INSTANCE, "application-test.toml")) .setLogRecordPredicate(record -> record.getLevel().intValue() >= Level.WARNING.intValue()) .assertLogRecords(logRecords -> { List<LogRecord> unknownConfigFiles = logRecords.stream() .filter(l -> l.getMessage().startsWith("Unrecognized configuration file")) .toList(); assertEquals(1, unknownConfigFiles.size()); assertTrue(unknownConfigFiles.get(0).getParameters()[0].toString().contains("application.yaml")); List<LogRecord> profiledConfigFiles = logRecords.stream() .filter(l -> l.getMessage().startsWith("Profiled configuration file")) .toList(); assertEquals(1, profiledConfigFiles.size()); assertTrue(profiledConfigFiles.get(0).getParameters()[0].toString().contains("application-test.toml")); }); @Test void unknownConfigFiles() { } }
UnknownConfigFilesTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java
{ "start": 13183, "end": 13295 }
class ____ { @Bean public String c() { return "c"; } } @Configuration public static
ImportedSelector3
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/ingest/ReservedPipelineActionTests.java
{ "start": 1113, "end": 3924 }
class ____ extends ESTestCase { private TransformState processJSON(ProjectId projectId, ReservedPipelineAction action, TransformState prevState, String json) throws Exception { try (XContentParser parser = XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, json)) { return action.transform(projectId, action.fromXContent(parser), prevState); } } public void testAddRemoveIngestPipeline() throws Exception { ProjectId projectId = randomProjectIdOrDefault(); ProjectMetadata projectMetadata = ProjectMetadata.builder(projectId).build(); TransformState prevState = new TransformState( ClusterState.builder(ClusterName.DEFAULT).putProjectMetadata(projectMetadata).build(), Collections.emptySet() ); ReservedPipelineAction action = new ReservedPipelineAction(); String emptyJSON = ""; TransformState updatedState = processJSON(projectId, action, prevState, emptyJSON); assertThat(updatedState.keys(), empty()); String json = """ { "my_ingest_pipeline": { "description": "_description", "processors": [ { "set" : { "field": "_field", "value": "_value" } } ] }, "my_ingest_pipeline_1": { "description": "_description", "processors": [ { "set" : { "field": "_field", "value": "_value" } } ] } }"""; prevState = updatedState; updatedState = processJSON(projectId, action, prevState, json); assertThat(updatedState.keys(), containsInAnyOrder("my_ingest_pipeline", "my_ingest_pipeline_1")); String halfJSON = """ { "my_ingest_pipeline_1": { "description": "_description", "processors": [ { "set" : { "field": "_field", "value": "_value" } } ] } }"""; updatedState = processJSON(projectId, action, prevState, halfJSON); assertThat(updatedState.keys(), containsInAnyOrder("my_ingest_pipeline_1")); updatedState = processJSON(projectId, action, prevState, emptyJSON); assertThat(updatedState.keys(), empty()); } }
ReservedPipelineActionTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableGroupByTest.java
{ "start": 35140, "end": 60278 }
class ____ { int source; String message; @Override public String toString() { return "Event => source: " + source + " message: " + message; } } Observable<Event> ASYNC_INFINITE_OBSERVABLE_OF_EVENT(final int numGroups, final AtomicInteger subscribeCounter, final AtomicInteger sentEventCounter) { return SYNC_INFINITE_OBSERVABLE_OF_EVENT(numGroups, subscribeCounter, sentEventCounter).subscribeOn(Schedulers.newThread()); }; Observable<Event> SYNC_INFINITE_OBSERVABLE_OF_EVENT(final int numGroups, final AtomicInteger subscribeCounter, final AtomicInteger sentEventCounter) { return Observable.unsafeCreate(new ObservableSource<Event>() { @Override public void subscribe(final Observer<? super Event> op) { Disposable d = Disposable.empty(); op.onSubscribe(d); subscribeCounter.incrementAndGet(); int i = 0; while (!d.isDisposed()) { i++; Event e = new Event(); e.source = i % numGroups; e.message = "Event-" + i; op.onNext(e); sentEventCounter.incrementAndGet(); } op.onComplete(); } }); }; @Test public void groupByOnAsynchronousSourceAcceptsMultipleSubscriptions() throws InterruptedException { // choose an asynchronous source Observable<Long> source = Observable.interval(10, TimeUnit.MILLISECONDS).take(1); // apply groupBy to the source Observable<GroupedObservable<Boolean, Long>> stream = source.groupBy(IS_EVEN); // create two observers Observer<GroupedObservable<Boolean, Long>> o1 = TestHelper.mockObserver(); Observer<GroupedObservable<Boolean, Long>> o2 = TestHelper.mockObserver(); // subscribe with the observers stream.subscribe(o1); stream.subscribe(o2); // check that subscriptions were successful verify(o1, never()).onError(Mockito.<Throwable> any()); verify(o2, never()).onError(Mockito.<Throwable> any()); } private static Function<Long, Boolean> IS_EVEN = new Function<Long, Boolean>() { @Override public Boolean apply(Long n) { return n % 2 == 0; } }; private static Function<Integer, Boolean> IS_EVEN2 = new Function<Integer, Boolean>() { @Override public Boolean apply(Integer n) { return n % 2 == 0; } }; @Test public void groupByBackpressure() throws InterruptedException { TestObserver<String> to = new TestObserver<>(); Observable.range(1, 4000) .groupBy(IS_EVEN2) .flatMap(new Function<GroupedObservable<Boolean, Integer>, Observable<String>>() { @Override public Observable<String> apply(final GroupedObservable<Boolean, Integer> g) { return g.observeOn(Schedulers.computation()).map(new Function<Integer, String>() { @Override public String apply(Integer l) { if (g.getKey()) { try { Thread.sleep(1); } catch (InterruptedException e) { } return l + " is even."; } else { return l + " is odd."; } } }); } }).subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); to.assertNoErrors(); } <T, R> Function<T, R> just(final R value) { return new Function<T, R>() { @Override public R apply(T t1) { return value; } }; } <T> Function<Integer, T> fail(T dummy) { return new Function<Integer, T>() { @Override public T apply(Integer t1) { throw new RuntimeException("Forced failure"); } }; } <T, R> Function<T, R> fail2(R dummy2) { return new Function<T, R>() { @Override public R apply(T t1) { throw new RuntimeException("Forced failure"); } }; } Function<Integer, Integer> dbl = new Function<Integer, Integer>() { @Override public Integer apply(Integer t1) { return t1 * 2; } }; Function<Integer, Integer> identity = new Function<Integer, Integer>() { @Override public Integer apply(Integer v) { return v; } }; @Test public void normalBehavior() { Observable<String> source = Observable.fromIterable(Arrays.asList( " foo", " FoO ", "baR ", "foO ", " Baz ", " qux ", " bar", " BAR ", "FOO ", "baz ", " bAZ ", " fOo " )); /* * foo FoO foO FOO fOo * baR bar BAR * Baz baz bAZ * qux * */ Function<String, String> keysel = new Function<String, String>() { @Override public String apply(String t1) { return t1.trim().toLowerCase(); } }; Function<String, String> valuesel = new Function<String, String>() { @Override public String apply(String t1) { return t1 + t1; } }; Observable<String> m = source.groupBy(keysel, valuesel) .flatMap(new Function<GroupedObservable<String, String>, Observable<String>>() { @Override public Observable<String> apply(final GroupedObservable<String, String> g) { System.out.println("-----------> NEXT: " + g.getKey()); return g.take(2).map(new Function<String, String>() { int count; @Override public String apply(String v) { System.out.println(v); return g.getKey() + "-" + count++; } }); } }); TestObserver<String> to = new TestObserver<>(); m.subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); System.out.println("ts .get " + to.values()); to.assertNoErrors(); assertEquals(to.values(), Arrays.asList("foo-0", "foo-1", "bar-0", "foo-0", "baz-0", "qux-0", "bar-1", "bar-0", "foo-1", "baz-1", "baz-0", "foo-0")); } @Test public void keySelectorThrows() { Observable<Integer> source = Observable.just(0, 1, 2, 3, 4, 5, 6); Observable<Integer> m = source.groupBy(fail(0), dbl).flatMap(FLATTEN_INTEGER); TestObserverEx<Integer> to = new TestObserverEx<>(); m.subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); assertEquals(1, to.errors().size()); to.assertNoValues(); } @Test @SuppressUndeliverable public void valueSelectorThrows() { Observable<Integer> source = Observable.just(0, 1, 2, 3, 4, 5, 6); Observable<Integer> m = source.groupBy(identity, fail(0)).flatMap(FLATTEN_INTEGER); TestObserverEx<Integer> to = new TestObserverEx<>(); m.subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); assertEquals(1, to.errors().size()); to.assertNoValues(); } @Test public void innerEscapeCompleted() { Observable<Integer> source = Observable.just(0); Observable<Integer> m = source.groupBy(identity, dbl).flatMap(FLATTEN_INTEGER); TestObserver<Object> to = new TestObserver<>(); m.subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); to.assertNoErrors(); System.out.println(to.values()); } /** * Assert we get an IllegalStateException if trying to subscribe to an inner GroupedObservable more than once. */ @Test public void exceptionIfSubscribeToChildMoreThanOnce() { Observable<Integer> source = Observable.just(0); final AtomicReference<GroupedObservable<Integer, Integer>> inner = new AtomicReference<>(); Observable<GroupedObservable<Integer, Integer>> m = source.groupBy(identity, dbl); m.subscribe(new Consumer<GroupedObservable<Integer, Integer>>() { @Override public void accept(GroupedObservable<Integer, Integer> t1) { inner.set(t1); } }); inner.get().subscribe(); Observer<Integer> o2 = TestHelper.mockObserver(); inner.get().subscribe(o2); verify(o2, never()).onComplete(); verify(o2, never()).onNext(anyInt()); verify(o2).onError(any(IllegalStateException.class)); } @Test @SuppressUndeliverable public void error2() { Observable<Integer> source = Observable.concat(Observable.just(0), Observable.<Integer> error(new TestException("Forced failure"))); Observable<Integer> m = source.groupBy(identity, dbl).flatMap(FLATTEN_INTEGER); TestObserverEx<Object> to = new TestObserverEx<>(); m.subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); assertEquals(1, to.errors().size()); to.assertValueCount(1); } @Test public void groupByBackpressure3() throws InterruptedException { TestObserver<String> to = new TestObserver<>(); Observable.range(1, 4000).groupBy(IS_EVEN2).flatMap(new Function<GroupedObservable<Boolean, Integer>, Observable<String>>() { @Override public Observable<String> apply(final GroupedObservable<Boolean, Integer> g) { return g.doOnComplete(new Action() { @Override public void run() { System.out.println("//////////////////// COMPLETED-A"); } }).observeOn(Schedulers.computation()).map(new Function<Integer, String>() { int c; @Override public String apply(Integer l) { if (g.getKey()) { if (c++ < 400) { try { Thread.sleep(1); } catch (InterruptedException e) { } } return l + " is even."; } else { return l + " is odd."; } } }).doOnComplete(new Action() { @Override public void run() { System.out.println("//////////////////// COMPLETED-B"); } }); } }).doOnEach(new Consumer<Notification<String>>() { @Override public void accept(Notification<String> t1) { System.out.println("NEXT: " + t1); } }).subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); to.assertNoErrors(); } @Test public void groupByBackpressure2() throws InterruptedException { TestObserver<String> to = new TestObserver<>(); Observable.range(1, 4000).groupBy(IS_EVEN2).flatMap(new Function<GroupedObservable<Boolean, Integer>, Observable<String>>() { @Override public Observable<String> apply(final GroupedObservable<Boolean, Integer> g) { return g.take(2).observeOn(Schedulers.computation()).map(new Function<Integer, String>() { @Override public String apply(Integer l) { if (g.getKey()) { try { Thread.sleep(1); } catch (InterruptedException e) { } return l + " is even."; } else { return l + " is odd."; } } }); } }).subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); to.assertNoErrors(); } static Function<GroupedObservable<Integer, Integer>, Observable<Integer>> FLATTEN_INTEGER = new Function<GroupedObservable<Integer, Integer>, Observable<Integer>>() { @Override public Observable<Integer> apply(GroupedObservable<Integer, Integer> t) { return t; } }; @Test public void groupByWithNullKey() { final String[] key = new String[]{"uninitialized"}; final List<String> values = new ArrayList<>(); Observable.just("a", "b", "c").groupBy(new Function<String, String>() { @Override public String apply(String value) { return null; } }).subscribe(new Consumer<GroupedObservable<String, String>>() { @Override public void accept(GroupedObservable<String, String> groupedObservable) { key[0] = groupedObservable.getKey(); groupedObservable.subscribe(new Consumer<String>() { @Override public void accept(String s) { values.add(s); } }); } }); assertNull(key[0]); assertEquals(Arrays.asList("a", "b", "c"), values); } @Test public void groupByUnsubscribe() { final Disposable upstream = mock(Disposable.class); Observable<Integer> o = Observable.unsafeCreate( new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { observer.onSubscribe(upstream); } } ); TestObserver<Object> to = new TestObserver<>(); o.groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer integer) { return null; } }).subscribe(to); to.dispose(); verify(upstream).dispose(); } @Test public void groupByShouldPropagateError() { final Throwable e = new RuntimeException("Oops"); final TestObserverEx<Integer> inner1 = new TestObserverEx<>(); final TestObserverEx<Integer> inner2 = new TestObserverEx<>(); final TestObserverEx<GroupedObservable<Integer, Integer>> outer = new TestObserverEx<>(new DefaultObserver<GroupedObservable<Integer, Integer>>() { @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(GroupedObservable<Integer, Integer> o) { if (o.getKey() == 0) { o.subscribe(inner1); } else { o.subscribe(inner2); } } }); Observable.unsafeCreate( new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); observer.onNext(0); observer.onNext(1); observer.onError(e); } } ).groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer i) { return i % 2; } }).subscribe(outer); assertEquals(Arrays.asList(e), outer.errors()); assertEquals(Arrays.asList(e), inner1.errors()); assertEquals(Arrays.asList(e), inner2.errors()); } @Test @SuppressUndeliverable public void keySelectorAndDelayError() { Observable.just(1).concatWith(Observable.<Integer>error(new TestException())) .groupBy(Functions.<Integer>identity(), true) .flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(GroupedObservable<Integer, Integer> g) throws Exception { return g; } }) .test() .assertFailure(TestException.class, 1); } @Test @SuppressUndeliverable public void keyAndValueSelectorAndDelayError() { Observable.just(1).concatWith(Observable.<Integer>error(new TestException())) .groupBy(Functions.<Integer>identity(), Functions.<Integer>identity(), true) .flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(GroupedObservable<Integer, Integer> g) throws Exception { return g; } }) .test() .assertFailure(TestException.class, 1); } @Test public void dispose() { TestHelper.checkDisposed(Observable.just(1).groupBy(Functions.justFunction(1))); Observable.just(1) .groupBy(Functions.justFunction(1)) .doOnNext(new Consumer<GroupedObservable<Integer, Integer>>() { @Override public void accept(GroupedObservable<Integer, Integer> g) throws Exception { TestHelper.checkDisposed(g); } }) .test(); } @Test public void reentrantComplete() { final PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Integer> to = new TestObserver<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { ps.onComplete(); } } }; Observable.merge(ps.groupBy(Functions.justFunction(1))) .subscribe(to); ps.onNext(1); to.assertResult(1); } @Test public void reentrantCompleteCancel() { final PublishSubject<Integer> ps = PublishSubject.create(); TestObserverEx<Integer> to = new TestObserverEx<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { ps.onComplete(); dispose(); } } }; Observable.merge(ps.groupBy(Functions.justFunction(1))) .subscribe(to); ps.onNext(1); to.assertSubscribed().assertValue(1).assertNoErrors().assertNotComplete(); } @Test public void delayErrorSimpleComplete() { Observable.just(1) .groupBy(Functions.justFunction(1), true) .flatMap(Functions.<Observable<Integer>>identity()) .test() .assertResult(1); } @Test public void cancelOverFlatmapRace() { for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { final TestObserver<Integer> to = new TestObserver<>(); final PublishSubject<Integer> ps = PublishSubject.create(); ps.groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer v) throws Throwable { return v % 10; } }) .flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(GroupedObservable<Integer, Integer> v) throws Throwable { return v; } }) .subscribe(to); Runnable r1 = new Runnable() { @Override public void run() { for (int j = 0; j < 1000; j++) { ps.onNext(j); } } }; Runnable r2 = new Runnable() { @Override public void run() { to.dispose(); } }; TestHelper.race(r1, r2); assertFalse("Round " + i, ps.hasObservers()); } } @Test public void abandonedGroupsNoDataloss() { final List<GroupedObservable<Integer, Integer>> groups = new ArrayList<>(); Observable.range(1, 1000) .groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer v) throws Throwable { return v % 10; } }) .doOnNext(new Consumer<GroupedObservable<Integer, Integer>>() { @Override public void accept(GroupedObservable<Integer, Integer> v) throws Throwable { groups.add(v); } }) .test() .assertValueCount(1000) .assertComplete() .assertNoErrors(); Observable.concat(groups) .test() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } @Test public void newGroupValueSelectorFails() { TestObserver<Object> to1 = new TestObserver<>(); final TestObserver<Object> to2 = new TestObserver<>(); Observable.just(1) .groupBy(Functions.<Integer>identity(), new Function<Integer, Object>() { @Override public Object apply(Integer v) throws Throwable { throw new TestException(); } }) .doOnNext(new Consumer<GroupedObservable<Integer, Object>>() { @Override public void accept(GroupedObservable<Integer, Object> g) throws Throwable { g.subscribe(to2); } }) .subscribe(to1); to1.assertValueCount(1) .assertError(TestException.class) .assertNotComplete(); to2.assertFailure(TestException.class); } @Test public void existingGroupValueSelectorFails() { TestObserver<Object> to1 = new TestObserver<>(); final TestObserver<Object> to2 = new TestObserver<>(); Observable.just(1, 2) .groupBy(Functions.justFunction(1), new Function<Integer, Object>() { @Override public Object apply(Integer v) throws Throwable { if (v == 2) { throw new TestException(); } return v; } }) .doOnNext(new Consumer<GroupedObservable<Integer, Object>>() { @Override public void accept(GroupedObservable<Integer, Object> g) throws Throwable { g.subscribe(to2); } }) .subscribe(to1); to1.assertValueCount(1) .assertError(TestException.class) .assertNotComplete(); to2.assertFailure(TestException.class, 1); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(o -> o.groupBy(v -> v)); } @Test public void nullKeyDisposeGroup() { Observable.just(1) .groupBy(v -> null) .flatMap(v -> v.take(1)) .test() .assertResult(1); } @Test public void groupSubscribeOnNextRace() throws Throwable { for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { BehaviorSubject<Integer> bs = BehaviorSubject.createDefault(1); CountDownLatch cdl = new CountDownLatch(1); bs.groupBy(v -> 1) .doOnNext(g -> { TestHelper.raceOther(() -> { g.test(); }, cdl); }) .test(); cdl.await(); } } @Test public void abandonedGroupDispose() { AtomicReference<Observable<Integer>> ref = new AtomicReference<>(); Observable.just(1) .groupBy(v -> 1) .doOnNext(ref::set) .test(); ref.get().take(1).test().assertResult(1); } @Test public void delayErrorCompleteMoreWorkInGroup() { PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<Integer> to = ps.groupBy(v -> 1, true) .flatMap(g -> g.doOnNext(v -> { if (v == 1) { ps.onNext(2); ps.onComplete(); } }) ) .test() ; ps.onNext(1); to.assertResult(1, 2); } }
Event
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/BaseConfiguration.java
{ "start": 1702, "end": 3107 }
class ____ { @Bean AbstractWebEndpointIntegrationTests.EndpointDelegate endpointDelegate() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader instanceof TomcatEmbeddedWebappClassLoader) { Thread.currentThread().setContextClassLoader(classLoader.getParent()); } try { return mock(AbstractWebEndpointIntegrationTests.EndpointDelegate.class); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } @Bean EndpointMediaTypes endpointMediaTypes() { List<String> mediaTypes = Arrays.asList("application/vnd.test+json", "application/json"); return new EndpointMediaTypes(mediaTypes, mediaTypes); } @Bean WebEndpointDiscoverer webEndpointDiscoverer(EndpointMediaTypes endpointMediaTypes, ApplicationContext applicationContext, ObjectProvider<PathMapper> pathMappers) { ParameterValueMapper parameterMapper = new ConversionServiceParameterValueMapper( DefaultConversionService.getSharedInstance()); return new WebEndpointDiscoverer(applicationContext, parameterMapper, endpointMediaTypes, pathMappers.orderedStream().toList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); } @Bean static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
BaseConfiguration
java
google__guava
android/guava-tests/test/com/google/common/collect/MapsTransformValuesUnmodifiableIteratorTest.java
{ "start": 1894, "end": 12666 }
class ____<K, V> extends ForwardingMap<K, V> { final Map<K, V> delegate; UnmodifiableIteratorMap(Map<K, V> delegate) { this.delegate = delegate; } @Override protected Map<K, V> delegate() { return delegate; } @Override public Set<K> keySet() { return new ForwardingSet<K>() { @Override protected Set<K> delegate() { return delegate.keySet(); } @Override public Iterator<K> iterator() { return Iterators.unmodifiableIterator(delegate.keySet().iterator()); } @Override public boolean removeAll(Collection<?> c) { return delegate.keySet().removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return delegate.keySet().retainAll(c); } }; } @Override public Collection<V> values() { return new ForwardingCollection<V>() { @Override protected Collection<V> delegate() { return delegate.values(); } @Override public Iterator<V> iterator() { return Iterators.unmodifiableIterator(delegate.values().iterator()); } @Override public boolean removeAll(Collection<?> c) { return delegate.values().removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return delegate.values().retainAll(c); } }; } @Override public Set<Entry<K, V>> entrySet() { return new ForwardingSet<Entry<K, V>>() { @Override protected Set<Entry<K, V>> delegate() { return delegate.entrySet(); } @Override public Iterator<Entry<K, V>> iterator() { return Iterators.unmodifiableIterator(delegate.entrySet().iterator()); } @Override public boolean removeAll(Collection<?> c) { return delegate.entrySet().removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return delegate.entrySet().retainAll(c); } }; } } @Override protected Map<String, String> makeEmptyMap() { Map<String, Integer> underlying = new HashMap<>(); return transformValues( new UnmodifiableIteratorMap<String, Integer>(underlying), Functions.toStringFunction()); } @Override protected Map<String, String> makePopulatedMap() { Map<String, Integer> underlying = new HashMap<>(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); return transformValues( new UnmodifiableIteratorMap<String, Integer>(underlying), Functions.toStringFunction()); } @Override protected String getKeyNotInPopulatedMap() throws UnsupportedOperationException { return "z"; } @Override protected String getValueNotInPopulatedMap() throws UnsupportedOperationException { return "26"; } /** Helper assertion comparing two maps */ private void assertMapsEqual(Map<?, ?> expected, Map<?, ?> map) { assertEquals(expected, map); assertEquals(expected.hashCode(), map.hashCode()); assertEquals(expected.entrySet(), map.entrySet()); // Assert that expectedValues > mapValues and that // mapValues > expectedValues; i.e. that expectedValues == mapValues. Collection<?> expectedValues = expected.values(); Collection<?> mapValues = map.values(); assertEquals(expectedValues.size(), mapValues.size()); assertTrue(expectedValues.containsAll(mapValues)); assertTrue(mapValues.containsAll(expectedValues)); } public void testTransformEmptyMapEquality() { Map<String, String> map = transformValues(ImmutableMap.<String, Integer>of(), Functions.toStringFunction()); assertMapsEqual(new HashMap<>(), map); } public void testTransformSingletonMapEquality() { Map<String, String> map = transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); Map<String, String> expected = ImmutableMap.of("a", "1"); assertMapsEqual(expected, map); assertEquals(expected.get("a"), map.get("a")); } public void testTransformIdentityFunctionEquality() { Map<String, Integer> underlying = ImmutableMap.of("a", 1); Map<String, Integer> map = transformValues(underlying, Functions.<Integer>identity()); assertMapsEqual(underlying, map); } public void testTransformPutEntryIsUnsupported() { Map<String, String> map = transformValues(ImmutableMap.of("a", 1), Functions.toStringFunction()); assertThrows(UnsupportedOperationException.class, () -> map.put("b", "2")); assertThrows(UnsupportedOperationException.class, () -> map.putAll(ImmutableMap.of("b", "2"))); assertThrows( UnsupportedOperationException.class, () -> map.entrySet().iterator().next().setValue("one")); } public void testTransformRemoveEntry() { Map<String, Integer> underlying = new HashMap<>(); underlying.put("a", 1); Map<String, String> map = transformValues(underlying, Functions.toStringFunction()); assertEquals("1", map.remove("a")); assertThat(map.remove("b")).isNull(); } public void testTransformEqualityOfMapsWithNullValues() { Map<String, @Nullable String> underlying = new HashMap<>(); underlying.put("a", null); underlying.put("b", ""); Map<@Nullable String, Boolean> map = transformValues( underlying, new Function<@Nullable String, Boolean>() { @Override public Boolean apply(@Nullable String from) { return from == null; } }); Map<String, Boolean> expected = ImmutableMap.of("a", true, "b", false); assertMapsEqual(expected, map); assertEquals(expected.get("a"), map.get("a")); assertEquals(expected.containsKey("a"), map.containsKey("a")); assertEquals(expected.get("b"), map.get("b")); assertEquals(expected.containsKey("b"), map.containsKey("b")); assertEquals(expected.get("c"), map.get("c")); assertEquals(expected.containsKey("c"), map.containsKey("c")); } public void testTransformReflectsUnderlyingMap() { Map<String, Integer> underlying = new HashMap<>(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); Map<String, String> map = transformValues(underlying, Functions.toStringFunction()); assertEquals(underlying.size(), map.size()); underlying.put("d", 4); assertEquals(underlying.size(), map.size()); assertEquals("4", map.get("d")); underlying.remove("c"); assertEquals(underlying.size(), map.size()); assertFalse(map.containsKey("c")); underlying.clear(); assertEquals(underlying.size(), map.size()); } public void testTransformChangesAreReflectedInUnderlyingMap() { Map<String, Integer> underlying = new LinkedHashMap<>(); underlying.put("a", 1); underlying.put("b", 2); underlying.put("c", 3); underlying.put("d", 4); underlying.put("e", 5); underlying.put("f", 6); underlying.put("g", 7); Map<String, String> map = transformValues(underlying, Functions.toStringFunction()); map.remove("a"); assertFalse(underlying.containsKey("a")); Set<String> keys = map.keySet(); keys.remove("b"); assertFalse(underlying.containsKey("b")); Iterator<String> keyIterator = keys.iterator(); keyIterator.next(); keyIterator.remove(); assertFalse(underlying.containsKey("c")); Collection<String> values = map.values(); values.remove("4"); assertFalse(underlying.containsKey("d")); Iterator<String> valueIterator = values.iterator(); valueIterator.next(); valueIterator.remove(); assertFalse(underlying.containsKey("e")); Set<Entry<String, String>> entries = map.entrySet(); Entry<String, String> firstEntry = entries.iterator().next(); entries.remove(firstEntry); assertFalse(underlying.containsKey("f")); Iterator<Entry<String, String>> entryIterator = entries.iterator(); entryIterator.next(); entryIterator.remove(); assertFalse(underlying.containsKey("g")); assertTrue(underlying.isEmpty()); assertTrue(map.isEmpty()); assertTrue(keys.isEmpty()); assertTrue(values.isEmpty()); assertTrue(entries.isEmpty()); } public void testTransformEquals() { Map<String, Integer> underlying = ImmutableMap.of("a", 0, "b", 1, "c", 2); Map<String, Integer> expected = transformValues(underlying, Functions.<Integer>identity()); assertMapsEqual(expected, expected); Map<String, Integer> equalToUnderlying = Maps.newTreeMap(); equalToUnderlying.putAll(underlying); Map<String, Integer> map = transformValues(equalToUnderlying, Functions.<Integer>identity()); assertMapsEqual(expected, map); map = transformValues( ImmutableMap.of("a", 1, "b", 2, "c", 3), new Function<Integer, Integer>() { @Override public Integer apply(Integer from) { return from - 1; } }); assertMapsEqual(expected, map); } public void testTransformEntrySetContains() { Map<@Nullable String, @Nullable Boolean> underlying = new HashMap<>(); underlying.put("a", null); underlying.put("b", true); underlying.put(null, true); Map<@Nullable String, @Nullable Boolean> map = transformValues( underlying, new Function<@Nullable Boolean, @Nullable Boolean>() { @Override public @Nullable Boolean apply(@Nullable Boolean from) { return (from == null) ? true : null; } }); Set<Entry<@Nullable String, @Nullable Boolean>> entries = map.entrySet(); assertTrue(entries.contains(immutableEntry("a", true))); assertTrue(entries.contains(Maps.<String, @Nullable Boolean>immutableEntry("b", null))); assertTrue( entries.contains(Maps.<@Nullable String, @Nullable Boolean>immutableEntry(null, null))); assertFalse(entries.contains(Maps.<String, @Nullable Boolean>immutableEntry("c", null))); assertFalse(entries.contains(Maps.<@Nullable String, Boolean>immutableEntry(null, true))); } @Override public void testKeySetRemoveAllNullFromEmpty() { try { super.testKeySetRemoveAllNullFromEmpty(); } catch (RuntimeException tolerated) { // GWT's HashMap.keySet().removeAll(null) doesn't throws NPE. } } @Override public void testEntrySetRemoveAllNullFromEmpty() { try { super.testEntrySetRemoveAllNullFromEmpty(); } catch (RuntimeException tolerated) { // GWT's HashMap.entrySet().removeAll(null) doesn't throws NPE. } } }
UnmodifiableIteratorMap
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/extension/support/TypeBasedParameterResolverTests.java
{ "start": 5774, "end": 6101 }
class ____ { void methodWithBasicTypeParameter(@TestAnnotation String string) { } void methodWithObjectParameter(Object nothing) { } void methodWithParameterizedTypeParameter(Map<String, List<Integer>> map) { } void methodWithAnotherParameterizedTypeParameter(Map<String, List<Object>> nothing) { } } }
Sample
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/RawErasureCoderFactory.java
{ "start": 1192, "end": 1841 }
interface ____ { /** * Create raw erasure encoder. * @param coderOptions the options used to create the encoder * @return raw erasure encoder */ RawErasureEncoder createEncoder(ErasureCoderOptions coderOptions); /** * Create raw erasure decoder. * @param coderOptions the options used to create the encoder * @return raw erasure decoder */ RawErasureDecoder createDecoder(ErasureCoderOptions coderOptions); /** * Get the name of the coder. * @return coder name */ String getCoderName(); /** * Get the name of its codec. * @return codec name */ String getCodecName(); }
RawErasureCoderFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/ExecuteWithTemporaryTableHelper.java
{ "start": 2771, "end": 19561 }
class ____ { private ExecuteWithTemporaryTableHelper() { } public static CacheableSqmInterpretation<InsertSelectStatement, JdbcOperationQueryMutation> createMatchingIdsIntoIdTableInsert( MultiTableSqmMutationConverter sqmConverter, Predicate suppliedPredicate, TemporaryTable idTable, JdbcParameter sessionUidParameter, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) { final TableGroup mutatingTableGroup = sqmConverter.getMutatingTableGroup(); final var mutatingEntityDescriptor = (EntityMappingType) mutatingTableGroup.getModelPart(); final NamedTableReference idTableReference = new NamedTableReference( idTable.getTableExpression(), InsertSelectStatement.DEFAULT_ALIAS ); final InsertSelectStatement idTableInsert = new InsertSelectStatement( idTableReference ); for ( int i = 0; i < idTable.getColumns().size(); i++ ) { final TemporaryTableColumn column = idTable.getColumns().get( i ); idTableInsert.addTargetColumnReferences( new ColumnReference( idTableReference, column.getColumnName(), // id columns cannot be formulas and cannot have custom read and write expressions false, null, column.getJdbcMapping() ) ); } final QuerySpec matchingIdSelection = new QuerySpec( true, 1 ); idTableInsert.setSourceSelectStatement( matchingIdSelection ); matchingIdSelection.getFromClause().addRoot( mutatingTableGroup ); mutatingEntityDescriptor.getIdentifierMapping().forEachSelectable( (selectionIndex, selection) -> { matchingIdSelection.getSelectClause().addSqlSelection( new SqlSelectionImpl( selectionIndex, sqmConverter.getSqlExpressionResolver().resolveSqlExpression( mutatingTableGroup.resolveTableReference( mutatingTableGroup.getNavigablePath(), selection.getContainingTableExpression() ), selection ) ) ); } ); final SharedSessionContractImplementor session = executionContext.getSession(); if ( idTable.getSessionUidColumn() != null ) { final int jdbcPosition = matchingIdSelection.getSelectClause().getSqlSelections().size(); matchingIdSelection.getSelectClause().addSqlSelection( new SqlSelectionImpl( jdbcPosition, sessionUidParameter ) ); } matchingIdSelection.applyPredicate( suppliedPredicate ); final var factory = session.getFactory(); final JdbcEnvironment jdbcEnvironment = factory.getJdbcServices().getJdbcEnvironment(); final LockOptions lockOptions = executionContext.getQueryOptions().getLockOptions(); final LockMode lockMode = lockOptions.getLockMode(); // Acquire a WRITE lock for the rows that are about to be modified lockOptions.setLockMode( LockMode.WRITE ); // Visit the table joins and reset the lock mode if we encounter OUTER joins that are not supported final QueryPart sourceSelectStatement = idTableInsert.getSourceSelectStatement(); if ( sourceSelectStatement != null && !jdbcEnvironment.getDialect().supportsOuterJoinForUpdate() ) { sourceSelectStatement.visitQuerySpecs( querySpec -> { querySpec.getFromClause().visitTableJoins( tableJoin -> { if ( tableJoin.isInitialized() && tableJoin.getJoinType() != SqlAstJoinType.INNER ) { lockOptions.setLockMode( lockMode ); } } ); } ); } final var jdbcInsert = jdbcEnvironment.getSqlAstTranslatorFactory() .buildMutationTranslator( factory, idTableInsert ) .translate( jdbcParameterBindings, executionContext.getQueryOptions() ); lockOptions.setLockMode( lockMode ); return new CacheableSqmInterpretation<>( idTableInsert, jdbcInsert, Map.of(), Map.of() ); } public static CacheableSqmInterpretation<InsertSelectStatement, JdbcOperationQueryMutation> createTemporaryTableInsert( InsertSelectStatement temporaryTableInsert, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) { final var factory = executionContext.getSession().getFactory(); final JdbcServices jdbcServices = factory.getJdbcServices(); final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); final LockOptions lockOptions = executionContext.getQueryOptions().getLockOptions(); final LockMode lockMode = lockOptions.getLockMode(); // Acquire a WRITE lock for the rows that are about to be modified lockOptions.setLockMode( LockMode.WRITE ); // Visit the table joins and reset the lock mode if we encounter OUTER joins that are not supported final QueryPart sourceSelectStatement = temporaryTableInsert.getSourceSelectStatement(); if ( sourceSelectStatement != null && !jdbcEnvironment.getDialect().supportsOuterJoinForUpdate() ) { sourceSelectStatement.visitQuerySpecs( querySpec -> { querySpec.getFromClause().visitTableJoins( tableJoin -> { if ( tableJoin.isInitialized() && tableJoin.getJoinType() != SqlAstJoinType.INNER ) { lockOptions.setLockMode( lockMode ); } } ); } ); } final var jdbcInsert = jdbcEnvironment.getSqlAstTranslatorFactory() .buildMutationTranslator( factory, temporaryTableInsert ) .translate( jdbcParameterBindings, executionContext.getQueryOptions() ); lockOptions.setLockMode( lockMode ); return new CacheableSqmInterpretation<>( temporaryTableInsert, jdbcInsert, Map.of(), Map.of() ); } public static int saveIntoTemporaryTable( InsertSelectStatement temporaryTableInsert, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) { final var factory = executionContext.getSession().getFactory(); final JdbcServices jdbcServices = factory.getJdbcServices(); final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); final LockOptions lockOptions = executionContext.getQueryOptions().getLockOptions(); final LockMode lockMode = lockOptions.getLockMode(); // Acquire a WRITE lock for the rows that are about to be modified lockOptions.setLockMode( LockMode.WRITE ); // Visit the table joins and reset the lock mode if we encounter OUTER joins that are not supported final QueryPart sourceSelectStatement = temporaryTableInsert.getSourceSelectStatement(); if ( sourceSelectStatement != null && !jdbcEnvironment.getDialect().supportsOuterJoinForUpdate() ) { sourceSelectStatement.visitQuerySpecs( querySpec -> { querySpec.getFromClause().visitTableJoins( tableJoin -> { if ( tableJoin.isInitialized() && tableJoin.getJoinType() != SqlAstJoinType.INNER ) { lockOptions.setLockMode( lockMode ); } } ); } ); } final var jdbcInsert = jdbcEnvironment.getSqlAstTranslatorFactory() .buildMutationTranslator( factory, temporaryTableInsert ) .translate( jdbcParameterBindings, executionContext.getQueryOptions() ); lockOptions.setLockMode( lockMode ); return saveIntoTemporaryTable( jdbcInsert, jdbcParameterBindings, executionContext ); } public static int saveIntoTemporaryTable( JdbcOperationQueryMutation jdbcInsert, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) { return executionContext.getSession().getFactory().getJdbcServices().getJdbcMutationExecutor().execute( jdbcInsert, jdbcParameterBindings, sql -> executionContext.getSession().getJdbcCoordinator() .getStatementPreparer().prepareStatement( sql ), (integer, preparedStatement) -> {}, executionContext ); } public static QuerySpec createIdTableSelectQuerySpec( TemporaryTable idTable, JdbcParameter sessionUidParameter, EntityMappingType entityDescriptor, ExecutionContext executionContext) { return createIdTableSelectQuerySpec( idTable, null, sessionUidParameter, entityDescriptor, executionContext ); } public static QuerySpec createIdTableSelectQuerySpec( TemporaryTable idTable, ModelPart fkModelPart, JdbcParameter sessionUidParameter, EntityMappingType entityDescriptor, ExecutionContext executionContext) { final QuerySpec querySpec = new QuerySpec( false ); final NamedTableReference idTableReference = new NamedTableReference( idTable.getTableExpression(), TemporaryTable.DEFAULT_ALIAS, true ); final TableGroup idTableGroup = new StandardTableGroup( true, new NavigablePath( idTableReference.getTableExpression() ), entityDescriptor, null, idTableReference, null, executionContext.getSession().getFactory() ); querySpec.getFromClause().addRoot( idTableGroup ); applyIdTableSelections( querySpec, idTableReference, idTable, fkModelPart, entityDescriptor ); applyIdTableRestrictions( querySpec, idTableReference, idTable, sessionUidParameter, executionContext ); return querySpec; } private static void applyIdTableSelections( QuerySpec querySpec, TableReference tableReference, TemporaryTable idTable, ModelPart fkModelPart, EntityMappingType entityDescriptor) { if ( fkModelPart == null ) { final int size = entityDescriptor.getIdentifierMapping().getJdbcTypeCount(); for ( int i = 0; i < size; i++ ) { final var temporaryTableColumn = idTable.getColumns().get( i ); if ( temporaryTableColumn != idTable.getSessionUidColumn() ) { querySpec.getSelectClause().addSqlSelection( new SqlSelectionImpl( i, new ColumnReference( tableReference, temporaryTableColumn.getColumnName(), false, null, temporaryTableColumn.getJdbcMapping() ) ) ); } } } else { fkModelPart.forEachSelectable( (i, selectableMapping) -> { querySpec.getSelectClause().addSqlSelection( new SqlSelectionImpl( i, new ColumnReference( tableReference, selectableMapping.getSelectionExpression(), false, null, selectableMapping.getJdbcMapping() ) ) ); } ); } } private static void applyIdTableRestrictions( QuerySpec querySpec, TableReference idTableReference, TemporaryTable idTable, JdbcParameter sessionUidParameter, ExecutionContext executionContext) { if ( idTable.getSessionUidColumn() != null ) { querySpec.applyPredicate( new ComparisonPredicate( new ColumnReference( idTableReference, idTable.getSessionUidColumn().getColumnName(), false, null, idTable.getSessionUidColumn().getJdbcMapping() ), ComparisonOperator.EQUAL, sessionUidParameter ) ); } } @Deprecated(forRemoval = true, since = "7.1") public static void performBeforeTemporaryTableUseActions( TemporaryTable temporaryTable, ExecutionContext executionContext) { performBeforeTemporaryTableUseActions( temporaryTable, executionContext.getSession().getDialect().getTemporaryTableBeforeUseAction(), executionContext ); } public static boolean performBeforeTemporaryTableUseActions( TemporaryTable temporaryTable, TemporaryTableStrategy temporaryTableStrategy, ExecutionContext executionContext) { return performBeforeTemporaryTableUseActions( temporaryTable, temporaryTableStrategy.getTemporaryTableBeforeUseAction(), executionContext ); } private static boolean performBeforeTemporaryTableUseActions( TemporaryTable temporaryTable, BeforeUseAction beforeUseAction, ExecutionContext executionContext) { final var factory = executionContext.getSession().getFactory(); final Dialect dialect = factory.getJdbcServices().getDialect(); if ( beforeUseAction == BeforeUseAction.CREATE ) { final var temporaryTableCreationWork = new TemporaryTableCreationWork( temporaryTable, factory ); final var ddlTransactionHandling = dialect.getTemporaryTableDdlTransactionHandling(); if ( ddlTransactionHandling == NONE ) { return executionContext.getSession().doReturningWork( temporaryTableCreationWork ); } else { final var isolationDelegate = executionContext.getSession().getJdbcCoordinator().getJdbcSessionOwner() .getTransactionCoordinator().createIsolationDelegate(); return isolationDelegate.delegateWork( temporaryTableCreationWork, ddlTransactionHandling == ISOLATE_AND_TRANSACT ); } } else { return false; } } public static int[] loadInsertedRowNumbers( TemporaryTable temporaryTable, Function<SharedSessionContractImplementor, String> sessionUidAccess, int rows, ExecutionContext executionContext) { final String sqlSelect = createInsertedRowNumbersSelectSql( temporaryTable, sessionUidAccess, executionContext ); return loadInsertedRowNumbers( sqlSelect, temporaryTable, sessionUidAccess, rows, executionContext ); } public static int[] loadInsertedRowNumbers( String sqlSelect, TemporaryTable temporaryTable, Function<SharedSessionContractImplementor, String> sessionUidAccess, int rows, ExecutionContext executionContext) { final TemporaryTableSessionUidColumn sessionUidColumn = temporaryTable.getSessionUidColumn(); final SharedSessionContractImplementor session = executionContext.getSession(); final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator(); PreparedStatement preparedStatement = null; try { preparedStatement = jdbcCoordinator.getStatementPreparer().prepareStatement( sqlSelect ); if ( sessionUidColumn != null ) { //noinspection unchecked sessionUidColumn.getJdbcMapping().getJdbcValueBinder().bind( preparedStatement, UUID.fromString( sessionUidAccess.apply( session ) ), 1, session ); } final ResultSet resultSet = jdbcCoordinator.getResultSetReturn().execute( preparedStatement, sqlSelect ); final int[] rowNumbers = new int[rows]; try { int rowIndex = 0; while (resultSet.next()) { rowNumbers[rowIndex++] = resultSet.getInt( 1 ); } return rowNumbers; } catch ( IndexOutOfBoundsException e ) { throw new IllegalArgumentException( "Expected " + rows + " to be inserted but found more", e ); } } catch( SQLException ex ) { throw new IllegalStateException( ex ); } finally { if ( preparedStatement != null ) { try { jdbcCoordinator.getLogicalConnection().getResourceRegistry().release( preparedStatement ); } catch( Throwable ignore ) { // ignore } jdbcCoordinator.afterStatementExecution(); } } } public static String createInsertedRowNumbersSelectSql( TemporaryTable temporaryTable, Function<SharedSessionContractImplementor, String> sessionUidAccess, ExecutionContext executionContext) { final TemporaryTableSessionUidColumn sessionUidColumn = temporaryTable.getSessionUidColumn(); final TemporaryTableColumn rowNumberColumn = temporaryTable.getColumns() .get( temporaryTable.getColumns().size() - (sessionUidColumn == null ? 1 : 2 ) ); assert rowNumberColumn != null; final SharedSessionContractImplementor session = executionContext.getSession(); final SimpleSelect simpleSelect = new SimpleSelect( session.getFactory() ) .setTableName( temporaryTable.getQualifiedTableName() ) .addColumn( rowNumberColumn.getColumnName() ); if ( sessionUidColumn != null ) { simpleSelect.addRestriction( sessionUidColumn.getColumnName() ); } return simpleSelect.toStatementString(); } public static void performAfterTemporaryTableUseActions( TemporaryTable temporaryTable, Function<SharedSessionContractImplementor, String> sessionUidAccess, AfterUseAction afterUseAction, ExecutionContext executionContext) { final var factory = executionContext.getSession().getFactory(); final Dialect dialect = factory.getJdbcServices().getDialect(); switch ( afterUseAction ) { case CLEAN: TemporaryTableHelper.cleanTemporaryTableRows( temporaryTable, dialect.getTemporaryTableExporter(), sessionUidAccess, executionContext.getSession() ); break; case DROP: final var temporaryTableDropWork = new TemporaryTableDropWork( temporaryTable, factory ); final var ddlTransactionHandling = dialect.getTemporaryTableDdlTransactionHandling(); if ( ddlTransactionHandling == NONE ) { executionContext.getSession().doWork( temporaryTableDropWork ); } else { final var isolationDelegate = executionContext.getSession().getJdbcCoordinator().getJdbcSessionOwner() .getTransactionCoordinator().createIsolationDelegate(); isolationDelegate.delegateWork( temporaryTableDropWork, ddlTransactionHandling == ISOLATE_AND_TRANSACT ); } } } }
ExecuteWithTemporaryTableHelper
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/example/test/DefaultAssertionErrorCollector_Test.java
{ "start": 1297, "end": 4015 }
class ____ { private final DefaultAssertionErrorCollector underTest = new DefaultAssertionErrorCollector(); @Test void collected_errors_should_be_decorate_with_line_numbers() { // GIVEN AssertionError error1 = expectAssertionError(() -> assertThat("foo").isEqualTo("bar")); AssertionError error2 = expectAssertionError(() -> assertThat(1).isNegative()); underTest.collectAssertionError(error1); underTest.collectAssertionError(error2); // WHEN List<AssertionError> decoratedErrors = underTest.assertionErrorsCollected(); // THEN then(decoratedErrors.get(0)).hasMessageContainingAll("at DefaultAssertionErrorCollector_Test.lambda", "(DefaultAssertionErrorCollector_Test.java:39)"); then(decoratedErrors.get(1)).hasMessageContainingAll("at DefaultAssertionErrorCollector_Test.lambda", "(DefaultAssertionErrorCollector_Test.java:40)"); } @Test void decorated_AssertionFailedError_should_keep_actual_and_expected_values_when_populated() { // GIVEN var error = expectAssertionError(() -> assertThat("foo").isEqualTo("bar")); underTest.collectAssertionError(error); // WHEN AssertionError decoratedError = underTest.assertionErrorsCollected().get(0); // THEN then(decoratedError).isInstanceOf(AssertionFailedError.class); Object actualInOriginalError = byName("actual.value").apply(error); Object actualInDecoratedError = byName("actual.value").apply(decoratedError); then(actualInDecoratedError).isSameAs(actualInOriginalError); Object expectedInOriginalError = byName("expected.value").apply(error); Object expectedInDecoratedError = byName("expected.value").apply(decoratedError); then(expectedInDecoratedError).isSameAs(expectedInOriginalError); } @Test void decorated_AssertionFailedError_should_not_have_null_actual_and_expected_values_when_not_populated() { // GIVEN AssertionError error = new AssertionFailedError("boom"); underTest.collectAssertionError(error); // WHEN AssertionError decoratedError = underTest.assertionErrorsCollected().get(0); // THEN then(decoratedError).isInstanceOf(AssertionFailedError.class) .hasMessageContainingAll(error.getMessage(), "(DefaultAssertionErrorCollector_Test.java:72)"); AssertionFailedError decoratedAssertionFailedError = (AssertionFailedError) decoratedError; then(decoratedAssertionFailedError.isActualDefined()).isFalse(); then(decoratedAssertionFailedError.isExpectedDefined()).isFalse(); } }
DefaultAssertionErrorCollector_Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/NettyShuffleEnvironmentTest.java
{ "start": 4181, "end": 19434 }
class ____ { private static final String tempDir = EnvironmentInformation.getTemporaryFileDirectory(); private static FileChannelManager fileChannelManager; @BeforeAll static void setUp() { fileChannelManager = new FileChannelManagerImpl(new String[] {tempDir}, "testing"); } @AfterAll static void shutdown() throws Exception { fileChannelManager.close(); } /** * Verifies that {@link Task#setupPartitionsAndGates(ResultPartitionWriter[], InputGate[])}} * sets up (un)bounded buffer pool instances for various types of input and output channels * working with the bare minimum of required buffers. */ @Test void testRegisterTaskWithLimitedBuffers() throws Exception { // outgoing: 1 buffer per channel + 1 extra buffer per ResultPartition // incoming: 2 exclusive buffers per channel + 1 floating buffer per single gate final int bufferCount = 18 + 10 * 2; testRegisterTaskWithLimitedBuffers(bufferCount); } /** * Verifies that {@link Task#setupPartitionsAndGates(ResultPartitionWriter[], InputGate[])}} * fails if the bare minimum of required buffers is not available (we are one buffer short). */ @Test void testRegisterTaskWithInsufficientBuffers() throws Exception { // outgoing: 1 buffer per channel + 1 extra buffer per ResultPartition // incoming: 2 exclusive buffers per channel + 1 floating buffer per single gate final int bufferCount = 10 + 10 * 2 - 1; assertThatThrownBy(() -> testRegisterTaskWithLimitedBuffers(bufferCount)) .isInstanceOf(IOException.class) .hasMessageContaining("Insufficient number of network buffers"); } @Test void testSlowIODoesNotBlockRelease() throws Exception { BlockerSync sync = new BlockerSync(); ResultPartitionManager blockingResultPartitionManager = new ResultPartitionManager() { @Override public void releasePartition(ResultPartitionID partitionId, Throwable cause) { sync.blockNonInterruptible(); super.releasePartition(partitionId, cause); } }; NettyShuffleEnvironment shuffleEnvironment = new NettyShuffleEnvironmentBuilder() .setResultPartitionManager(blockingResultPartitionManager) .setIoExecutor(Executors.newFixedThreadPool(1)) .build(); shuffleEnvironment.releasePartitionsLocally(Collections.singleton(new ResultPartitionID())); sync.awaitBlocker(); sync.releaseBlocker(); } @Test @SuppressWarnings("unchecked") void testRegisteringDebloatingMetrics() throws IOException { Map<String, Metric> metrics = new ConcurrentHashMap<>(); final TaskMetricGroup taskMetricGroup = createTaskMetricGroup(metrics); final Configuration config = new Configuration(); config.set(TaskManagerOptions.BUFFER_DEBLOAT_ENABLED, true); final NettyShuffleEnvironment shuffleEnvironment = new NettyShuffleEnvironmentBuilder() .setDebloatConfig(BufferDebloatConfiguration.fromConfiguration(config)) .build(); shuffleEnvironment.createInputGates( shuffleEnvironment.createShuffleIOOwnerContext( "test", createExecutionAttemptId(), taskMetricGroup), (dsid, id, consumer) -> {}, Arrays.asList( new InputGateDeploymentDescriptor( new IntermediateDataSetID(), ResultPartitionType.PIPELINED, 0, new ShuffleDescriptorAndIndex[] { new ShuffleDescriptorAndIndex( new NettyShuffleDescriptorBuilder().buildRemote(), 0) }), new InputGateDeploymentDescriptor( new IntermediateDataSetID(), ResultPartitionType.PIPELINED, 1, new ShuffleDescriptorAndIndex[] { new ShuffleDescriptorAndIndex( new NettyShuffleDescriptorBuilder().buildRemote(), 0) }))); for (int i = 0; i < 2; i++) { assertThat( ((Gauge<Integer>) getDebloatingMetric( metrics, i, MetricNames.DEBLOATED_BUFFER_SIZE)) .getValue()) .isEqualTo( TaskManagerOptions.STARTING_MEMORY_SEGMENT_SIZE .defaultValue() .getBytes()); assertThat( ((Gauge<Long>) getDebloatingMetric( metrics, i, MetricNames.ESTIMATED_TIME_TO_CONSUME_BUFFERS)) .getValue()) .isZero(); } } @Test void testInputChannelMetricsOnlyRegisterOnce() throws IOException { try (NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder().build()) { Map<String, Integer> metricRegisteredCounter = new HashMap<>(); InterceptingTaskMetricGroup taskMetricGroup = new InterceptingTaskMetricGroup() { @Override protected void addMetric(String name, Metric metric) { metricRegisteredCounter.compute( name, (metricName, registerCount) -> registerCount == null ? 1 : registerCount + 1); super.addMetric(name, metric); } }; ShuffleIOOwnerContext ownerContext = environment.createShuffleIOOwnerContext( "faker owner", createExecutionAttemptId(), taskMetricGroup); final int numberOfGates = 3; List<InputGateDeploymentDescriptor> gateDeploymentDescriptors = new ArrayList<>(); IntermediateDataSetID[] ids = new IntermediateDataSetID[numberOfGates]; for (int i = 0; i < numberOfGates; i++) { ids[i] = new IntermediateDataSetID(); gateDeploymentDescriptors.add( new InputGateDeploymentDescriptor( ids[i], ResultPartitionType.PIPELINED, 0, new ShuffleDescriptorAndIndex[] { new ShuffleDescriptorAndIndex( NettyShuffleDescriptorBuilder.newBuilder() .buildRemote(), 0) })); } environment.createInputGates( ownerContext, (ignore1, ignore2, ignore3) -> {}, gateDeploymentDescriptors); // all metric should only be registered once. assertThat(metricRegisteredCounter).allSatisfy((k, v) -> assertThat(v).isOne()); } } private Metric getDebloatingMetric(Map<String, Metric> metrics, int i, String metricName) { final String inputScope = "taskmanager.job.task.Shuffle.Netty.Input"; return metrics.get(inputScope + "." + i + "." + metricName); } private void testRegisterTaskWithLimitedBuffers(int bufferPoolSize) throws Exception { final NettyShuffleEnvironment network = new NettyShuffleEnvironmentBuilder().setNumNetworkBuffers(bufferPoolSize).build(); final ConnectionManager connManager = createDummyConnectionManager(); int channels = 2; int rp4Channels = 4; int floatingBuffers = network.getConfiguration().floatingNetworkBuffersPerGate(); int exclusiveBuffers = network.getConfiguration().networkBuffersPerChannel(); int expectedBuffers = channels * exclusiveBuffers + floatingBuffers; int expectedRp4Buffers = rp4Channels * exclusiveBuffers + floatingBuffers; // result partitions ResultPartition rp1 = createPartition(network, ResultPartitionType.PIPELINED, channels); ResultPartition rp2 = createPartition( network, fileChannelManager, ResultPartitionType.BLOCKING, channels); ResultPartition rp3 = createPartition(network, ResultPartitionType.PIPELINED_BOUNDED, channels); ResultPartition rp4 = createPartition(network, ResultPartitionType.PIPELINED_BOUNDED, rp4Channels); final ResultPartition[] resultPartitions = new ResultPartition[] {rp1, rp2, rp3, rp4}; // input gates SingleInputGate ig1 = createSingleInputGate(network, ResultPartitionType.PIPELINED, channels); SingleInputGate ig2 = createSingleInputGate(network, ResultPartitionType.BLOCKING, channels); SingleInputGate ig3 = createSingleInputGate(network, ResultPartitionType.PIPELINED_BOUNDED, channels); SingleInputGate ig4 = createSingleInputGate(network, ResultPartitionType.PIPELINED_BOUNDED, rp4Channels); InputChannel[] ic1 = new InputChannel[channels]; InputChannel[] ic2 = new InputChannel[channels]; InputChannel[] ic3 = new InputChannel[channels]; InputChannel[] ic4 = new InputChannel[rp4Channels]; final SingleInputGate[] inputGates = new SingleInputGate[] {ig1, ig2, ig3, ig4}; ic4[0] = createRemoteInputChannel(ig4, 0, rp1, connManager); ic4[1] = createRemoteInputChannel(ig4, 0, rp2, connManager); ic4[2] = createRemoteInputChannel(ig4, 0, rp3, connManager); ic4[3] = createRemoteInputChannel(ig4, 0, rp4, connManager); ig4.setInputChannels(ic4); ic1[0] = createRemoteInputChannel(ig1, 1, rp1, connManager); ic1[1] = createRemoteInputChannel(ig1, 1, rp4, connManager); ig1.setInputChannels(ic1); ic2[0] = createRemoteInputChannel(ig2, 1, rp2, connManager); ic2[1] = createRemoteInputChannel(ig2, 2, rp4, connManager); ig2.setInputChannels(ic2); ic3[0] = createRemoteInputChannel(ig3, 1, rp3, connManager); ic3[1] = createRemoteInputChannel(ig3, 3, rp4, connManager); ig3.setInputChannels(ic3); Task.setupPartitionsAndGates(resultPartitions, inputGates); // verify buffer pools for the result partitions assertThat(rp1.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(Integer.MAX_VALUE); assertThat(rp2.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(Integer.MAX_VALUE); assertThat(rp3.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(expectedBuffers); assertThat(rp4.getBufferPool().getMaxNumberOfMemorySegments()) .isEqualTo(expectedRp4Buffers); for (ResultPartition rp : resultPartitions) { assertThat(rp.getBufferPool().getNumberOfRequiredMemorySegments()) .isEqualTo(rp.getNumberOfSubpartitions() + 1); assertThat(rp.getBufferPool().getNumBuffers()) .isEqualTo(rp.getNumberOfSubpartitions() + 1); } // verify buffer pools for the input gates (NOTE: credit-based uses minimum required buffers // for exclusive buffers not managed by the buffer pool) assertThat(ig1.getBufferPool().getNumberOfRequiredMemorySegments()).isOne(); assertThat(ig2.getBufferPool().getNumberOfRequiredMemorySegments()).isOne(); assertThat(ig3.getBufferPool().getNumberOfRequiredMemorySegments()).isOne(); assertThat(ig4.getBufferPool().getNumberOfRequiredMemorySegments()).isOne(); assertThat(ig1.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(floatingBuffers); assertThat(ig2.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(floatingBuffers); assertThat(ig3.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(floatingBuffers); assertThat(ig4.getBufferPool().getMaxNumberOfMemorySegments()).isEqualTo(floatingBuffers); verify(ig1, times(1)).setupChannels(); verify(ig2, times(1)).setupChannels(); verify(ig3, times(1)).setupChannels(); verify(ig4, times(1)).setupChannels(); for (ResultPartition rp : resultPartitions) { rp.release(); } for (SingleInputGate ig : inputGates) { ig.close(); } network.close(); } /** * Helper to create spy of a {@link SingleInputGate} for use by a {@link Task} inside {@link * Task#setupPartitionsAndGates(ResultPartitionWriter[], InputGate[])}}. * * @param network network environment to create buffer pool factory for {@link SingleInputGate} * @param partitionType the consumed partition type * @param numberOfChannels the number of input channels * @return input gate with some fake settings */ private SingleInputGate createSingleInputGate( NettyShuffleEnvironment network, ResultPartitionType partitionType, int numberOfChannels) { return spy( new SingleInputGateBuilder() .setNumberOfChannels(numberOfChannels) .setResultPartitionType(partitionType) .setupBufferPoolFactory(network) .build()); } private static RemoteInputChannel createRemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartition resultPartition, ConnectionManager connManager) { return InputChannelBuilder.newBuilder() .setChannelIndex(channelIndex) .setPartitionId(resultPartition.getPartitionId()) .setConnectionManager(connManager) .buildRemoteChannel(inputGate); } private static TaskMetricGroup createTaskMetricGroup(Map<String, Metric> metrics) { return TaskManagerMetricGroup.createTaskManagerMetricGroup( new TestMetricRegistry(metrics), "localhost", ResourceID.generate()) .addJob(new JobID(), "jobName") .addTask(createExecutionAttemptId(), "test"); } /** The metric registry for storing the registered metrics to verify in tests. */ private static
NettyShuffleEnvironmentTest
java
apache__camel
components/camel-aws/camel-aws2-lambda/src/test/java/org/apache/camel/component/aws2/lambda/integration/Aws2LambdaBase.java
{ "start": 1379, "end": 1907 }
class ____ extends CamelTestSupport { @RegisterExtension public static AWSService service = AWSServiceFactory.createLambdaService(); @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); Lambda2Component lambdaComponent = context.getComponent("aws2-lambda", Lambda2Component.class); lambdaComponent.getConfiguration().setAwsLambdaClient(AWSSDKClientUtils.newLambdaClient()); return context; } }
Aws2LambdaBase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/instant/InstantWithNormalizedTest.java
{ "start": 3118, "end": 3442 }
class ____ { @Id long id; Instant instantInUtc; @JdbcTypeCode(TIMESTAMP) Instant instantInLocalTimeZone; @JdbcTypeCode(TIMESTAMP_WITH_TIMEZONE) Instant instantWithTimeZone; LocalDateTime localDateTime; OffsetDateTime offsetDateTime; LocalDateTime localDateTimeUtc; OffsetDateTime offsetDateTimeUtc; } }
Instants
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4087PercentEncodedFileUrlTest.java
{ "start": 1040, "end": 1904 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that deployment to a file:// repository decodes percent-encoded characters. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4087"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng4087"); verifier.filterFile("pom-template.xml", "pom.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFileNotPresent("target/%72%65%70%6F"); verifier.verifyFilePresent("target/repo"); } }
MavenITmng4087PercentEncodedFileUrlTest
java
apache__hadoop
hadoop-tools/hadoop-aliyun/src/main/java/org/apache/hadoop/fs/aliyun/oss/AliyunOSSInputStream.java
{ "start": 1542, "end": 9190 }
class ____ extends FSInputStream { public static final Logger LOG = LoggerFactory.getLogger(AliyunOSSInputStream.class); private final long downloadPartSize; private AliyunOSSFileSystemStore store; private final String key; private Statistics statistics; private boolean closed; private long contentLength; private long position; private long partRemaining; private byte[] buffer; private int maxReadAheadPartNumber; private long expectNextPos; private long lastByteStart; private ExecutorService readAheadExecutorService; private Queue<ReadBuffer> readBufferQueue = new ArrayDeque<>(); public AliyunOSSInputStream(Configuration conf, ExecutorService readAheadExecutorService, int maxReadAheadPartNumber, AliyunOSSFileSystemStore store, String key, Long contentLength, Statistics statistics) throws IOException { this.readAheadExecutorService = MoreExecutors.listeningDecorator(readAheadExecutorService); this.store = store; this.key = key; this.statistics = statistics; this.contentLength = contentLength; downloadPartSize = conf.getLong(MULTIPART_DOWNLOAD_SIZE_KEY, MULTIPART_DOWNLOAD_SIZE_DEFAULT); this.maxReadAheadPartNumber = maxReadAheadPartNumber; this.expectNextPos = 0; this.lastByteStart = -1; reopen(0); closed = false; } /** * Reopen the wrapped stream at give position, by seeking for * data of a part length from object content stream. * * @param pos position from start of a file * @throws IOException if failed to reopen */ private synchronized void reopen(long pos) throws IOException { long partSize; if (pos < 0) { throw new EOFException("Cannot seek at negative position:" + pos); } else if (pos > contentLength) { throw new EOFException("Cannot seek after EOF, contentLength:" + contentLength + " position:" + pos); } else if (pos + downloadPartSize > contentLength) { partSize = contentLength - pos; } else { partSize = downloadPartSize; } if (this.buffer != null) { if (LOG.isDebugEnabled()) { LOG.debug("Aborting old stream to open at pos " + pos); } this.buffer = null; } boolean isRandomIO = true; if (pos == this.expectNextPos) { isRandomIO = false; } else { //new seek, remove cache buffers if its byteStart is not equal to pos while (readBufferQueue.size() != 0) { if (readBufferQueue.element().getByteStart() != pos) { readBufferQueue.poll(); } else { break; } } } this.expectNextPos = pos + partSize; int currentSize = readBufferQueue.size(); if (currentSize == 0) { //init lastByteStart to pos - partSize, used by for loop below lastByteStart = pos - partSize; } else { ReadBuffer[] readBuffers = readBufferQueue.toArray( new ReadBuffer[currentSize]); lastByteStart = readBuffers[currentSize - 1].getByteStart(); } int maxLen = this.maxReadAheadPartNumber - currentSize; for (int i = 0; i < maxLen && i < (currentSize + 1) * 2; i++) { if (lastByteStart + partSize * (i + 1) > contentLength) { break; } long byteStart = lastByteStart + partSize * (i + 1); long byteEnd = byteStart + partSize -1; if (byteEnd >= contentLength) { byteEnd = contentLength - 1; } ReadBuffer readBuffer = new ReadBuffer(byteStart, byteEnd); if (readBuffer.getBuffer().length == 0) { //EOF readBuffer.setStatus(ReadBuffer.STATUS.SUCCESS); } else { this.readAheadExecutorService.execute( new AliyunOSSFileReaderTask(key, store, readBuffer)); } readBufferQueue.add(readBuffer); if (isRandomIO) { break; } } ReadBuffer readBuffer = readBufferQueue.poll(); readBuffer.lock(); try { readBuffer.await(ReadBuffer.STATUS.INIT); if (readBuffer.getStatus() == ReadBuffer.STATUS.ERROR) { this.buffer = null; } else { this.buffer = readBuffer.getBuffer(); } } catch (InterruptedException e) { LOG.warn("interrupted when wait a read buffer"); } finally { readBuffer.unlock(); } if (this.buffer == null) { throw new IOException("Null IO stream"); } position = pos; partRemaining = partSize; } @Override public synchronized int read() throws IOException { checkNotClosed(); if (partRemaining <= 0 && position < contentLength) { reopen(position); } int byteRead = -1; if (partRemaining != 0) { byteRead = this.buffer[this.buffer.length - (int)partRemaining] & 0xFF; } if (byteRead >= 0) { position++; partRemaining--; } if (statistics != null && byteRead >= 0) { statistics.incrementBytesRead(byteRead); } return byteRead; } /** * Verify that the input stream is open. Non blocking; this gives * the last state of the volatile {@link #closed} field. * * @throws IOException if the connection is closed. */ private void checkNotClosed() throws IOException { if (closed) { throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED); } } @Override public synchronized int read(byte[] buf, int off, int len) throws IOException { checkNotClosed(); if (buf == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > buf.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } int bytesRead = 0; // Not EOF, and read not done while (position < contentLength && bytesRead < len) { if (partRemaining == 0) { reopen(position); } int bytes = 0; for (int i = this.buffer.length - (int)partRemaining; i < this.buffer.length; i++) { buf[off + bytesRead] = this.buffer[i]; bytes++; bytesRead++; if (off + bytesRead >= len) { break; } } if (bytes > 0) { position += bytes; partRemaining -= bytes; } else if (partRemaining != 0) { throw new IOException("Failed to read from stream. Remaining:" + partRemaining); } } if (statistics != null && bytesRead > 0) { statistics.incrementBytesRead(bytesRead); } // Read nothing, but attempt to read something if (bytesRead == 0 && len > 0) { return -1; } else { return bytesRead; } } @Override public synchronized void close() throws IOException { if (closed) { return; } closed = true; this.buffer = null; } @Override public synchronized int available() throws IOException { checkNotClosed(); long remaining = contentLength - position; if (remaining > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int)remaining; } @Override public synchronized void seek(long pos) throws IOException { checkNotClosed(); if (position == pos) { return; } else if (pos > position && pos < position + partRemaining) { long len = pos - position; position = pos; partRemaining -= len; } else { reopen(pos); } } @Override public synchronized long getPos() throws IOException { checkNotClosed(); return position; } @Override public boolean seekToNewSource(long targetPos) throws IOException { checkNotClosed(); return false; } public long getExpectNextPos() { return this.expectNextPos; } }
AliyunOSSInputStream
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/utils/ByteBufferOutputStream.java
{ "start": 1421, "end": 1715 }
class ____ used for the second reason and unexpected buffer expansion happens. * So, it's best to assume that buffer expansion can always happen. An improvement would be to create a separate class * that throws an error if buffer expansion is required to avoid the issue altogether. */ public
is
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/proxy/Enhancer.java
{ "start": 30283, "end": 30999 }
class ____ * <i>not</i> implement the {@link Factory} interface. * <p> * Note that this method only registers the callbacks on the current thread. * If you want to register callbacks for instances created by multiple threads, * use {@link #registerStaticCallbacks}. * <p> * The registered callbacks are overwritten and subsequently cleared * when calling any of the <code>create</code> methods (such as * {@link #create}), or any {@link Factory} <code>newInstance</code> method. * Otherwise they are <i>not</i> cleared, and you should be careful to set them * back to <code>null</code> after creating new instances via reflection if * memory leakage is a concern. * @param generatedClass a
does
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/extensions/ClassicDelegationTokenManager.java
{ "start": 2067, "end": 7372 }
class ____ implements CustomDelegationTokenManager { private static final Logger LOG = LoggerFactory.getLogger( ClassicDelegationTokenManager.class); /** * Classname. */ public static final String NAME = "org.apache.hadoop.fs.azurebfs.extensions.ClassicDelegationTokenManager"; /** * If this the DT is unbound, this is used for the service kind. */ public static final String UNSET = "abfs://user@unset.dfs.core.windows.net/"; /** * The URI used when creating a token for an unset binding. */ public static final URI UNSET_URI = newURI(UNSET); private URI fsURI; private boolean initialized; private boolean closed; private int renewals; private int cancellations; private int issued; private Text kind; private UserGroupInformation owner; private String canonicalServiceName; /** * Instantiate. */ public ClassicDelegationTokenManager() { } @Override public void initialize(final Configuration configuration) throws IOException { initialized = true; owner = UserGroupInformation.getCurrentUser(); LOG.info("Creating Stub DT manager for {}", owner.getUserName()); } public void close() { closed = true; } @Override public Token<DelegationTokenIdentifier> getDelegationToken(final String renewer) throws IOException { // guarantees issued issued++; URI uri = fsURI != null ? fsURI : UNSET_URI; Text renewerT = new Text(renewer != null ? renewer : ""); Token t = createToken(issued, uri, new Text(owner.getUserName()), renewerT); if (kind != null) { t.setKind(kind); } t.setService(createServiceText()); LOG.info("Created token {}", t); return t; } public Text createServiceText() { return new Text(fsURI != null ? fsURI.toString() : UNSET); } /** * Create a token. * * @param sequenceNumber sequence number. * @param uri FS URI * @param owner FS owner * @param renewer renewer * @return a token. */ public static Token<DelegationTokenIdentifier> createToken( final int sequenceNumber, final URI uri, final Text owner, final Text renewer) { StubAbfsTokenIdentifier id = new StubAbfsTokenIdentifier(uri, owner, renewer); id.setSequenceNumber(sequenceNumber); Token<DelegationTokenIdentifier> token = new Token( id, new TokenSecretManager()); return token; } @Override public long renewDelegationToken(final Token<?> token) throws IOException { renewals++; decodeIdentifier(token); return 0; } @Override public void cancelDelegationToken(final Token<?> token) throws IOException { cancellations++; decodeIdentifier(token); } protected void innerBind(final URI uri, final Configuration conf) throws IOException { Preconditions.checkState(initialized, "Not initialized"); Preconditions.checkState(fsURI == null, "already bound"); fsURI = uri; canonicalServiceName = uri.toString(); LOG.info("Bound to {}", fsURI); } public String getCanonicalServiceName() { return canonicalServiceName; } public void setCanonicalServiceName(final String canonicalServiceName) { this.canonicalServiceName = canonicalServiceName; } public URI getFsURI() { return fsURI; } public boolean isInitialized() { return initialized; } public boolean isBound() { return fsURI != null; } public boolean isClosed() { return closed; } public int getRenewals() { return renewals; } public int getCancellations() { return cancellations; } public int getIssued() { return issued; } public Text getKind() { return kind; } public void setKind(final Text kind) { this.kind = kind; } @Override public String toString() { final StringBuilder sb = new StringBuilder( "StubDelegationTokenManager{"); sb.append("fsURI=").append(fsURI); sb.append(", initialized=").append(initialized); sb.append(", closed=").append(closed); sb.append(", renewals=").append(renewals); sb.append(", cancellations=").append(cancellations); sb.append(", issued=").append(issued); sb.append('}'); return sb.toString(); } /** * Patch a configuration to declare this the DT provider for a filesystem * built off the given configuration. * The ABFS Filesystem still needs to come up with security enabled. * @param conf configuration. * @return the patched configuration. */ public static Configuration useClassicDTManager(Configuration conf) { conf.setBoolean(FS_AZURE_ENABLE_DELEGATION_TOKEN, true); conf.set(FS_AZURE_DELEGATION_TOKEN_PROVIDER_TYPE, ClassicDelegationTokenManager.NAME); return conf; } /** * Get the password to use in secret managers. * This is a constant; its just recalculated every time to stop findbugs * highlighting security risks of shared mutable byte arrays. * @return a password. */ private static byte[] getSecretManagerPassword() { return "non-password".getBytes(StandardCharsets.UTF_8); } /** * The secret manager always uses the same secret; the * factory for new identifiers is that of the token manager. */ protected static
ClassicDelegationTokenManager
java
greenrobot__greendao
DaoCore/src/main/java/org/greenrobot/greendao/query/DeleteQuery.java
{ "start": 1071, "end": 3513 }
class ____<T2> extends AbstractQueryData<T2, DeleteQuery<T2>> { private QueryData(AbstractDao<T2, ?> dao, String sql, String[] initialValues) { super(dao, sql, initialValues); } @Override protected DeleteQuery<T2> createQuery() { return new DeleteQuery<T2>(this, dao, sql, initialValues.clone()); } } static <T2> DeleteQuery<T2> create(AbstractDao<T2, ?> dao, String sql, Object[] initialValues) { QueryData<T2> queryData = new QueryData<T2>(dao, sql, toStringArray(initialValues)); return queryData.forCurrentThread(); } private final QueryData<T> queryData; private DeleteQuery(QueryData<T> queryData, AbstractDao<T, ?> dao, String sql, String[] initialValues) { super(dao, sql, initialValues); this.queryData = queryData; } public DeleteQuery<T> forCurrentThread() { return queryData.forCurrentThread(this); } /** * Deletes all matching entities without detaching them from the identity scope (aka session/cache). Note that this * method may lead to stale entity objects in the session cache. Stale entities may be returned when loaded by * their * primary key, but not using queries. */ public void executeDeleteWithoutDetachingEntities() { checkThread(); Database db = dao.getDatabase(); if (db.isDbLockedByCurrentThread()) { dao.getDatabase().execSQL(sql, parameters); } else { // Do TX to acquire a connection before locking this to avoid deadlocks // Locking order as described in AbstractDao db.beginTransaction(); try { dao.getDatabase().execSQL(sql, parameters); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } // copy setParameter methods to allow easy chaining @Override public DeleteQuery<T> setParameter(int index, Object parameter) { return (DeleteQuery<T>) super.setParameter(index, parameter); } @Override public DeleteQuery<T> setParameter(int index, Date parameter) { return (DeleteQuery<T>) super.setParameter(index, parameter); } @Override public DeleteQuery<T> setParameter(int index, Boolean parameter) { return (DeleteQuery<T>) super.setParameter(index, parameter); } }
QueryData
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestOldCombinerGrouping.java
{ "start": 1700, "end": 1826 }
class ____ { private static File testRootDir = GenericTestUtils.getRandomizedTestDir(); public static
TestOldCombinerGrouping
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/support/ShortcutConfigurableTests.java
{ "start": 1534, "end": 8924 }
class ____ { @Autowired BeanFactory beanFactory; @Autowired ConfigurableEnvironment env; private SpelExpressionParser parser; @Test public void testNormalizeDefaultTypeWithSpelAssignmentAndInvalidInputFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("bean", "#{ @myMap['my.flag'] = true}"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class); } @Test public void testNormalizeDefaultTypeWithSpelAndInvalidInputFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("bean", "#{T(java.lang.Runtime).getRuntime().exec(\"touch /tmp/x\")}"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class); } @Test public void testNormalizeDefaultTypeWithSpelSystemPropertiesFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("bean", "#{ @systemProperties['user.home'] ?: 'n.a' }"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class); } @Test public void testNormalizeDefaultTypeWithSpelEnvironmentVariablesFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("bean", "#{ @systemEnvironment['user.home'] ?: 'n.a' }"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class); } @Test public void testNormalizeDefaultTypeWithSpelAndInvalidPropertyReferenceFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("barproperty", "#{@bar.property}"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class) .hasMessageContaining("Property or field 'property' cannot be found"); } @Test public void testNormalizeDefaultTypeWithSpelAndInvalidMethodReferenceFails() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("barmethod", "#{@bar.myMethod}"); args.put("arg1", "val1"); assertThatThrownBy(() -> { ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); }).isInstanceOf(SpelEvaluationException.class); } @Test public void testNormalizeDefaultTypeWithSpel() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("bean", "arg1"); } }; Map<String, String> args = new HashMap<>(); args.put("bean", "#{@foo}"); args.put("arg1", "val1"); Map<String, Object> map = ShortcutType.DEFAULT.normalize(args, shortcutConfigurable, parser, this.beanFactory); assertThat(map).isNotNull().containsEntry("bean", 42).containsEntry("arg1", "val1"); } @Test @SuppressWarnings("unchecked") public void testNormalizeGatherListTypeWithSpel() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("values"); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST; } }; Map<String, String> args = new HashMap<>(); args.put("1", "#{@foo}"); args.put("2", "val1"); args.put("3", "val2"); Map<String, Object> map = ShortcutType.GATHER_LIST.normalize(args, shortcutConfigurable, parser, this.beanFactory); assertThat(map).isNotNull().containsKey("values"); assertThat((List) map.get("values")).containsExactly(42, "val1", "val2"); } @Test public void testNormalizeGatherListTailFlagFlagExists() { assertListTailFlag(true); } @Test public void testNormalizeGatherListTailFlagFlagMissing() { assertListTailFlag(false); } @SuppressWarnings("unchecked") private void assertListTailFlag(boolean hasTailFlag) { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("values", "flag"); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST_TAIL_FLAG; } }; Map<String, String> args = new HashMap<>(); args.put("1", "val0"); args.put("2", "val1"); args.put("3", "val2"); if (hasTailFlag) { args.put("4", "false"); } Map<String, Object> map = ShortcutType.GATHER_LIST_TAIL_FLAG.normalize(args, shortcutConfigurable, parser, this.beanFactory); assertThat(map).isNotNull().containsKey("values"); assertThat((List) map.get("values")).containsExactly("val0", "val1", "val2"); if (hasTailFlag) { assertThat(map.get("flag")).isEqualTo("false"); } else { assertThat(map).doesNotContainKeys("flag"); } } @Test public void testNormalizeGatherListTailFlagFlagIsNull() { parser = new SpelExpressionParser(); ShortcutConfigurable shortcutConfigurable = new ShortcutConfigurable() { @Override public List<String> shortcutFieldOrder() { return Arrays.asList("values", "flag"); } @Override public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST_TAIL_FLAG; } }; Map<String, String> args = new HashMap<>(); args.put("1", "val0"); args.put("2", "val1"); args.put("3", "val2"); args.put("4", null); Map<String, Object> map = ShortcutType.GATHER_LIST_TAIL_FLAG.normalize(args, shortcutConfigurable, parser, this.beanFactory); assertThat(map).isNotNull().containsKey("values"); assertThat((List) map.get("values")).containsExactly("val0", "val1", "val2"); assertThat(map.get("flag")).isNull(); } @SpringBootConfiguration protected static
ShortcutConfigurableTests
java
hibernate__hibernate-orm
tooling/hibernate-ant/src/main/java/org/hibernate/tool/enhance/EnhancementTask.java
{ "start": 2749, "end": 11751 }
class ____ extends Task { private List<FileSet> filesets = new ArrayList<FileSet>(); private String base; private String dir; private boolean failOnError = true; private boolean enableLazyInitialization = true; private boolean enableDirtyTracking = true; private boolean enableAssociationManagement = false; private boolean enableExtendedEnhancement = false; private List<File> sourceSet = new ArrayList<>(); public void addFileset(FileSet set) { this.filesets.add( set ); } public void setBase(String base) { this.base = base; } public void setDir(String dir) { this.dir = dir; } public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } public void setEnableLazyInitialization(boolean enableLazyInitialization) { this.enableLazyInitialization = enableLazyInitialization; } public void setEnableDirtyTracking(boolean enableDirtyTracking) { this.enableDirtyTracking = enableDirtyTracking; } public void setEnableAssociationManagement(boolean enableAssociationManagement) { this.enableAssociationManagement = enableAssociationManagement; } public void setEnableExtendedEnhancement(boolean enableExtendedEnhancement) { this.enableExtendedEnhancement = enableExtendedEnhancement; } private boolean shouldApply() { return enableLazyInitialization || enableDirtyTracking || enableAssociationManagement || enableExtendedEnhancement; } @Override public void execute() throws BuildException { if ( !enableLazyInitialization ) { log( "The 'enableLazyInitialization' configuration is deprecated and will be removed. Set the value to 'true' to get rid of this warning", Project.MSG_WARN ); } if ( !enableDirtyTracking ) { log( "The 'enableDirtyTracking' configuration is deprecated and will be removed. Set the value to 'true' to get rid of this warning", Project.MSG_WARN ); } if ( !shouldApply() ) { log( "Skipping Hibernate bytecode enhancement task execution since no feature is enabled", Project.MSG_WARN ); return; } if ( base == null ) { throw new BuildException( "The enhancement directory 'base' should be present" ); } if ( !filesets.isEmpty() && dir != null ) { throw new BuildException( "Please remove the enhancement directory 'dir' if 'fileset' is using" ); } if ( dir == null ) { for ( FileSet fileSet : filesets ) { Iterator<Resource> it = fileSet.iterator(); while ( it.hasNext() ) { File file = new File( it.next().toString() ); if ( file.isFile() ) { sourceSet.add( file ); } } } if ( sourceSet.isEmpty() ) { log( "Skipping Hibernate enhancement task execution since there are no classes to enhance in the filesets " + filesets, Project.MSG_INFO ); return; } log( "Starting Hibernate enhancement task for classes in filesets " + filesets, Project.MSG_INFO ); } else { if ( !dir.startsWith( base ) ) { throw new BuildException( "The enhancement directory 'dir' (" + dir + ") is no subdirectory of 'base' (" + base + ")" ); } // Perform a depth first search for sourceSet File root = new File( dir ); if ( !root.exists() ) { log( "Skipping Hibernate enhancement task execution since there is no classes dir " + dir, Project.MSG_INFO ); return; } walkDir( root ); if ( sourceSet.isEmpty() ) { log( "Skipping Hibernate enhancement task execution since there are no classes to enhance on " + dir, Project.MSG_INFO ); return; } log( "Starting Hibernate enhancement task for classes on " + dir, Project.MSG_INFO ); } ClassLoader classLoader = toClassLoader( Collections.singletonList( new File( base ) ) ); EnhancementContext enhancementContext = new DefaultEnhancementContext() { @Override public ClassLoader getLoadingClassLoader() { return classLoader; } @Override public boolean doBiDirectionalAssociationManagement(UnloadedField field) { return enableAssociationManagement; } @Override public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) { return enableDirtyTracking; } @Override public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) { return enableLazyInitialization; } @Override public boolean isLazyLoadable(UnloadedField field) { return enableLazyInitialization; } @Override public boolean doExtendedEnhancement(UnloadedClass classDescriptor) { return enableExtendedEnhancement; } }; if ( enableExtendedEnhancement ) { DEPRECATION_LOGGER.deprecatedSettingForRemoval("extended enhancement", "false"); } if ( enableAssociationManagement ) { DEPRECATION_LOGGER.deprecatedSettingForRemoval( "management of bidirectional association persistent attributes", "false" ); } final BytecodeProvider bytecodeProvider = buildDefaultBytecodeProvider(); try { Enhancer enhancer = bytecodeProvider.getEnhancer( enhancementContext ); for ( File file : sourceSet ) { discoverTypes( file, enhancer ); log( "Successfully discovered types for class [" + file + "]", Project.MSG_INFO ); } for ( File file : sourceSet ) { byte[] enhancedBytecode = doEnhancement( file, enhancer ); if ( enhancedBytecode == null ) { continue; } writeOutEnhancedClass( enhancedBytecode, file ); log( "Successfully enhanced class [" + file + "]", Project.MSG_INFO ); } } finally { bytecodeProvider.resetCaches(); } } private ClassLoader toClassLoader(List<File> runtimeClasspath) throws BuildException { List<URL> urls = new ArrayList<>(); for ( File file : runtimeClasspath ) { try { urls.add( file.toURI().toURL() ); log( "Adding classpath entry for classes root " + file.getAbsolutePath(), Project.MSG_DEBUG ); } catch ( MalformedURLException e ) { String msg = "Unable to resolve classpath entry to URL: " + file.getAbsolutePath(); if ( failOnError ) { throw new BuildException( msg, e ); } log( msg, Project.MSG_WARN ); } } return new URLClassLoader( urls.toArray( new URL[urls.size()] ), Enhancer.class.getClassLoader() ); } private void discoverTypes(File javaClassFile, Enhancer enhancer) throws BuildException { try { String className = javaClassFile.getAbsolutePath().substring( base.length() + 1, javaClassFile.getAbsolutePath().length() - ".class".length() ).replace( File.separatorChar, '.' ); ByteArrayOutputStream originalBytes = new ByteArrayOutputStream(); FileInputStream fileInputStream = new FileInputStream( javaClassFile ); try { byte[] buffer = new byte[1024]; int length; while ( ( length = fileInputStream.read( buffer ) ) != -1 ) { originalBytes.write( buffer, 0, length ); } } finally { fileInputStream.close(); } enhancer.discoverTypes( className, originalBytes.toByteArray() ); } catch (Exception e) { String msg = "Unable to discover types for class: " + javaClassFile.getName(); if ( failOnError ) { throw new BuildException( msg, e ); } log( msg, e, Project.MSG_WARN ); } } private byte[] doEnhancement(File javaClassFile, Enhancer enhancer) throws BuildException { try { String className = javaClassFile.getAbsolutePath().substring( base.length() + 1, javaClassFile.getAbsolutePath().length() - ".class".length() ).replace( File.separatorChar, '.' ); ByteArrayOutputStream originalBytes = new ByteArrayOutputStream(); FileInputStream fileInputStream = new FileInputStream( javaClassFile ); try { byte[] buffer = new byte[1024]; int length; while ( ( length = fileInputStream.read( buffer ) ) != -1 ) { originalBytes.write( buffer, 0, length ); } } finally { fileInputStream.close(); } return enhancer.enhance( className, originalBytes.toByteArray() ); } catch (Exception e) { String msg = "Unable to enhance class: " + javaClassFile.getName(); if ( failOnError ) { throw new BuildException( msg, e ); } log( msg, e, Project.MSG_WARN ); return null; } } /** * Expects a directory. */ private void walkDir(File dir) { walkDir( dir, new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith( ".class" ); } }, new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } } ); } private void walkDir(File dir, FileFilter classesFilter, FileFilter dirFilter) { File[] dirs = dir.listFiles( dirFilter ); if ( dirs != null ) { for ( File dir1 : dirs ) { walkDir( dir1, classesFilter, dirFilter ); } } File[] files = dir.listFiles( classesFilter ); if ( files != null ) { Collections.addAll( sourceSet, files ); } } private void writeOutEnhancedClass(byte[] enhancedBytecode, File file) throws BuildException { try { if ( file.delete() ) { if ( !file.createNewFile() ) { log( "Unable to recreate
EnhancementTask
java
spring-projects__spring-security
docs/src/test/java/org/springframework/security/docs/features/authentication/authenticationpasswordstoragedepgettingstarted/WithDefaultPasswordEncoderUsage.java
{ "start": 349, "end": 1192 }
class ____ { public UserDetails createSingleUser() { // tag::createSingleUser[] UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("user") .build(); System.out.println(user.getPassword()); // {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG // end::createSingleUser[] return user; } public List<UserDetails> createMultipleUsers() { // tag::createMultipleUsers[] UserBuilder users = User.withDefaultPasswordEncoder(); UserDetails user = users .username("user") .password("password") .roles("USER") .build(); UserDetails admin = users .username("admin") .password("password") .roles("USER","ADMIN") .build(); // end::createMultipleUsers[] return List.of(user, admin); } }
WithDefaultPasswordEncoderUsage
java
quarkusio__quarkus
integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/config/RecorderRuntimeConfigTest.java
{ "start": 603, "end": 2188 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)); @Inject SmallRyeConfig config; @Inject TestMappingRunTime mappingRunTime; @Test void runtimeConfig() { // Make sure we get the recorded property with the highest priority (the profile property with test) assertEquals("from-application", config.getConfigValue("recorded.property").getValue()); assertEquals("from-application", config.getConfigValue("recorded.profiled.property").getValue()); assertEquals("from-application", config.getConfigValue("quarkus.mapping.rt.record-profiled").getValue()); assertTrue(mappingRunTime.recordProfiled().isPresent()); assertEquals("from-application", mappingRunTime.recordProfiled().get()); // Make sure that when we merge all the defaults, we override the non-profiled name Optional<ConfigSource> configSource = config.getConfigSource("Runtime Values"); assertTrue(configSource.isPresent()); ConfigSource runtimeValues = configSource.get(); assertEquals("from-application", runtimeValues.getValue("%test.recorded.profiled.property")); assertEquals("recorded", runtimeValues.getValue("recorded.profiled.property")); assertEquals("from-application", runtimeValues.getValue("%test.quarkus.mapping.rt.record-profiled")); assertEquals("recorded", runtimeValues.getValue("quarkus.mapping.rt.record-profiled")); } }
RecorderRuntimeConfigTest
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/exceptions/NoSuchMessageException.java
{ "start": 792, "end": 1054 }
class ____ extends BeanContextException { /** * Default constructor. * @param code The message code */ public NoSuchMessageException(String code) { super("No message exists for the given code: " + code); } }
NoSuchMessageException
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/util/ObjectMethodsGuruTest.java
{ "start": 426, "end": 571 }
interface ____ { int compareTo(HasCompareToButDoesNotImplementComparable other); } private
HasCompareToButDoesNotImplementComparable
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/graph/CannotContainSubGraphException.java
{ "start": 332, "end": 480 }
class ____ extends HibernateException { public CannotContainSubGraphException(String message) { super( message ); } }
CannotContainSubGraphException
java
spring-projects__spring-boot
module/spring-boot-health/src/test/java/org/springframework/boot/health/autoconfigure/actuate/endpoint/HealthEndpointAutoConfigurationTests.java
{ "start": 19183, "end": 19438 }
class ____ { @Bean ReactiveHealthContributorRegistry reactiveHealthContributorRegistry() { return new DefaultReactiveHealthContributorRegistry(); } } @Configuration(proxyBeanMethods = false) static
ReactiveHealthContributorRegistryConfiguration
java
quarkusio__quarkus
extensions/smallrye-health/runtime/src/main/java/io/quarkus/smallrye/health/runtime/SmallRyeHealthRuntimeConfig.java
{ "start": 519, "end": 1491 }
interface ____ { /** * If Health UI should be enabled. By default, Health UI is enabled if it is included (see {@code always-include}). */ @WithName("ui.enabled") @WithDefault("true") boolean enabled(); /** * If Health UI should be enabled. By default, Health UI is enabled if it is included (see {@code always-include}). * * @deprecated use {@code quarkus.smallrye-health.ui.enabled} instead */ @WithName("ui.enable") @Deprecated(since = "3.26", forRemoval = true) Optional<Boolean> enable(); /** * Additional top-level properties to be included in the resulting JSON object. */ @WithName("additional.property") @ConfigDocMapKey("property-name") Map<String, String> additionalProperties(); /** * Specifications of checks that can be disabled. */ @ConfigDocMapKey("check-classname") Map<String, Enabled> check(); @ConfigGroup
SmallRyeHealthRuntimeConfig
java
spring-projects__spring-boot
module/spring-boot-restclient/src/test/java/org/springframework/boot/restclient/autoconfigure/RestClientAutoConfigurationTests.java
{ "start": 13390, "end": 13585 }
class ____ { @Bean RestClientCustomizer restClientCustomizer() { return mock(RestClientCustomizer.class); } } @Configuration(proxyBeanMethods = false) static
RestClientCustomizerConfig
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/protocol/AbstractResponseMessage.java
{ "start": 966, "end": 1241 }
class ____ extends AbstractMessage implements ResponseMessage { protected AbstractResponseMessage(ManagedBuffer body, boolean isBodyInFrame) { super(body, isBodyInFrame); } public abstract ResponseMessage createFailureResponse(String error); }
AbstractResponseMessage
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/RemoteLocationContext.java
{ "start": 935, "end": 1005 }
class ____ objects that are unique to a namespace. */ public abstract
for
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketChannelNotYetConnectedTest.java
{ "start": 1697, "end": 4971 }
class ____ extends AbstractClientSocketTest { @Test @Timeout(30) public void testShutdownNotYetConnected(TestInfo testInfo) throws Throwable { run(testInfo, new Runner<Bootstrap>() { @Override public void run(Bootstrap bootstrap) throws Throwable { testShutdownNotYetConnected(bootstrap); } }); } public void testShutdownNotYetConnected(Bootstrap cb) throws Throwable { SocketChannel ch = (SocketChannel) cb.handler(new ChannelInboundHandlerAdapter()) .bind(newSocketAddress()).syncUninterruptibly().channel(); try { try { ch.shutdownInput().syncUninterruptibly(); fail(); } catch (Throwable cause) { checkThrowable(cause); } try { ch.shutdownOutput().syncUninterruptibly(); fail(); } catch (Throwable cause) { checkThrowable(cause); } } finally { ch.close().syncUninterruptibly(); } } private static void checkThrowable(Throwable cause) throws Throwable { // Depending on OIO / NIO both are ok if (!(cause instanceof NotYetConnectedException) && !(cause instanceof SocketException)) { throw cause; } } @Test @Timeout(30) public void readMustBePendingUntilChannelIsActive(TestInfo info) throws Throwable { run(info, new Runner<Bootstrap>() { @Override public void run(Bootstrap bootstrap) throws Throwable { EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); ServerBootstrap sb = new ServerBootstrap().group(group); Channel serverChannel = sb.childHandler(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copyInt(42)); } }).channel(NioServerSocketChannel.class).bind(0).sync().channel(); final CountDownLatch readLatch = new CountDownLatch(1); bootstrap.handler(new ByteToMessageDecoder() { @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertFalse(ctx.channel().isActive()); ctx.read(); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { assertThat(in.readableBytes()).isLessThanOrEqualTo(Integer.BYTES); if (in.readableBytes() == Integer.BYTES) { assertThat(in.readInt()).isEqualTo(42); readLatch.countDown(); } } }); bootstrap.connect(serverChannel.localAddress()).sync(); readLatch.await(); group.shutdownGracefully().await(); } }); } }
SocketChannelNotYetConnectedTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/v2/ttl/TtlMapState.java
{ "start": 5945, "end": 7889 }
class ____<R> implements Iterator<R> { private final Iterator<Map.Entry<UK, TtlValue<UV>>> originalIterator; private final Function<Map.Entry<UK, UV>, R> resultMapper; private Map.Entry<UK, UV> nextUnexpired = null; private boolean rightAfterNextIsCalled = false; private EntriesIterator( @Nonnull Iterable<Map.Entry<UK, TtlValue<UV>>> withTs, @Nonnull Function<Map.Entry<UK, UV>, R> resultMapper) { this.originalIterator = withTs.iterator(); this.resultMapper = resultMapper; } @Override public boolean hasNext() { rightAfterNextIsCalled = false; while (nextUnexpired == null && originalIterator.hasNext()) { Map.Entry<UK, TtlValue<UV>> ttlEntry = originalIterator.next(); UV value = getElementWithTtlCheck(ttlEntry.getValue()); nextUnexpired = value == null ? null : new AbstractMap.SimpleEntry<>(ttlEntry.getKey(), value); } return nextUnexpired != null; } @Override public R next() { if (hasNext()) { rightAfterNextIsCalled = true; R result = resultMapper.apply(nextUnexpired); nextUnexpired = null; return result; } throw new NoSuchElementException(); } @Override public void remove() { if (rightAfterNextIsCalled) { originalIterator.remove(); } else { throw new IllegalStateException( "next() has not been called or hasNext() has been called afterwards," + " remove() is supported only right after calling next()"); } } } private
EntriesIterator
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/state/JoinRecordStateViews.java
{ "start": 3124, "end": 4521 }
class ____ implements JoinRecordStateView { private final ValueState<RowData> recordState; private final List<RowData> reusedList; private JoinKeyContainsUniqueKey( RuntimeContext ctx, String stateName, InternalTypeInfo<RowData> recordType, StateTtlConfig ttlConfig) { ValueStateDescriptor<RowData> recordStateDesc = new ValueStateDescriptor<>(stateName, recordType); if (ttlConfig.isEnabled()) { recordStateDesc.enableTimeToLive(ttlConfig); } this.recordState = ctx.getState(recordStateDesc); // the result records always not more than 1 this.reusedList = new ArrayList<>(1); } @Override public void addRecord(RowData record) throws Exception { recordState.update(record); } @Override public void retractRecord(RowData record) throws Exception { recordState.clear(); } @Override public Iterable<RowData> getRecords() throws Exception { reusedList.clear(); RowData record = recordState.value(); if (record != null) { reusedList.add(record); } return reusedList; } } private static final
JoinKeyContainsUniqueKey
java
alibaba__nacos
consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/WriterTest.java
{ "start": 962, "end": 1481 }
class ____ { private Writer writer; @BeforeEach void setUp() { writer = new Writer("test"); } @Test void test() { assertEquals("test", writer.getPath()); assertTrue(writer.addFile("a")); assertTrue(writer.addFile("b", new LocalFileMeta())); assertEquals(2, writer.listFiles().size()); assertTrue(writer.removeFile("a")); assertEquals(1, writer.listFiles().size()); } }
WriterTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
{ "start": 1796, "end": 2645 }
class ____ { // BUG: Diagnostic contains: @Test public void testThisIsATest() {} // BUG: Diagnostic contains: @Test public static void testThisIsAStaticTest() {} }\ """) .doTest(); } @Test public void positiveCase2() { compilationHelper .addSourceLines( "JUnit4TestNotRunPositiveCase2.java", """ package com.google.errorprone.bugpatterns.testdata; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; /** * Mockito test runner that uses JUnit 4. * * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(MockitoJUnitRunner.class) public
JUnit4TestNotRunPositiveCase1
java
google__guava
android/guava-testlib/test/com/google/common/testing/SerializableTesterTest.java
{ "start": 3092, "end": 3539 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; @Override public boolean equals(@Nullable Object other) { return (other instanceof ObjectWhichIsEqualButChangesClass || other instanceof OtherForm); } @Override public int hashCode() { return 1; } private Object writeReplace() { return new OtherForm(); } private static
ObjectWhichIsEqualButChangesClass
java
spring-projects__spring-boot
module/spring-boot-security/src/main/java/org/springframework/boot/security/web/reactive/ApplicationContextServerWebExchangeMatcher.java
{ "start": 1651, "end": 4116 }
class ____<C> implements ServerWebExchangeMatcher { private final Class<? extends C> contextClass; private volatile @Nullable Supplier<C> context; private final Object contextLock = new Object(); public ApplicationContextServerWebExchangeMatcher(Class<? extends C> contextClass) { Assert.notNull(contextClass, "'contextClass' must not be null"); this.contextClass = contextClass; } @Override public final Mono<MatchResult> matches(ServerWebExchange exchange) { if (ignoreApplicationContext(exchange.getApplicationContext())) { return MatchResult.notMatch(); } return matches(exchange, getContext(exchange)); } /** * Decides whether the rule implemented by the strategy matches the supplied exchange. * @param exchange the source exchange * @param context a supplier for the initialized context (may throw an exception) * @return if the exchange matches */ protected abstract Mono<MatchResult> matches(ServerWebExchange exchange, Supplier<C> context); /** * Returns if the {@link ApplicationContext} should be ignored and not used for * matching. If this method returns {@code true} then the context will not be used and * the {@link #matches(ServerWebExchange) matches} method will return {@code false}. * @param applicationContext the candidate application context * @return if the application context should be ignored */ protected boolean ignoreApplicationContext(@Nullable ApplicationContext applicationContext) { return false; } protected Supplier<C> getContext(ServerWebExchange exchange) { Supplier<C> context = this.context; if (context == null) { synchronized (this.contextLock) { context = this.context; if (context == null) { context = createContext(exchange); initialized(context); this.context = context; } } } return context; } /** * Called once the context has been initialized. * @param context a supplier for the initialized context (may throw an exception) */ protected void initialized(Supplier<C> context) { } @SuppressWarnings("unchecked") private Supplier<C> createContext(ServerWebExchange exchange) { ApplicationContext context = exchange.getApplicationContext(); Assert.state(context != null, "No ApplicationContext found on ServerWebExchange."); if (this.contextClass.isInstance(context)) { return () -> (C) context; } return () -> context.getBean(this.contextClass); } }
ApplicationContextServerWebExchangeMatcher
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/jdk/TypedContainerSerTest.java
{ "start": 2059, "end": 4155 }
class ____ extends Issue508A { } private final static ObjectMapper mapper = new ObjectMapper(); /* /********************************************************** /* Test methods /********************************************************** */ @Test public void testPolymorphicWithContainer() throws Exception { Dog dog = new Dog("medor"); dog.setBoneCount(3); Container1 c1 = new Container1(); c1.setAnimal(dog); String s1 = mapper.writeValueAsString(c1); assertTrue(s1.indexOf("\"object-type\":\"doggy\"") >= 0, "polymorphic type info is kept (1)"); Container2<Animal> c2 = new Container2<Animal>(); c2.setAnimal(dog); String s2 = mapper.writeValueAsString(c2); assertTrue(s2.indexOf("\"object-type\":\"doggy\"") >= 0, "polymorphic type info is kept (2)"); } @Test public void testIssue329() throws Exception { ArrayList<Animal> animals = new ArrayList<Animal>(); animals.add(new Dog("Spot")); JavaType rootType = mapper.getTypeFactory().constructParametricType(Iterator.class, Animal.class); String json = mapper.writerFor(rootType).writeValueAsString(animals.iterator()); if (json.indexOf("\"object-type\":\"doggy\"") < 0) { fail("No polymorphic type retained, should be; JSON = '"+json+"'"); } } @Test public void testIssue508() throws Exception { List<List<Issue508A>> l = new ArrayList<List<Issue508A>>(); List<Issue508A> l2 = new ArrayList<Issue508A>(); l2.add(new Issue508A()); l.add(l2); TypeReference<List<List<Issue508A>>> typeRef = new TypeReference<List<List<Issue508A>>>() {}; String json = mapper.writerFor(typeRef).writeValueAsString(l); List<?> output = mapper.readValue(json, typeRef); assertEquals(1, output.size()); Object ob = output.get(0); assertTrue(ob instanceof List<?>); List<?> list2 = (List<?>) ob; assertEquals(1, list2.size()); ob = list2.get(0); assertSame(Issue508A.class, ob.getClass()); } }
Issue508B
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/common/CommonPhysicalMatchRule.java
{ "start": 6824, "end": 7381 }
class ____ extends RexDefaultVisitor<Object> { @Override public Object visitCall(RexCall call) { SqlOperator operator = call.getOperator(); if (operator instanceof SqlAggFunction) { call.accept(new AggregationPatternVariableFinder()); } else { call.getOperands().forEach(o -> o.accept(this)); } return null; } @Override public Object visitNode(RexNode rexNode) { return null; } } }
AggregationsValidator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedNestedClassTest.java
{ "start": 4869, "end": 5154 }
class ____ { private static final B b = new B(); } } """) .doTest(); } @Test public void usedOutsideSelf_noWarning() { compilationHelper .addSourceLines( "Test.java", """
B
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/dml_return_types/DmlMapperReturnTypesTest.java
{ "start": 1241, "end": 3331 }
class ____ { private static final String SQL = "org/apache/ibatis/submitted/dml_return_types/CreateDB.sql"; private static final String XML = "org/apache/ibatis/submitted/dml_return_types/mybatis-config.xml"; private static SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession; private Mapper mapper; @BeforeAll static void setUp() throws Exception { // create a SqlSessionFactory try (Reader reader = Resources.getResourceAsReader(XML)) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } // populate in-memory database BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), SQL); } @BeforeEach void openSession() { sqlSession = sqlSessionFactory.openSession(); mapper = sqlSession.getMapper(Mapper.class); } @AfterEach void closeSession() { sqlSession.close(); } @Test void updateShouldReturnVoid() { mapper.updateReturnsVoid(new User(1, "updateShouldReturnVoid")); } @Test void shouldReturnPrimitiveInteger() { final int rows = mapper.updateReturnsPrimitiveInteger(new User(1, "shouldReturnPrimitiveInteger")); assertEquals(1, rows); } @Test void shouldReturnInteger() { final Integer rows = mapper.updateReturnsInteger(new User(1, "shouldReturnInteger")); assertEquals(Integer.valueOf(1), rows); } @Test void shouldReturnPrimitiveLong() { final long rows = mapper.updateReturnsPrimitiveLong(new User(1, "shouldReturnPrimitiveLong")); assertEquals(1L, rows); } @Test void shouldReturnLong() { final Long rows = mapper.updateReturnsLong(new User(1, "shouldReturnLong")); assertEquals(Long.valueOf(1), rows); } @Test void shouldReturnPrimitiveBoolean() { final boolean rows = mapper.updateReturnsPrimitiveBoolean(new User(1, "shouldReturnPrimitiveBoolean")); assertTrue(rows); } @Test void shouldReturnBoolean() { final Boolean rows = mapper.updateReturnsBoolean(new User(1, "shouldReturnBoolean")); assertTrue(rows); } }
DmlMapperReturnTypesTest
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/http2/Http2WithNamedConfigTlsRegistryTest.java
{ "start": 1202, "end": 3579 }
class ____ { protected static final String PING_DATA = "87654321"; @TestHTTPResource(value = "/ping", tls = true) URL tlsUrl; @TestHTTPResource(value = "/ping") URL plainUrl; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyBean.class) .addAsResource(new File("target/certs/ssl-test-keystore.jks"), "server-keystore.jks")) .overrideConfigKey("quarkus.tls.key-store.jks.path", "server-keystore.jks") .overrideConfigKey("quarkus.tls.key-store.jks.password", "secret"); @Test public void testHttp2EnabledTls() throws ExecutionException, InterruptedException { WebClientOptions options = new WebClientOptions() .setUseAlpn(true) .setProtocolVersion(HttpVersion.HTTP_2) .setSsl(true) .setTrustOptions(new JksOptions().setPath("target/certs/ssl-test-truststore.jks").setPassword("secret")); WebClient client = WebClient.create(VertxCoreRecorder.getVertx().get(), options); int port = tlsUrl.getPort(); runTest(client, port); } @Test public void testHttp2EnabledPlain() throws ExecutionException, InterruptedException { WebClientOptions options = new WebClientOptions() .setProtocolVersion(HttpVersion.HTTP_2) .setHttp2ClearTextUpgrade(true); WebClient client = WebClient.create(VertxCoreRecorder.getVertx().get(), options); runTest(client, plainUrl.getPort()); } private void runTest(WebClient client, int port) throws InterruptedException, ExecutionException { CompletableFuture<String> result = new CompletableFuture<>(); client .get(port, "localhost", "/ping") .send(ar -> { if (ar.succeeded()) { // Obtain response HttpResponse<Buffer> response = ar.result(); result.complete(response.bodyAsString()); } else { result.completeExceptionally(ar.cause()); } }); Assertions.assertEquals(PING_DATA, result.get()); } @ApplicationScoped static
Http2WithNamedConfigTlsRegistryTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/OrderByEmbeddableToOneTest.java
{ "start": 3724, "end": 4024 }
class ____ { @Id private Integer id; @Basic private String data; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } } }
Contained
java
quarkusio__quarkus
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/providers/AzureAccessTokenCustomizer.java
{ "start": 532, "end": 1347 }
class ____ implements TokenCustomizer { @Override public JsonObject customizeHeaders(JsonObject headers) { try { String nonce = headers.containsKey(OidcConstants.NONCE) ? headers.getString(OidcConstants.NONCE) : null; if (nonce != null) { byte[] nonceSha256 = OidcUtils.getSha256Digest(nonce.getBytes(StandardCharsets.UTF_8)); byte[] newNonceBytes = Base64.getUrlEncoder().withoutPadding().encode(nonceSha256); return jsonProvider().createObjectBuilder(headers) .add(OidcConstants.NONCE, new String(newNonceBytes, StandardCharsets.UTF_8)).build(); } return null; } catch (Exception ex) { throw new OIDCException(ex); } } }
AzureAccessTokenCustomizer
java
elastic__elasticsearch
libs/entitlement/qa/src/javaRestTest/java/org/elasticsearch/entitlement/qa/AbstractEntitlementsIT.java
{ "start": 1009, "end": 4174 }
class ____ extends ESRestTestCase { static final PolicyBuilder ALLOWED_TEST_ENTITLEMENTS = (builder, tempDir) -> { builder.value("create_class_loader"); builder.value("set_https_connection_properties"); builder.value("inbound_network"); builder.value("outbound_network"); builder.value("load_native_libraries"); builder.value("manage_threads"); builder.value( Map.of( "write_system_properties", Map.of("properties", List.of("es.entitlements.checkSetSystemProperty", "es.entitlements.checkClearSystemProperty")) ) ); builder.value( Map.of( "files", List.of( Map.of("path", tempDir.resolve("read_dir"), "mode", "read"), Map.of("path", tempDir.resolve("read_write_dir"), "mode", "read_write"), Map.of("path", tempDir.resolve("read_file"), "mode", "read"), Map.of("path", tempDir.resolve("read_write_file"), "mode", "read_write") ) ) ); }; private final String actionName; private final boolean expectAllowed; AbstractEntitlementsIT(String actionName, boolean expectAllowed) { this.actionName = actionName; this.expectAllowed = expectAllowed; } private Response executeCheck() throws IOException { var request = new Request("GET", "/_entitlement_check"); request.addParameter("action", actionName); return client().performRequest(request); } public void testAction() throws IOException { logger.info("Executing Entitlement test for [{}]", actionName); if (expectAllowed) { Response result = executeCheck(); assertThat(result.getStatusLine().getStatusCode(), equalTo(200)); } else { var exception = expectThrows(ResponseException.class, this::executeCheck); assertThat(exception, statusCodeMatcher(403)); } } private static Matcher<ResponseException> statusCodeMatcher(int statusCode) { return new TypeSafeMatcher<>() { String expectedException = null; @Override protected boolean matchesSafely(ResponseException item) { Response resp = item.getResponse(); expectedException = resp.getHeader("expectedException"); return resp.getStatusLine().getStatusCode() == statusCode && expectedException != null; } @Override public void describeTo(Description description) { description.appendValue(statusCode).appendText(" due to ").appendText(expectedException); } @Override protected void describeMismatchSafely(ResponseException item, Description description) { description.appendText("was ") .appendValue(item.getResponse().getStatusLine().getStatusCode()) .appendText("\n") .appendValue(item.getMessage()); } }; } }
AbstractEntitlementsIT
java
quarkusio__quarkus
extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/MongoTestBase.java
{ "start": 733, "end": 3206 }
class ____ { private static final Logger LOGGER = Logger.getLogger(MongoTestBase.class); protected TransitionWalker.ReachedState<RunningMongodProcess> mongo; protected static String getConfiguredConnectionString() { return getProperty("connection_string"); } protected static String getProperty(String name) { String s = System.getProperty(name); if (s != null) { s = s.trim(); if (s.length() > 0) { return s; } } return null; } @BeforeAll public void startMongoDatabase() { forceExtendedSocketOptionsClassInit(); String uri = getConfiguredConnectionString(); // This switch allow testing against a running mongo database. if (uri == null) { Version.Main version = Version.Main.V7_0; int port = 27018; LOGGER.infof("Starting Mongo %s on port %s", version, port); ImmutableMongod config = Mongod.instance() .withNet(Start.to(Net.class).initializedWith(Net.builder() .from(Net.defaults()) .port(port) .build())) .withMongodArguments(Start.to(MongodArguments.class) .initializedWith(MongodArguments.defaults() .withUseNoJournal( false))) .withProcessConfig( Start.to(ProcessConfig.class) .initializedWith(ProcessConfig.defaults() .withStopTimeoutInMillis(15_000))); config = addExtraConfig(config); mongo = config.start(version); } else { LOGGER.infof("Using existing Mongo %s", uri); } } protected ImmutableMongod addExtraConfig(ImmutableMongod mongo) { return mongo; } @AfterAll public void stopMongoDatabase() { if (mongo != null) { try { mongo.close(); } catch (Exception e) { LOGGER.error("Unable to stop MongoDB", e); } } } public static void forceExtendedSocketOptionsClassInit() { try { //JDK bug workaround //https://github.com/quarkusio/quarkus/issues/14424 //force
MongoTestBase
java
netty__netty
testsuite-http2/src/main/java/io/netty/testsuite/http2/Http2Server.java
{ "start": 1225, "end": 2264 }
class ____ { private final int port; Http2Server(final int port) { this.port = port; } void run() throws Exception { // Configure the server. EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new Http2ServerInitializer()); Channel ch = b.bind(port).sync().channel(); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 9000; } new Http2Server(port).run(); } }
Http2Server
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/BlockListAsLongs.java
{ "start": 10891, "end": 14787 }
class ____ extends BlockListAsLongs { // reserve upper bits for future use. decoding masks off these bits to // allow compatibility for the current through future release that may // start using the bits private static long NUM_BYTES_MASK = (-1L) >>> (64 - 48); private static long REPLICA_STATE_MASK = (-1L) >>> (64 - 4); private final ByteString buffer; private final int numBlocks; private int numFinalized; private final int maxDataLength; BufferDecoder(final int numBlocks, final ByteString buf, final int maxDataLength) { this(numBlocks, -1, buf, maxDataLength); } BufferDecoder(final int numBlocks, final int numFinalized, final ByteString buf, final int maxDataLength) { this.numBlocks = numBlocks; this.numFinalized = numFinalized; this.buffer = buf; this.maxDataLength = maxDataLength; } @Override public int getNumberOfBlocks() { return numBlocks; } @Override public ByteString getBlocksBuffer() { return buffer; } @Override public long[] getBlockListAsLongs() { // terribly inefficient but only occurs if server tries to transcode // an undecoded buffer into longs - ie. it will never happen but let's // handle it anyway if (numFinalized == -1) { int n = 0; for (Replica replica : this) { if (replica.getState() == ReplicaState.FINALIZED) { n++; } } numFinalized = n; } int numUc = numBlocks - numFinalized; int size = 2 + 3*(numFinalized+1) + 4*(numUc); long[] longs = new long[size]; longs[0] = numFinalized; longs[1] = numUc; int idx = 2; int ucIdx = idx + 3*numFinalized; // delimiter block longs[ucIdx++] = -1; longs[ucIdx++] = -1; longs[ucIdx++] = -1; for (BlockReportReplica block : this) { switch (block.getState()) { case FINALIZED: { longs[idx++] = block.getBlockId(); longs[idx++] = block.getNumBytes(); longs[idx++] = block.getGenerationStamp(); break; } default: { longs[ucIdx++] = block.getBlockId(); longs[ucIdx++] = block.getNumBytes(); longs[ucIdx++] = block.getGenerationStamp(); longs[ucIdx++] = block.getState().getValue(); break; } } } return longs; } @Override public Iterator<BlockReportReplica> iterator() { return new Iterator<BlockReportReplica>() { final BlockReportReplica block = new BlockReportReplica(); final CodedInputStream cis = buffer.newCodedInput(); private int currentBlockIndex = 0; { if (maxDataLength != IPC_MAXIMUM_DATA_LENGTH_DEFAULT) { cis.setSizeLimit(maxDataLength); } } @Override public boolean hasNext() { return currentBlockIndex < numBlocks; } @Override public BlockReportReplica next() { currentBlockIndex++; try { // zig-zag to reduce size of legacy blocks and mask off bits // we don't (yet) understand block.setBlockId(cis.readSInt64()); block.setNumBytes(cis.readRawVarint64() & NUM_BYTES_MASK); block.setGenerationStamp(cis.readRawVarint64()); long state = cis.readRawVarint64() & REPLICA_STATE_MASK; block.setState(ReplicaState.getState((int)state)); } catch (IOException e) { throw new IllegalStateException(e); } return block; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } // decode old style block report of longs private static
BufferDecoder
java
apache__camel
components/camel-kamelet/src/main/java/org/apache/camel/component/kamelet/KameletProcessorFactory.java
{ "start": 1026, "end": 1390 }
class ____ extends TypedProcessorFactory<KameletDefinition> { public KameletProcessorFactory() { super(KameletDefinition.class); } @Override public Processor doCreateProcessor(Route route, KameletDefinition definition) throws Exception { return new KameletReifier(route, definition).createProcessor(); } }
KameletProcessorFactory
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/jdk8/OptionalNumbersTest.java
{ "start": 729, "end": 961 }
class ____ { public OptionalLong value; public OptionalLongBean() { value = OptionalLong.empty(); } OptionalLongBean(long v) { value = OptionalLong.of(v); } } static
OptionalLongBean
java
processing__processing4
core/src/processing/data/JSONObject.java
{ "start": 5995, "end": 6794 }
class ____ { /** * The maximum number of keys in the key pool. */ private static final int keyPoolSize = 100; /** * Key pooling is like string interning, but without permanently tying up * memory. To help conserve memory, storage of duplicated key strings in * JSONObjects will be avoided by using a key pool to manage unique key * string objects. This is used by JSONObject.put(string, object). */ private static HashMap<String, Object> keyPool = new HashMap<>(keyPoolSize); // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final
JSONObject
java
netty__netty
codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java
{ "start": 850, "end": 7148 }
class ____ implements Comparable<DnsResponseCode> { /** * The 'NoError' DNS RCODE (0), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode NOERROR = new DnsResponseCode(0, "NoError"); /** * The 'FormErr' DNS RCODE (1), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode FORMERR = new DnsResponseCode(1, "FormErr"); /** * The 'ServFail' DNS RCODE (2), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode SERVFAIL = new DnsResponseCode(2, "ServFail"); /** * The 'NXDomain' DNS RCODE (3), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode NXDOMAIN = new DnsResponseCode(3, "NXDomain"); /** * The 'NotImp' DNS RCODE (4), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode NOTIMP = new DnsResponseCode(4, "NotImp"); /** * The 'Refused' DNS RCODE (5), as defined in <a href="https://tools.ietf.org/html/rfc1035">RFC1035</a>. */ public static final DnsResponseCode REFUSED = new DnsResponseCode(5, "Refused"); /** * The 'YXDomain' DNS RCODE (6), as defined in <a href="https://tools.ietf.org/html/rfc2136">RFC2136</a>. */ public static final DnsResponseCode YXDOMAIN = new DnsResponseCode(6, "YXDomain"); /** * The 'YXRRSet' DNS RCODE (7), as defined in <a href="https://tools.ietf.org/html/rfc2136">RFC2136</a>. */ public static final DnsResponseCode YXRRSET = new DnsResponseCode(7, "YXRRSet"); /** * The 'NXRRSet' DNS RCODE (8), as defined in <a href="https://tools.ietf.org/html/rfc2136">RFC2136</a>. */ public static final DnsResponseCode NXRRSET = new DnsResponseCode(8, "NXRRSet"); /** * The 'NotAuth' DNS RCODE (9), as defined in <a href="https://tools.ietf.org/html/rfc2136">RFC2136</a>. */ public static final DnsResponseCode NOTAUTH = new DnsResponseCode(9, "NotAuth"); /** * The 'NotZone' DNS RCODE (10), as defined in <a href="https://tools.ietf.org/html/rfc2136">RFC2136</a>. */ public static final DnsResponseCode NOTZONE = new DnsResponseCode(10, "NotZone"); /** * The 'BADVERS' or 'BADSIG' DNS RCODE (16), as defined in <a href="https://tools.ietf.org/html/rfc2671">RFC2671</a> * and <a href="https://tools.ietf.org/html/rfc2845">RFC2845</a>. */ public static final DnsResponseCode BADVERS_OR_BADSIG = new DnsResponseCode(16, "BADVERS_OR_BADSIG"); /** * The 'BADKEY' DNS RCODE (17), as defined in <a href="https://tools.ietf.org/html/rfc2845">RFC2845</a>. */ public static final DnsResponseCode BADKEY = new DnsResponseCode(17, "BADKEY"); /** * The 'BADTIME' DNS RCODE (18), as defined in <a href="https://tools.ietf.org/html/rfc2845">RFC2845</a>. */ public static final DnsResponseCode BADTIME = new DnsResponseCode(18, "BADTIME"); /** * The 'BADMODE' DNS RCODE (19), as defined in <a href="https://tools.ietf.org/html/rfc2930">RFC2930</a>. */ public static final DnsResponseCode BADMODE = new DnsResponseCode(19, "BADMODE"); /** * The 'BADNAME' DNS RCODE (20), as defined in <a href="https://tools.ietf.org/html/rfc2930">RFC2930</a>. */ public static final DnsResponseCode BADNAME = new DnsResponseCode(20, "BADNAME"); /** * The 'BADALG' DNS RCODE (21), as defined in <a href="https://tools.ietf.org/html/rfc2930">RFC2930</a>. */ public static final DnsResponseCode BADALG = new DnsResponseCode(21, "BADALG"); /** * Returns the {@link DnsResponseCode} that corresponds with the given {@code responseCode}. * * @param responseCode the DNS RCODE * * @return the corresponding {@link DnsResponseCode} */ public static DnsResponseCode valueOf(int responseCode) { switch (responseCode) { case 0: return NOERROR; case 1: return FORMERR; case 2: return SERVFAIL; case 3: return NXDOMAIN; case 4: return NOTIMP; case 5: return REFUSED; case 6: return YXDOMAIN; case 7: return YXRRSET; case 8: return NXRRSET; case 9: return NOTAUTH; case 10: return NOTZONE; case 16: return BADVERS_OR_BADSIG; case 17: return BADKEY; case 18: return BADTIME; case 19: return BADMODE; case 20: return BADNAME; case 21: return BADALG; default: return new DnsResponseCode(responseCode); } } private final int code; private final String name; private String text; private DnsResponseCode(int code) { this(code, "UNKNOWN"); } public DnsResponseCode(int code, String name) { if (code < 0 || code > 65535) { throw new IllegalArgumentException("code: " + code + " (expected: 0 ~ 65535)"); } this.code = code; this.name = checkNotNull(name, "name"); } /** * Returns the error code for this {@link DnsResponseCode}. */ public int intValue() { return code; } @Override public int compareTo(DnsResponseCode o) { return intValue() - o.intValue(); } @Override public int hashCode() { return intValue(); } /** * Equality of {@link DnsResponseCode} only depends on {@link #intValue()}. */ @Override public boolean equals(Object o) { if (!(o instanceof DnsResponseCode)) { return false; } return intValue() == ((DnsResponseCode) o).intValue(); } /** * Returns a formatted error message for this {@link DnsResponseCode}. */ @Override public String toString() { String text = this.text; if (text == null) { this.text = text = name + '(' + intValue() + ')'; } return text; } }
DnsResponseCode
java
spring-projects__spring-boot
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/VirtualZipDataBlock.java
{ "start": 1027, "end": 5392 }
class ____ extends VirtualDataBlock implements CloseableDataBlock { private final CloseableDataBlock data; /** * Create a new {@link VirtualZipDataBlock} for the given entries. * @param data the source zip data * @param nameOffsetLookups the name offsets to apply * @param centralRecords the records that should be copied to the virtual zip * @param centralRecordPositions the record positions in the data block. * @throws IOException on I/O error */ VirtualZipDataBlock(CloseableDataBlock data, NameOffsetLookups nameOffsetLookups, ZipCentralDirectoryFileHeaderRecord[] centralRecords, long[] centralRecordPositions) throws IOException { this.data = data; List<DataBlock> parts = new ArrayList<>(); List<DataBlock> centralParts = new ArrayList<>(); long offset = 0; long sizeOfCentralDirectory = 0; for (int i = 0; i < centralRecords.length; i++) { ZipCentralDirectoryFileHeaderRecord centralRecord = centralRecords[i]; int nameOffset = nameOffsetLookups.get(i); long centralRecordPos = centralRecordPositions[i]; DataBlock name = new DataPart( centralRecordPos + ZipCentralDirectoryFileHeaderRecord.FILE_NAME_OFFSET + nameOffset, Short.toUnsignedLong(centralRecord.fileNameLength()) - nameOffset); long localRecordPos = Integer.toUnsignedLong(centralRecord.offsetToLocalHeader()); ZipLocalFileHeaderRecord localRecord = ZipLocalFileHeaderRecord.load(this.data, localRecordPos); DataBlock content = new DataPart(localRecordPos + localRecord.size(), centralRecord.compressedSize()); boolean hasDescriptorRecord = ZipDataDescriptorRecord.isPresentBasedOnFlag(centralRecord); ZipDataDescriptorRecord dataDescriptorRecord = (!hasDescriptorRecord) ? null : ZipDataDescriptorRecord.load(data, localRecordPos + localRecord.size() + content.size()); sizeOfCentralDirectory += addToCentral(centralParts, centralRecord, centralRecordPos, name, (int) offset); offset += addToLocal(parts, centralRecord, localRecord, dataDescriptorRecord, name, content); } parts.addAll(centralParts); ZipEndOfCentralDirectoryRecord eocd = new ZipEndOfCentralDirectoryRecord((short) centralRecords.length, (int) sizeOfCentralDirectory, (int) offset); parts.add(new ByteArrayDataBlock(eocd.asByteArray())); setParts(parts); } private long addToCentral(List<DataBlock> parts, ZipCentralDirectoryFileHeaderRecord originalRecord, long originalRecordPos, DataBlock name, int offsetToLocalHeader) throws IOException { ZipCentralDirectoryFileHeaderRecord record = originalRecord.withFileNameLength((short) (name.size() & 0xFFFF)) .withOffsetToLocalHeader(offsetToLocalHeader); int originalExtraFieldLength = Short.toUnsignedInt(originalRecord.extraFieldLength()); int originalFileCommentLength = Short.toUnsignedInt(originalRecord.fileCommentLength()); int extraFieldAndCommentSize = originalExtraFieldLength + originalFileCommentLength; parts.add(new ByteArrayDataBlock(record.asByteArray())); parts.add(name); if (extraFieldAndCommentSize > 0) { parts.add(new DataPart(originalRecordPos + originalRecord.size() - extraFieldAndCommentSize, extraFieldAndCommentSize)); } return record.size(); } private long addToLocal(List<DataBlock> parts, ZipCentralDirectoryFileHeaderRecord centralRecord, ZipLocalFileHeaderRecord originalRecord, ZipDataDescriptorRecord dataDescriptorRecord, DataBlock name, DataBlock content) throws IOException { ZipLocalFileHeaderRecord record = originalRecord.withFileNameLength((short) (name.size() & 0xFFFF)); long originalRecordPos = Integer.toUnsignedLong(centralRecord.offsetToLocalHeader()); int extraFieldLength = Short.toUnsignedInt(originalRecord.extraFieldLength()); parts.add(new ByteArrayDataBlock(record.asByteArray())); parts.add(name); if (extraFieldLength > 0) { parts.add(new DataPart(originalRecordPos + originalRecord.size() - extraFieldLength, extraFieldLength)); } parts.add(content); if (dataDescriptorRecord != null) { parts.add(new ByteArrayDataBlock(dataDescriptorRecord.asByteArray())); } return record.size() + content.size() + ((dataDescriptorRecord != null) ? dataDescriptorRecord.size() : 0); } @Override public void close() throws IOException { this.data.close(); } /** * {@link DataBlock} that points to part of the original data block. */ final
VirtualZipDataBlock
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/cli/CLITestCmdMR.java
{ "start": 1046, "end": 1716 }
class ____ extends CLITestCmd { public CLITestCmdMR(String str, CLICommandTypes type) { super(str, type); } /** * This is not implemented because HadoopArchive constructor requires JobConf * to create an archive object. Because TestMRCLI uses setup method from * TestHDFSCLI the initialization of executor objects happens before a config * is created and updated. Thus, actual calls to executors happen in the body * of the test method. */ @Override public CommandExecutor getExecutor(String tag, Configuration conf) throws IllegalArgumentException { throw new IllegalArgumentException("Method isn't supported"); } }
CLITestCmdMR
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/MethodInvokers.java
{ "start": 8866, "end": 9095 }
interface ____ redirects its calls to the given method. * <p> * For the definition of "single-method", see {@link MethodHandleProxies#asInterfaceInstance(Class, MethodHandle)}. * </p> * * @param <T> The
which
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/analysis/IndexAnalyzers.java
{ "start": 1050, "end": 1236 }
class ____ holds analyzers that are explicitly configured for an index and doesn't allow * access to individual tokenizers, char or token filter. * * @see AnalysisRegistry */ public
only
java
square__retrofit
retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java
{ "start": 3818, "end": 4292 }
class ____ { @FormUrlEncoded // @Multipart // @POST("/") // Call<ResponseBody> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageThat() .isEqualTo("Only one encoding annotation is allowed.\n for method Example.method"); } } @Test public void invalidPathParam() throws Exception {
Example
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java
{ "start": 49935, "end": 51685 }
class ____ extends RMAppTransition { @Override public void transition(RMAppImpl app, RMAppEvent event) { String msg = null; if (event instanceof RMAppFailedAttemptEvent) { msg = app.getAppAttemptFailedDiagnostics(event); } LOG.info(msg); app.diagnostics.append(msg); // Inform the node for app-finish new FinalTransition(RMAppState.FAILED).transition(app, event); } } private String getAppAttemptFailedDiagnostics(RMAppEvent event) { String msg = null; RMAppFailedAttemptEvent failedEvent = (RMAppFailedAttemptEvent) event; if (this.submissionContext.getUnmanagedAM()) { // RM does not manage the AM. Do not retry msg = "Unmanaged application " + this.getApplicationId() + " failed due to " + failedEvent.getDiagnosticMsg() + ". Failing the application."; } else if (this.isNumAttemptsBeyondThreshold) { int globalLimit = conf.getInt(YarnConfiguration.GLOBAL_RM_AM_MAX_ATTEMPTS, conf.getInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS)); msg = String.format( "Application %s failed %d times%s%s due to %s. Failing the application.", getApplicationId(), maxAppAttempts, (attemptFailuresValidityInterval <= 0 ? "" : (" in previous " + attemptFailuresValidityInterval + " milliseconds")), (globalLimit == maxAppAttempts) ? "" : (" (global limit =" + globalLimit + "; local limit is =" + maxAppAttempts + ")"), failedEvent.getDiagnosticMsg()); } return msg; } private static final
AttemptFailedFinalStateSavedTransition
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/SecurityActionMapperTests.java
{ "start": 5330, "end": 5630 }
class ____ extends SingleShardRequest<MockPainlessExecuteRequest> { MockPainlessExecuteRequest(String index) { super(index); } @Override public ActionRequestValidationException validate() { return null; } } }
MockPainlessExecuteRequest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/web/server/OidcLogoutSpecTests.java
{ "start": 30108, "end": 30456 }
class ____ { private final MockWebServer server = new MockWebServer(); @Bean MockWebServer web(ObjectProvider<WebTestClient> web) { this.server.setDispatcher(new WebTestClientDispatcher(web)); return this.server; } @PreDestroy void shutdown() throws IOException { this.server.shutdown(); } } private static
WebServerConfig
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/legacy/ConfigureTest.java
{ "start": 1205, "end": 1264 }
class ____ that a Camel context can be configured. */
ensuring
java
apache__flink
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlAlterMaterializedTableOptions.java
{ "start": 1330, "end": 2125 }
class ____ extends SqlAlterMaterializedTable { private final SqlNodeList propertyList; public SqlAlterMaterializedTableOptions( SqlParserPos pos, SqlIdentifier tableName, SqlNodeList propertyList) { super(pos, tableName); this.propertyList = propertyList; } public SqlNodeList getPropertyList() { return propertyList; } @Override public List<SqlNode> getOperandList() { return ImmutableNullableList.of(name, propertyList); } @Override public void unparseAlterOperation(SqlWriter writer, int leftPrec, int rightPrec) { super.unparseAlterOperation(writer, leftPrec, rightPrec); SqlUnparseUtils.unparseSetOptions(propertyList, writer, leftPrec, rightPrec); } }
SqlAlterMaterializedTableOptions
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/OperatorPrecedenceTest.java
{ "start": 3940, "end": 4211 }
class ____ { void f(boolean a, boolean b, boolean c, boolean d, boolean e) { boolean g = (a || (b && c && d) && e); } } """) .addOutputLines( "Test.java", """
Test
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/scan/valid/a/AScanConfiguration.java
{ "start": 1172, "end": 1260 }
class ____ { } @Profile("test") @ConfigurationProperties("profile") static
AProperties
java
processing__processing4
app/src/processing/app/syntax/JEditTextArea.java
{ "start": 61428, "end": 64770 }
class ____ implements LayoutManager { //final int LEFT_EXTRA = 5; public void addLayoutComponent(String name, Component comp) { if(name.equals(CENTER)) center = comp; else if(name.equals(RIGHT)) right = comp; else if(name.equals(BOTTOM)) bottom = comp; else if(name.equals(LEFT_OF_SCROLLBAR)) leftOfScrollBar.addElement(comp); } public void removeLayoutComponent(Component comp) { if(center == comp) center = null; if(right == comp) right = null; if(bottom == comp) bottom = null; else leftOfScrollBar.removeElement(comp); } public Dimension preferredLayoutSize(Container parent) { Dimension dim = new Dimension(); Insets insets = getInsets(); dim.width = insets.left + insets.right; dim.height = insets.top + insets.bottom; Dimension centerPref = center.getPreferredSize(); dim.width += centerPref.width; dim.height += centerPref.height; Dimension rightPref = right.getPreferredSize(); dim.width += rightPref.width; Dimension bottomPref = bottom.getPreferredSize(); dim.height += bottomPref.height; return dim; } public Dimension minimumLayoutSize(Container parent) { Dimension dim = new Dimension(); Insets insets = getInsets(); dim.width = insets.left + insets.right; dim.height = insets.top + insets.bottom; Dimension centerPref = center.getMinimumSize(); dim.width += centerPref.width; dim.height += centerPref.height; Dimension rightPref = right.getMinimumSize(); dim.width += rightPref.width; Dimension bottomPref = bottom.getMinimumSize(); dim.height += bottomPref.height; dim.height += 5; return dim; } public void layoutContainer(Container parent) { Dimension size = parent.getSize(); Insets insets = parent.getInsets(); int itop = insets.top; int ileft = insets.left; int ibottom = insets.bottom; int iright = insets.right; int rightWidth = right.getPreferredSize().width; int bottomHeight = bottom.getPreferredSize().height; int centerWidth = size.width - rightWidth - ileft - iright; int centerHeight = size.height - bottomHeight - itop - ibottom; center.setBounds(ileft, // + LEFT_EXTRA, itop, centerWidth, // - LEFT_EXTRA, centerHeight); right.setBounds(ileft + centerWidth, itop, rightWidth, centerHeight); // Lay out all status components, in order Enumeration<Component> status = leftOfScrollBar.elements(); while (status.hasMoreElements()) { Component comp = status.nextElement(); Dimension dim = comp.getPreferredSize(); comp.setBounds(ileft, itop + centerHeight, dim.width, bottomHeight); ileft += dim.width; } bottom.setBounds(ileft, itop + centerHeight, size.width - rightWidth - ileft - iright, bottomHeight); } // private members private Component center; private Component right; private Component bottom; private final Vector<Component> leftOfScrollBar = new Vector<>(); } */
ScrollLayout
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/spatial/SpatialCentroidCartesianPointDocValuesAggregatorFunctionSupplier.java
{ "start": 826, "end": 2040 }
class ____ implements AggregatorFunctionSupplier { public SpatialCentroidCartesianPointDocValuesAggregatorFunctionSupplier() { } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return SpatialCentroidCartesianPointDocValuesAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return SpatialCentroidCartesianPointDocValuesGroupingAggregatorFunction.intermediateStateDesc(); } @Override public SpatialCentroidCartesianPointDocValuesAggregatorFunction aggregator( DriverContext driverContext, List<Integer> channels) { return SpatialCentroidCartesianPointDocValuesAggregatorFunction.create(driverContext, channels); } @Override public SpatialCentroidCartesianPointDocValuesGroupingAggregatorFunction groupingAggregator( DriverContext driverContext, List<Integer> channels) { return SpatialCentroidCartesianPointDocValuesGroupingAggregatorFunction.create(channels, driverContext); } @Override public String describe() { return "spatial_centroid_cartesian_point_doc of valuess"; } }
SpatialCentroidCartesianPointDocValuesAggregatorFunctionSupplier
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AlreadyCheckedTest.java
{ "start": 1165, "end": 1548 }
class ____ { public void test(boolean a) { if (a) { // BUG: Diagnostic contains: false } else if (a) { } } } """) .doTest(); } @Test public void thisAndThat() { helper .addSourceLines( "Test.java", """
Test
java
spring-projects__spring-boot
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/sbom/SbomEndpointDocumentationTests.java
{ "start": 1570, "end": 2098 }
class ____ extends MockMvcEndpointDocumentationTests { @Test void sbom() { assertThat(this.mvc.get().uri("/actuator/sbom")).hasStatusOk() .apply(MockMvcRestDocumentation.document("sbom", responseFields(fieldWithPath("ids").description("An array of available SBOM ids.")))); } @Test void sboms() { assertThat(this.mvc.get().uri("/actuator/sbom/application")).hasStatusOk() .apply(MockMvcRestDocumentation.document("sbom/id")); } @Configuration(proxyBeanMethods = false) static
SbomEndpointDocumentationTests
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/providers/ProviderConfigInjectionTest.java
{ "start": 1473, "end": 1800 }
class ____ implements ContextResolver<String> { @ConfigProperty(name = "configProperty", defaultValue = "configProperty") String configProperty; @Override public String getContext(Class<?> type) { return configProperty; } } @StaticInitSafe public static
FooProvider
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParser.java
{ "start": 51774, "end": 54142 }
class ____ extends ParserRuleContext { public List<LabelContext> label() { return getRuleContexts(LabelContext.class); } public LabelContext label(int i) { return getRuleContext(LabelContext.class,i); } public List<TerminalNode> COMMA() { return getTokens(PromqlBaseParser.COMMA); } public TerminalNode COMMA(int i) { return getToken(PromqlBaseParser.COMMA, i); } @SuppressWarnings("this-escape") public LabelsContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_labels; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).enterLabels(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PromqlBaseParserListener ) ((PromqlBaseParserListener)listener).exitLabels(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof PromqlBaseParserVisitor ) return ((PromqlBaseParserVisitor<? extends T>)visitor).visitLabels(this); else return visitor.visitChildren(this); } } public final LabelsContext labels() throws RecognitionException { LabelsContext _localctx = new LabelsContext(_ctx, getState()); enterRule(_localctx, 22, RULE_labels); int _la; try { enterOuterAlt(_localctx, 1); { setState(209); label(); setState(216); _errHandler.sync(this); _la = _input.LA(1); while (_la==COMMA) { { { setState(210); match(COMMA); setState(212); _errHandler.sync(this); _la = _input.LA(1); if ((((_la) & ~0x3f) == 0 && ((1L << _la) & 21715488800768L) != 0)) { { setState(211); label(); } } } } setState(218); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
LabelsContext
java
apache__camel
components/camel-servlet/src/test/java/org/apache/camel/component/servlet/ServletSetExchangePropertyBeanTest.java
{ "start": 999, "end": 2047 }
class ____ extends ServletCamelRouterTestSupport { @Test public void testSetProperty() throws Exception { WebRequest req = new GetMethodWebRequest(contextUrl + "/services/hello"); WebResponse response = query(req); assertEquals(204, response.getResponseCode()); assertEquals("", response.getText(), "The response message is wrong"); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { onException(Exception.class) .handled(true); from("servlet:/hello?httpBinding.eagerCheckContentAvailable=true") .setProperty("myProperty").method(ServletSetExchangePropertyBeanTest.class, "throwException"); } }; } public static void throwException() throws Exception { throw new IllegalArgumentException("Forced"); } }
ServletSetExchangePropertyBeanTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/serialization/Serdes.java
{ "start": 2732, "end": 2917 }
class ____ extends WrapperSerde<Float> { public FloatSerde() { super(new FloatSerializer(), new FloatDeserializer()); } } public static final
FloatSerde
java
apache__camel
tooling/camel-tooling-util/src/main/java/org/apache/camel/tooling/util/ReflectionHelper.java
{ "start": 7007, "end": 7198 }
class ____ the supplied name. Searches all superclasses up to * {@code Object}. * <p> * Returns {@code null} if no {@link Method} can be found. * * @param clazz the
with
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ArrayElementTypeStrategyTest.java
{ "start": 1067, "end": 2263 }
class ____ extends TypeStrategiesTestBase { @Override protected Stream<TestSpec> testData() { return Stream.of( TestSpec.forStrategy( "Infer an element of an array type", SpecificTypeStrategies.ARRAY_ELEMENT) .inputTypes(DataTypes.ARRAY(DataTypes.BIGINT().notNull())) .expectDataType(DataTypes.BIGINT().nullable()), TestSpec.forStrategy( "Infer an element of a multiset type", SpecificTypeStrategies.ARRAY_ELEMENT) .inputTypes(DataTypes.MULTISET(DataTypes.STRING().notNull())) .expectDataType(DataTypes.STRING().nullable()), TestSpec.forStrategy( "Error on non collection type", SpecificTypeStrategies.ARRAY_ELEMENT) .inputTypes(DataTypes.BIGINT()) .expectErrorMessage( "Could not infer an output type for the given arguments.")); } }
ArrayElementTypeStrategyTest
java
apache__kafka
metadata/src/main/java/org/apache/kafka/metadata/placement/ReplicaPlacer.java
{ "start": 994, "end": 1099 }
interface ____ a Kafka replica placement policy must implement. */ @InterfaceStability.Unstable public
which
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/filecache/DistributedCache.java
{ "start": 4564, "end": 5353 }
class ____ extends MapReduceBase * implements Mapper&lt;K, V, K, V&gt; { * * private Path[] localArchives; * private Path[] localFiles; * * public void configure(JobConf job) { * // Get the cached archives/files * File f = new File("./map.zip/some/file/in/zip.txt"); * } * * public void map(K key, V value, * OutputCollector&lt;K, V&gt; output, Reporter reporter) * throws IOException { * // Use data from the cached archives/files here * // ... * // ... * output.collect(k, v); * } * } * * </pre></blockquote> * * It is also very common to use the DistributedCache by using * {@link org.apache.hadoop.util.GenericOptionsParser}. * * This
MapClass