language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
hibernate__hibernate-orm
hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0EmptyIsolationLevelTest.java
{ "start": 1528, "end": 3033 }
class ____ { private static final C3P0ProxyConnectionProvider connectionProvider = new C3P0ProxyConnectionProvider(); @Test public void testStoredProcedureOutParameter(SessionFactoryScope factoryScope) throws SQLException { var sqlCollector = factoryScope.getCollectingStatementInspector(); sqlCollector.clear(); connectionProvider.clear(); factoryScope.inTransaction( (session) -> { Person person = new Person(); person.id = 1L; person.name = "Vlad Mihalcea"; session.persist( person ); } ); assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 ); assertThat( sqlCollector.getSqlQueries().get( 0 ) ).startsWithIgnoringCase( "insert into " ); Connection connectionSpy = connectionProvider.getConnectionSpyMap().keySet().iterator().next(); verify( connectionSpy, never() ).setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); sqlCollector.clear(); connectionProvider.clear(); factoryScope.inTransaction( (session) -> { Person person = session.find( Person.class, 1L ); assertThat( person.name ).isEqualTo( "Vlad Mihalcea" ); } ); assertThat( sqlCollector.getSqlQueries() ).hasSize( 1 ); assertThat( sqlCollector.getSqlQueries().get( 0 ) ).startsWithIgnoringCase( "select " ); connectionSpy = connectionProvider.getConnectionSpyMap().keySet().iterator().next(); verify( connectionSpy, never() ).setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); } @Entity(name = "Person") public static
C3P0EmptyIsolationLevelTest
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/rsocket/service/RSocketExchangeReflectiveProcessorTests.java
{ "start": 3787, "end": 4015 }
class ____ { private String value; public Metadata(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
Metadata
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/transport/actions/put/GetWatcherSettingsAction.java
{ "start": 1130, "end": 1479 }
class ____ extends ActionType<GetWatcherSettingsAction.Response> { public static final GetWatcherSettingsAction INSTANCE = new GetWatcherSettingsAction(); public static final String NAME = "cluster:admin/xpack/watcher/settings/get"; public GetWatcherSettingsAction() { super(NAME); } public static
GetWatcherSettingsAction
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/analytics/event/AnalyticsEvent.java
{ "start": 1351, "end": 1537 }
class ____ Analytics events object meant to be emitted to the event queue. * @deprecated in 9.0 */ @Deprecated @UpdateForV10(owner = UpdateForV10.Owner.ENTERPRISE_SEARCH) public
represents
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/validators/FixLicenseHeaders.java
{ "start": 816, "end": 4899 }
class ____ { String[] header = { "/*", " * Copyright (c) 2016-present, RxJava Contributors.", " *", " * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in", " * compliance with the License. You may obtain a copy of the License at", " *", " * http://www.apache.org/licenses/LICENSE-2.0", " *", " * Unless required by applicable law or agreed to in writing, software distributed under the License is", " * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See", " * the License for the specific language governing permissions and limitations under the License.", " */", "" }; @Test public void checkAndUpdateLicenses() throws Exception { if (System.getenv("CI") != null) { // no point in changing the files in CI return; } File f = TestHelper.findSource("Flowable"); if (f == null) { return; } Queue<File> dirs = new ArrayDeque<>(); File parent = f.getParentFile().getParentFile(); dirs.offer(parent); dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/perf/java"))); dirs.offer(new File(parent.getAbsolutePath().replace('\\', '/').replace("src/main/java", "src/test/java"))); StringBuilder fail = new StringBuilder(); while (!dirs.isEmpty()) { f = dirs.poll(); File[] list = f.listFiles(); if (list != null && list.length != 0) { for (File u : list) { if (u.isDirectory()) { dirs.offer(u); } else { if (u.getName().endsWith(".java")) { List<String> lines = new ArrayList<>(); BufferedReader in = new BufferedReader(new FileReader(u)); try { for (;;) { String line = in.readLine(); if (line == null) { break; } lines.add(line); } } finally { in.close(); } if (!lines.get(0).equals(header[0]) || !lines.get(1).equals(header[1])) { fail.append("java.lang.RuntimeException: missing header added, refresh and re-run tests!\r\n") .append(" at ") ; String fn = u.toString().replace('\\', '/'); int idx = fn.indexOf("io/reactivex/"); fn = fn.substring(idx).replace('/', '.').replace(".java", ""); fail.append(fn).append(" (") ; int jdx = fn.lastIndexOf('.'); fail.append(fn.substring(jdx + 1)); fail.append(".java:1)\r\n\r\n"); lines.addAll(0, Arrays.asList(header)); PrintWriter w = new PrintWriter(new FileWriter(u)); try { for (String s : lines) { w.println(s); } } finally { w.close(); } } } } } } } if (fail.length() != 0) { System.out.println(fail); throw new AssertionError(fail.toString()); } } }
FixLicenseHeaders
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaDurationWithMillisTest.java
{ "start": 2923, "end": 3287 }
class ____ { private static final Duration DURATION = Duration.ZERO.withMillis(42); } """) .doTest(); } @Test public void durationConstructorLongPrimitiveInsideJoda() { helper .addSourceLines( "TestClass.java", """ package org.joda.time; public
TestClass
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/hive/HiveCreateTableTest_15_pk.java
{ "start": 917, "end": 2554 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "create table pk(id1 integer, id2 integer,\n" + " primary key(id1, id2) disable novalidate);"; List<SQLStatement> statementList = SQLUtils.toStatementList(sql, JdbcConstants.HIVE); SQLStatement stmt = statementList.get(0); System.out.println(stmt.toString()); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.HIVE); stmt.accept(visitor); { String text = SQLUtils.toSQLString(stmt, JdbcConstants.HIVE); assertEquals("CREATE TABLE pk (\n" + "\tid1 integer,\n" + "\tid2 integer,\n" + "\tPRIMARY KEY (id1, id2) DISABLE NOVALIDATE\n" + ");", text); } System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); assertEquals(0, visitor.getOrderByColumns().size()); assertTrue(visitor.containsTable("pk")); } }
HiveCreateTableTest_15_pk
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/loadbalancer/ExceptionFailureStatistics.java
{ "start": 1098, "end": 2313 }
class ____ { private final Map<Class<?>, AtomicLong> counters = new HashMap<>(); private final AtomicLong fallbackCounter = new AtomicLong(); public void init(List<Class<?>> exceptions) { if (exceptions != null) { for (Class<?> exception : exceptions) { counters.put(exception, new AtomicLong()); } } } public Iterator<Class<?>> getExceptions() { return counters.keySet().iterator(); } public long getFailureCounter(Class<?> exception) { AtomicLong counter = counters.get(exception); if (counter != null) { return counter.get(); } else { return fallbackCounter.get(); } } public void onHandledFailure(Exception exception) { Class<?> clazz = exception.getClass(); AtomicLong counter = counters.get(clazz); if (counter != null) { counter.incrementAndGet(); } else { fallbackCounter.incrementAndGet(); } } public void reset() { for (AtomicLong counter : counters.values()) { counter.set(0); } fallbackCounter.set(0); } }
ExceptionFailureStatistics
java
elastic__elasticsearch
plugins/examples/stable-analysis/src/main/java/org/elasticsearch/example/analysis/ExampleAnalysisSettings.java
{ "start": 898, "end": 1002 }
interface ____ will be injected into a plugins' constructors * annotated with @Inject. * The settings
that
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutResponseValidatorParameters.java
{ "start": 950, "end": 2257 }
class ____ { private final Saml2LogoutResponse response; private final Saml2LogoutRequest request; private final RelyingPartyRegistration registration; /** * Construct a {@link Saml2LogoutRequestValidatorParameters} * @param response the SAML 2.0 Logout Response received from the asserting party * @param request the SAML 2.0 Logout Request send by this application * @param registration the associated {@link RelyingPartyRegistration} */ public Saml2LogoutResponseValidatorParameters(Saml2LogoutResponse response, Saml2LogoutRequest request, RelyingPartyRegistration registration) { this.response = response; this.request = request; this.registration = registration; } /** * The SAML 2.0 Logout Response received from the asserting party * @return the logout response */ public Saml2LogoutResponse getLogoutResponse() { return this.response; } /** * The SAML 2.0 Logout Request sent by this application * @return the logout request */ public Saml2LogoutRequest getLogoutRequest() { return this.request; } /** * The {@link RelyingPartyRegistration} representing this relying party * @return the relying party */ public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } }
Saml2LogoutResponseValidatorParameters
java
netty__netty
example/src/main/java/io/netty/example/http2/helloworld/frame/client/Http2FrameClient.java
{ "start": 2398, "end": 5950 }
class ____ { static final boolean SSL = System.getProperty("ssl") != null; static final String HOST = System.getProperty("host", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); static final String PATH = System.getProperty("path", "/"); private Http2FrameClient() { } public static void main(String[] args) throws Exception { EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); // Configure SSL. final SslContext sslCtx; if (SSL) { final SslProvider provider = SslProvider.isAlpnSupported(SslProvider.OPENSSL)? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient() .sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) // you probably won't want to use this in production, but it is fine for this example: .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } try { final Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(new Http2ClientFrameInitializer(sslCtx)); // Start the client. final Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); final Http2ClientStreamFrameResponseHandler streamFrameResponseHandler = new Http2ClientStreamFrameResponseHandler(); final Http2StreamChannelBootstrap streamChannelBootstrap = new Http2StreamChannelBootstrap(channel); final Http2StreamChannel streamChannel = streamChannelBootstrap.open().syncUninterruptibly().getNow(); streamChannel.pipeline().addLast(streamFrameResponseHandler); // Send request (a HTTP/2 HEADERS frame - with ':method = GET' in this case) final DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.method("GET"); headers.path(PATH); headers.scheme(SSL? "https" : "http"); final Http2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers, true); streamChannel.writeAndFlush(headersFrame); System.out.println("Sent HTTP/2 GET request to " + PATH); // Wait for the responses (or for the latch to expire), then clean up the connections if (!streamFrameResponseHandler.responseSuccessfullyCompleted()) { System.err.println("Did not get HTTP/2 response in expected time."); } System.out.println("Finished HTTP/2 request, will close the connection."); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { group.shutdownGracefully(); } } }
Http2FrameClient
java
elastic__elasticsearch
x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/action/TransportPutRollupJobAction.java
{ "start": 3614, "end": 18087 }
class ____ extends AcknowledgedTransportMasterNodeAction<PutRollupJobAction.Request> { private static final Logger LOGGER = LogManager.getLogger(TransportPutRollupJobAction.class); private static final DeprecationLogger DEPRECATION_LOGGER = DeprecationLogger.getLogger(TransportPutRollupJobAction.class); private static final XContentParserConfiguration PARSER_CONFIGURATION = XContentParserConfiguration.EMPTY.withFiltering( null, Set.of("_doc._meta._rollup"), null, false ); private final PersistentTasksService persistentTasksService; private final Client client; private final ProjectResolver projectResolver; @Inject public TransportPutRollupJobAction( TransportService transportService, ThreadPool threadPool, ActionFilters actionFilters, ClusterService clusterService, PersistentTasksService persistentTasksService, Client client, ProjectResolver projectResolver ) { super( PutRollupJobAction.NAME, transportService, clusterService, threadPool, actionFilters, PutRollupJobAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.persistentTasksService = persistentTasksService; this.client = client; this.projectResolver = projectResolver; } @Override protected void masterOperation( Task task, PutRollupJobAction.Request request, ClusterState clusterState, ActionListener<AcknowledgedResponse> listener ) { DEPRECATION_LOGGER.warn(DeprecationCategory.API, DEPRECATION_KEY, DEPRECATION_MESSAGE); XPackPlugin.checkReadyForXPackCustomMetadata(clusterState); checkForDeprecatedTZ(request); final var project = projectResolver.getProjectMetadata(clusterState); int numberOfCurrentRollupJobs = RollupUsageTransportAction.findNumberOfRollupJobs(project); if (numberOfCurrentRollupJobs == 0) { try { boolean hasRollupIndices = hasRollupIndices(project); if (hasRollupIndices == false) { listener.onFailure( new IllegalArgumentException( "new rollup jobs are not allowed in clusters that don't have any rollup usage, since rollup has been deprecated" ) ); return; } } catch (IOException e) { listener.onFailure(e); return; } } FieldCapabilitiesRequest fieldCapsRequest = new FieldCapabilitiesRequest().indices(request.indices()) .fields(request.getConfig().getAllFields().toArray(new String[0])); fieldCapsRequest.setParentTask(clusterService.localNode().getId(), task.getId()); final var projectId = project.id(); client.fieldCaps(fieldCapsRequest, listener.delegateFailure((l, fieldCapabilitiesResponse) -> { ActionRequestValidationException validationException = request.validateMappings(fieldCapabilitiesResponse.get()); if (validationException != null) { l.onFailure(validationException); return; } RollupJob job = createRollupJob(request.getConfig(), threadPool); createIndex(projectId, job, l, persistentTasksService, client, LOGGER); })); } static void checkForDeprecatedTZ(PutRollupJobAction.Request request) { String timeZone = request.getConfig().getGroupConfig().getDateHistogram().getTimeZone(); String modernTZ = DateUtils.DEPRECATED_LONG_TIMEZONES.get(timeZone); if (modernTZ != null) { DEPRECATION_LOGGER.warn( DeprecationCategory.PARSING, "deprecated_timezone", "Creating Rollup job [" + request.getConfig().getId() + "] with timezone [" + timeZone + "], but [" + timeZone + "] has been deprecated by the IANA. Use [" + modernTZ + "] instead." ); } } private RollupJob createRollupJob(RollupJobConfig config, ThreadPool threadPool) { // ensure we only filter for the allowed headers Map<String, String> filteredHeaders = ClientHelper.getPersistableSafeSecurityHeaders( threadPool.getThreadContext(), clusterService.state() ); return new RollupJob(config, filteredHeaders); } static void createIndex( ProjectId projectId, RollupJob job, ActionListener<AcknowledgedResponse> listener, PersistentTasksService persistentTasksService, Client client, Logger logger ) { CreateIndexRequest request = new CreateIndexRequest(job.getConfig().getRollupIndex()); try { XContentBuilder mapping = createMappings(job.getConfig()); request.source(mapping); } catch (IOException e) { listener.onFailure(e); return; } client.execute( TransportCreateIndexAction.TYPE, request, ActionListener.wrap(createIndexResponse -> startPersistentTask(projectId, job, listener, persistentTasksService), e -> { if (e instanceof ResourceAlreadyExistsException) { logger.debug("Rolled index already exists for rollup job [" + job.getConfig().getId() + "], updating metadata."); updateMapping(projectId, job, listener, persistentTasksService, client, logger, request.masterNodeTimeout()); } else { String msg = "Could not create index for rollup job [" + job.getConfig().getId() + "]"; logger.error(msg); listener.onFailure(new RuntimeException(msg, e)); } }) ); } static XContentBuilder createMappings(RollupJobConfig config) throws IOException { return XContentBuilder.builder(XContentType.JSON.xContent()) .startObject() .startObject("mappings") .startObject("_doc") .startObject("_meta") .field("rollup-version", "") // empty string to remain backwards compatible .startObject("_rollup") .field(config.getId(), config) .endObject() .endObject() .startArray("dynamic_templates") .startObject() .startObject("strings") .field("match_mapping_type", "string") .startObject("mapping") .field("type", "keyword") .endObject() .endObject() .endObject() .startObject() .startObject("date_histograms") .field("path_match", "*.date_histogram.timestamp") .startObject("mapping") .field("type", "date") .endObject() .endObject() .endObject() .endArray() .endObject() .endObject() .endObject(); } @SuppressWarnings("unchecked") static void updateMapping( ProjectId projectId, RollupJob job, ActionListener<AcknowledgedResponse> listener, PersistentTasksService persistentTasksService, Client client, Logger logger, TimeValue masterTimeout ) { final String indexName = job.getConfig().getRollupIndex(); CheckedConsumer<GetMappingsResponse, Exception> getMappingResponseHandler = getMappingResponse -> { MappingMetadata mappings = getMappingResponse.getMappings().get(indexName); Object m = mappings.getSourceAsMap().get("_meta"); if (m == null) { String msg = "Rollup data cannot be added to existing indices that contain non-rollup data (expected " + "to find _meta key in mapping of rollup index [" + indexName + "] but not found)."; logger.error(msg); listener.onFailure(new RuntimeException(msg)); return; } Map<String, Object> metadata = (Map<String, Object>) m; if (metadata.get(RollupField.ROLLUP_META) == null) { String msg = "Rollup data cannot be added to existing indices that contain non-rollup data (expected " + "to find rollup meta key [" + RollupField.ROLLUP_META + "] in mapping of rollup index [" + indexName + "] but not found)."; logger.error(msg); listener.onFailure(new RuntimeException(msg)); return; } Map<String, Object> rollupMeta = (Map<String, Object>) ((Map<String, Object>) m).get(RollupField.ROLLUP_META); if (rollupMeta.get(job.getConfig().getId()) != null) { String msg = "Cannot create rollup job [" + job.getConfig().getId() + "] because job was previously created (existing metadata)."; logger.error(msg); listener.onFailure(new ElasticsearchStatusException(msg, RestStatus.CONFLICT)); return; } rollupMeta.put(job.getConfig().getId(), job.getConfig()); metadata.put(RollupField.ROLLUP_META, rollupMeta); Map<String, Object> newMapping = mappings.getSourceAsMap(); newMapping.put("_meta", metadata); PutMappingRequest request = new PutMappingRequest(indexName); request.source(newMapping); client.execute( TransportPutMappingAction.TYPE, request, ActionListener.wrap( putMappingResponse -> startPersistentTask(projectId, job, listener, persistentTasksService), listener::onFailure ) ); }; GetMappingsRequest request = new GetMappingsRequest(masterTimeout); client.execute(GetMappingsAction.INSTANCE, request, ActionListener.wrap(getMappingResponseHandler, e -> { String msg = "Could not update mappings for rollup job [" + job.getConfig().getId() + "]"; logger.error(msg); listener.onFailure(new RuntimeException(msg, e)); })); } static void startPersistentTask( ProjectId projectId, RollupJob job, ActionListener<AcknowledgedResponse> listener, PersistentTasksService persistentTasksService ) { assertNoAuthorizationHeader(job.getHeaders()); persistentTasksService.sendProjectStartRequest( projectId, job.getConfig().getId(), RollupField.TASK_NAME, job, TimeValue.THIRTY_SECONDS /* TODO should this be configurable? longer by default? infinite? */, ActionListener.wrap(rollupConfigPersistentTask -> waitForRollupStarted(projectId, job, listener, persistentTasksService), e -> { if (e instanceof ResourceAlreadyExistsException) { e = new ElasticsearchStatusException( "Cannot create job [" + job.getConfig().getId() + "] because it has already been created (task exists)", RestStatus.CONFLICT, e ); } listener.onFailure(e); }) ); } private static void waitForRollupStarted( ProjectId projectId, RollupJob job, ActionListener<AcknowledgedResponse> listener, PersistentTasksService persistentTasksService ) { persistentTasksService.waitForPersistentTaskCondition( projectId, job.getConfig().getId(), Objects::nonNull, job.getConfig().getTimeout(), new PersistentTasksService.WaitForPersistentTaskListener<RollupJob>() { @Override public void onResponse(PersistentTasksCustomMetadata.PersistentTask<RollupJob> task) { listener.onResponse(AcknowledgedResponse.TRUE); } @Override public void onFailure(Exception e) { listener.onFailure(e); } @Override public void onTimeout(TimeValue timeout) { listener.onFailure( new ElasticsearchException( "Creation of task for Rollup Job ID [" + job.getConfig().getId() + "] timed out after [" + timeout + "]" ) ); } } ); } static boolean hasRollupIndices(ProjectMetadata project) throws IOException { // Sniffing logic instead of invoking sourceAsMap(), which would materialize the entire mapping as map of maps. for (var imd : project) { if (imd.mapping() == null) { continue; } try (var parser = XContentHelper.createParser(PARSER_CONFIGURATION, imd.mapping().source().compressedReference())) { if (parser.nextToken() == XContentParser.Token.START_OBJECT) { if ("_doc".equals(parser.nextFieldName())) { if (parser.nextToken() == XContentParser.Token.START_OBJECT) { if ("_meta".equals(parser.nextFieldName())) { if (parser.nextToken() == XContentParser.Token.START_OBJECT) { if ("_rollup".equals(parser.nextFieldName())) { return true; } } } } } } } } return false; } @Override protected ClusterBlockException checkBlock(PutRollupJobAction.Request request, ClusterState state) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE); } }
TransportPutRollupJobAction
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/builtin/XmlGregorianCalendarToJodaLocalDateTime.java
{ "start": 611, "end": 1519 }
class ____ extends BuiltInMethod { private final Parameter parameter; private final Type returnType; private final Set<Type> importTypes; public XmlGregorianCalendarToJodaLocalDateTime(TypeFactory typeFactory) { this.parameter = new Parameter( "xcal", typeFactory.getType( XmlConstants.JAVAX_XML_XML_GREGORIAN_CALENDAR ) ); this.returnType = typeFactory.getType( JodaTimeConstants.LOCAL_DATE_TIME_FQN ); this.importTypes = asSet( typeFactory.getType( XmlConstants.JAVAX_XML_DATATYPE_CONSTANTS ), returnType, parameter.getType() ); } @Override public Parameter getParameter() { return parameter; } @Override public Type getReturnType() { return returnType; } @Override public Set<Type> getImportTypes() { return importTypes; } }
XmlGregorianCalendarToJodaLocalDateTime
java
micronaut-projects__micronaut-core
http-client/src/test/groovy/io/micronaut/http/client/docs/streaming/Headline.java
{ "start": 705, "end": 879 }
class ____ { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }
Headline
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/onetoone/bidirectional/EntityWithBidirectionalOneToOneTest.java
{ "start": 21647, "end": 22696 }
class ____ { @Id private Integer id; @OneToOne private Mother biologicalMother; private String name; @OneToOne private Mother stepMother; AdoptedChild() { } AdoptedChild(Integer id, String name, Mother stepMother) { this.id = id; this.name = name; this.stepMother = stepMother; this.stepMother.setAdopted( this ); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Mother getBiologicalMother() { return biologicalMother; } public void setBiologicalMother(Mother biologicalMother) { this.biologicalMother = biologicalMother; } public Mother getStepMother() { return stepMother; } public void setStepMother(Mother stepMother) { this.stepMother = stepMother; } @Override public String toString() { return "AdoptedChild{" + "id=" + id + ", name='" + name + '\'' + '}'; } } }
AdoptedChild
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/WhatsAppWebhookProcessor.java
{ "start": 1285, "end": 4314 }
class ____ extends AsyncProcessorSupport implements AsyncProcessor { private static final Logger LOG = LoggerFactory.getLogger(WhatsAppWebhookProcessor.class); private static final String MODE_QUERY_PARAM = "hub.mode"; private static final String VERIFY_TOKEN_QUERY_PARAM = "hub.verify_token"; private static final String CHALLENGE_QUERY_PARAM = "hub.challenge"; private final WhatsAppConfiguration configuration; private AsyncProcessor next; public WhatsAppWebhookProcessor(Processor next, WhatsAppConfiguration configuration) { this.next = AsyncProcessorConverterHelper.convert(next); this.configuration = configuration; } @Override public boolean process(Exchange exchange, AsyncCallback callback) { String content; if ("GET".equalsIgnoreCase(exchange.getIn().getHeader(Exchange.HTTP_METHOD).toString())) { // Parse params from the webhook verification request Map<String, String> queryParams = parseQueryParam(exchange); String mode = queryParams.get(MODE_QUERY_PARAM); String token = queryParams.get(VERIFY_TOKEN_QUERY_PARAM); String challenge = queryParams.get(CHALLENGE_QUERY_PARAM); if (mode != null && token != null) { if ("subscribe".equals(mode) && token.equals(configuration.getWebhookVerifyToken())) { LOG.info("WhatsApp Webhook verified and subscribed"); content = challenge; } else { content = null; exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 403); } } else { LOG.error("{} or {} missing from request query param", MODE_QUERY_PARAM, VERIFY_TOKEN_QUERY_PARAM); content = null; exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 400); } } else { InputStream body = exchange.getIn().getBody(InputStream.class); try { content = new String(body.readAllBytes()); } catch (IOException e) { exchange.setException(e); callback.done(true); return true; } } exchange.getMessage().setBody(content); return next.process(exchange, doneSync -> { exchange.getMessage().setBody(content); callback.done(doneSync); }); } private Map<String, String> parseQueryParam(Exchange exchange) { Map<String, String> queryParams = new HashMap<>(); if (exchange.getIn().getHeader(Exchange.HTTP_QUERY) != null) { String[] pairs = exchange.getIn().getHeader(Exchange.HTTP_QUERY).toString().split("&"); for (String pair : pairs) { String[] keyValuePair = pair.split("="); queryParams.put(keyValuePair[0], keyValuePair[1]); } } return queryParams; } }
WhatsAppWebhookProcessor
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java
{ "start": 5934, "end": 7300 }
interface ____ a concrete class) without having * a fully capable TargetSource available. * @see #setTargetSource * @see #setTarget */ public void setTargetClass(@Nullable Class<?> targetClass) { this.targetSource = EmptyTargetSource.forClass(targetClass); } @Override public @Nullable Class<?> getTargetClass() { return this.targetSource.getTargetClass(); } @Override public void setPreFiltered(boolean preFiltered) { this.preFiltered = preFiltered; } @Override public boolean isPreFiltered() { return this.preFiltered; } /** * Set the advisor chain factory to use. * <p>Default is a {@link DefaultAdvisorChainFactory}. */ public void setAdvisorChainFactory(AdvisorChainFactory advisorChainFactory) { Assert.notNull(advisorChainFactory, "AdvisorChainFactory must not be null"); this.advisorChainFactory = advisorChainFactory; } /** * Return the advisor chain factory to use (never {@code null}). */ public AdvisorChainFactory getAdvisorChainFactory() { return this.advisorChainFactory; } /** * Set the interfaces to be proxied. */ public void setInterfaces(Class<?>... interfaces) { Assert.notNull(interfaces, "Interfaces must not be null"); this.interfaces.clear(); for (Class<?> ifc : interfaces) { addInterface(ifc); } } /** * Add a new proxied interface. * @param ifc the additional
or
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java
{ "start": 8947, "end": 9412 }
class ____ implements SessionInformationExpiredStrategy { @Override public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException { HttpServletResponse response = event.getResponse(); response.getWriter() .print("This session has been expired (possibly due to multiple concurrent " + "logins being attempted as the same user)."); response.flushBuffer(); } } }
ResponseBodySessionInformationExpiredStrategy
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/aggregateddeps/PkgPrivateEntryPointGenerator.java
{ "start": 1284, "end": 2004 }
class ____ { private final XProcessingEnv env; private final PkgPrivateMetadata metadata; PkgPrivateEntryPointGenerator(XProcessingEnv env, PkgPrivateMetadata metadata) { this.env = env; this.metadata = metadata; } // This method creates the following generated code for an EntryPoint in pkg.MyEntryPoint that is // package // private // // package pkg; //same package // // import dagger.hilt.InstallIn; // import dagger.hilt.EntryPoint;; // import javax.annotation.Generated; // // @Generated("dagger.hilt.processor.internal.aggregateddeps.PkgPrivateEntryPointGenerator") // @InstallIn(InstallIn.Component.ACTIVITY) // @EntryPoint // public final
PkgPrivateEntryPointGenerator
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/header/writers/frameoptions/RegExpAllowFromStrategyTests.java
{ "start": 1096, "end": 2574 }
class ____ { @Test public void invalidRegularExpressionShouldLeadToException() { assertThatExceptionOfType(PatternSyntaxException.class).isThrownBy(() -> new RegExpAllowFromStrategy("[a-z")); } @Test public void nullRegularExpressionShouldLeadToException() { assertThatIllegalArgumentException().isThrownBy(() -> new RegExpAllowFromStrategy(null)); } @Test public void subdomainMatchingRegularExpression() { RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^https://([a-z0-9]*?\\.)test\\.com"); strategy.setAllowFromParameterName("from"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("from", "https://www.test.com"); String result1 = strategy.getAllowFromValue(request); assertThat(result1).isEqualTo("https://www.test.com"); request.setParameter("from", "https://www.test.com"); String result2 = strategy.getAllowFromValue(request); assertThat(result2).isEqualTo("https://www.test.com"); request.setParameter("from", "https://test.foobar.com"); String result3 = strategy.getAllowFromValue(request); assertThat(result3).isEqualTo("DENY"); } @Test public void noParameterShouldDeny() { RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^https://([a-z0-9]*?\\.)test\\.com"); MockHttpServletRequest request = new MockHttpServletRequest(); String result1 = strategy.getAllowFromValue(request); assertThat(result1).isEqualTo("DENY"); } }
RegExpAllowFromStrategyTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/RefreshUserMappingsProtocol.java
{ "start": 1359, "end": 1879 }
interface ____ { /** * Version 1: Initial version. */ public static final long versionID = 1L; /** * Refresh user to group mappings. * @throws IOException raised on errors performing I/O. */ @Idempotent public void refreshUserToGroupsMappings() throws IOException; /** * Refresh superuser proxy group list * @throws IOException raised on errors performing I/O. */ @Idempotent public void refreshSuperUserGroupsConfiguration() throws IOException; }
RefreshUserMappingsProtocol
java
apache__flink
flink-filesystems/flink-oss-fs-hadoop/src/main/java/org/apache/flink/fs/osshadoop/writer/OSSRecoverableFsDataOutputStream.java
{ "start": 1499, "end": 1890 }
class ____ NOT thread-safe. Concurrent writes tho this stream result in corrupt or lost * data. * * <p>The {@link #close()} method may be called concurrently when cancelling / shutting down. It * will still ensure that local transient resources (like streams and temp files) are cleaned up, * but will not touch data previously persisted in OSS. */ @PublicEvolving @NotThreadSafe public
is
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson/OAuth2ErrorMixin.java
{ "start": 1534, "end": 1730 }
class ____ { @JsonCreator OAuth2ErrorMixin(@JsonProperty("errorCode") String errorCode, @JsonProperty("description") String description, @JsonProperty("uri") String uri) { } }
OAuth2ErrorMixin
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/Array.java
{ "start": 771, "end": 844 }
interface ____ { /// The maximum length of the array. int length(); }
Array
java
elastic__elasticsearch
x-pack/plugin/shutdown/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/NodeShutdownUpgradeIT.java
{ "start": 906, "end": 5461 }
class ____ extends AbstractUpgradeTestCase { List<String> namesSorted; Map<String, String> nodeNameToIdMap; @SuppressWarnings("unchecked") @Before public void init() throws IOException { final Request getNodesReq = new Request("GET", "_nodes"); final Response getNodesResp = adminClient().performRequest(getNodesReq); final Map<String, Map<String, Object>> nodes = (Map<String, Map<String, Object>>) entityAsMap(getNodesResp).get("nodes"); nodeNameToIdMap = nodes.entrySet().stream().collect(Collectors.toMap(e -> (String) (e.getValue().get("name")), e -> e.getKey())); namesSorted = nodeNameToIdMap.keySet().stream().sorted().collect(Collectors.toList()); } public void testShutdown() throws Exception { String nodeIdToShutdown; switch (CLUSTER_TYPE) { case OLD: nodeIdToShutdown = nodeIdToShutdown(0); assertOK(client().performRequest(shutdownNode(nodeIdToShutdown))); assertBusy(() -> assertThat(getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0)))); break; case MIXED: if (FIRST_MIXED_ROUND) { // after upgrade the record still exist assertBusy(() -> assertThat(getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0)))); nodeIdToShutdown = nodeIdToShutdown(1); assertOK(client().performRequest(shutdownNode(nodeIdToShutdown))); assertBusy( () -> assertThat( getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0), shutdownStatusCompleteFor(1)) ) ); } else { assertBusy( () -> assertThat( getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0), shutdownStatusCompleteFor(1)) ) ); nodeIdToShutdown = nodeIdToShutdown(2); assertOK(client().performRequest(shutdownNode(nodeIdToShutdown))); assertBusy( () -> assertThat( getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0), shutdownStatusCompleteFor(1), shutdownStatusCompleteFor(2)) ) ); } break; case UPGRADED: assertBusy( () -> assertThat( getShutdownStatus(), containsInAnyOrder(shutdownStatusCompleteFor(0), shutdownStatusCompleteFor(1), shutdownStatusCompleteFor(2)) ) ); break; default: throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); } } private Matcher<Map<String, Object>> shutdownStatusCompleteFor(int i) { return allOf( hasEntry("node_id", nodeIdToShutdown(i)), hasEntry("reason", this.getTestName()), hasEntry("status", SingleNodeShutdownMetadata.Status.COMPLETE.toString()) ); } @SuppressWarnings("unchecked") private List<Map<String, Object>> getShutdownStatus() throws IOException { final Request getShutdownsReq = new Request("GET", "_nodes/shutdown"); final Response getShutdownsResp = client().performRequest(getShutdownsReq); return (List<Map<String, Object>>) entityAsMap(getShutdownsResp).get("nodes"); } private Request shutdownNode(String nodeIdToShutdown) throws IOException { final Request putShutdownRequest = new Request("PUT", "_nodes/" + nodeIdToShutdown + "/shutdown"); try (XContentBuilder putBody = JsonXContent.contentBuilder()) { putBody.startObject(); { putBody.field("type", "restart"); putBody.field("reason", this.getTestName()); } putBody.endObject(); putShutdownRequest.setJsonEntity(Strings.toString(putBody)); } return putShutdownRequest; } private String nodeIdToShutdown(int nodeNumber) { final String nodeName = namesSorted.get(nodeNumber); return nodeNameToIdMap.get(nodeName); } }
NodeShutdownUpgradeIT
java
netty__netty
common/src/main/java/io/netty/util/internal/logging/FormattingTuple.java
{ "start": 1970, "end": 2346 }
class ____ { private final String message; private final Throwable throwable; public FormattingTuple(String message, Throwable throwable) { this.message = message; this.throwable = throwable; } public String getMessage() { return message; } public Throwable getThrowable() { return throwable; } }
FormattingTuple
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/uninstallmodules/UninstallModulesProcessor.java
{ "start": 1191, "end": 1402 }
class ____ extends JavacBaseProcessingStepProcessor { @Override protected BaseProcessingStep processingStep() { return new UninstallModulesProcessingStep(getXProcessingEnv()); } }
UninstallModulesProcessor
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/expressions/AbstractEvaluatedExpression.java
{ "start": 1005, "end": 1179 }
class ____ subclassed * by evaluated expressions classes at compilation time. * * @author Sergey Gavrilov * @since 4.0.0 */ @Internal @UsedByGeneratedCode public abstract
is
java
elastic__elasticsearch
modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/SearchTemplateResponse.java
{ "start": 1230, "end": 3912 }
class ____ extends ActionResponse implements ToXContentObject { public static final ParseField TEMPLATE_OUTPUT_FIELD = new ParseField("template_output"); /** Contains the source of the rendered template **/ private BytesReference source; /** Contains the search response, if any **/ private SearchResponse response; private final RefCounted refCounted = LeakTracker.wrap(new AbstractRefCounted() { @Override protected void closeInternal() { if (response != null) { response.decRef(); } } }); SearchTemplateResponse() {} public BytesReference getSource() { return source; } public void setSource(BytesReference source) { this.source = source; } public SearchResponse getResponse() { return response; } public void setResponse(SearchResponse searchResponse) { this.response = searchResponse; } public boolean hasResponse() { return response != null; } @Override public String toString() { return "SearchTemplateResponse [source=" + source + ", response=" + response + "]"; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalBytesReference(source); out.writeOptionalWriteable(response); } @Override public void incRef() { refCounted.incRef(); } @Override public boolean tryIncRef() { return refCounted.tryIncRef(); } @Override public boolean decRef() { return refCounted.decRef(); } @Override public boolean hasReferences() { return refCounted.hasReferences(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); innerToXContent(builder, params); builder.endObject(); return builder; } void innerToXContent(XContentBuilder builder, Params params) throws IOException { if (hasResponse()) { ChunkedToXContent.wrapAsToXContent(response::innerToXContentChunked).toXContent(builder, params); } else { // we can assume the template is always json as we convert it before compiling it try (InputStream stream = source.streamInput()) { builder.rawField(TEMPLATE_OUTPUT_FIELD.getPreferredName(), stream, XContentType.JSON); } } } public RestStatus status() { if (hasResponse()) { return response.status(); } else { return RestStatus.OK; } } }
SearchTemplateResponse
java
square__retrofit
retrofit/src/main/java/retrofit2/Reflection.java
{ "start": 1283, "end": 2379 }
class ____ extends Reflection { @Override boolean isDefaultMethod(Method method) { return method.isDefault(); } @Override Object invokeDefaultMethod( Method method, Class<?> declaringClass, Object proxy, @Nullable Object[] args) throws Throwable { return DefaultMethodSupport.invoke(method, declaringClass, proxy, args); } @Override String describeMethodParameter(Method method, int index) { Parameter parameter = method.getParameters()[index]; if (parameter.isNamePresent()) { return "parameter '" + parameter.getName() + '\''; } return super.describeMethodParameter(method, index); } } /** * Android does not support MR jars, so this uses the Java 8 support class. * Default methods and the reflection API to detect them were added to API 24 * as part of the initial Java 8 set. MethodHandle, our means of invoking the default method * through the proxy, was not added until API 26. */ @TargetApi(24) @IgnoreJRERequirement // Only used on Android API 24+. static final
Java8
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/LayeredSpec.java
{ "start": 10440, "end": 10748 }
class ____ implements Function<String, IntoLayerSpec>, Serializable { @Override public IntoLayerSpec apply(String layer) { return new IntoLayerSpec(layer); } } } /** * An {@link IntoLayersSpec} that controls the layers to which dependencies belong. */ public static
IntoLayerSpecFactory
java
quarkusio__quarkus
independent-projects/qute/debug/src/main/java/io/quarkus/qute/debug/DebuggerException.java
{ "start": 522, "end": 1117 }
class ____ extends RuntimeException { /** * Creates a new {@link DebuggerException} with the specified cause. * * @param e the underlying cause of this exception, may be {@code null} */ public DebuggerException(Throwable e) { super(e); } /** * Creates a new {@link DebuggerException} without any message or cause. * <p> * This constructor is typically used when the context of the error * is sufficient to identify the problem without additional details. * </p> */ public DebuggerException() { } }
DebuggerException
java
apache__maven
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/cisupport/CIDetectorHelper.java
{ "start": 1307, "end": 1913 }
class ____ { private CIDetectorHelper() {} public static List<CIInfo> detectCI() { ArrayList<CIInfo> result = ServiceLoader.load(CIDetector.class).stream() .map(ServiceLoader.Provider::get) .map(CIDetector::detectCI) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toCollection(ArrayList::new)); if (result.size() > 1) { // remove generic result.removeIf(c -> GenericCIDetector.NAME.equals(c.name())); } return result; } }
CIDetectorHelper
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/execution/ProjectExecutionListener.java
{ "start": 1228, "end": 1644 }
interface ____ { void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException; void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException; void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException; void afterProjectExecutionFailure(ProjectExecutionEvent event); }
ProjectExecutionListener
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/pkg/jar/UberJarBuilder.java
{ "start": 1861, "end": 15280 }
class ____ extends AbstractJarBuilder<JarBuildItem> { private static final Logger LOG = Logger.getLogger(UberJarBuilder.class); private static final Predicate<String> UBER_JAR_IGNORED_ENTRIES_PREDICATE = new IsEntryIgnoredForUberJarPredicate(); private static final Predicate<String> UBER_JAR_CONCATENATED_ENTRIES_PREDICATE = new Predicate<>() { @Override public boolean test(String path) { return "META-INF/io.netty.versions.properties".equals(path) || (path.startsWith("META-INF/services/") && path.length() > 18) || // needed to initialize the CLI bootstrap Maven resolver "META-INF/sisu/javax.inject.Named".equals(path); } }; private final List<UberJarMergedResourceBuildItem> mergedResources; private final List<UberJarIgnoredResourceBuildItem> ignoredResources; public UberJarBuilder(CurateOutcomeBuildItem curateOutcome, OutputTargetBuildItem outputTarget, ApplicationInfoBuildItem applicationInfo, PackageConfig packageConfig, MainClassBuildItem mainClass, ApplicationArchivesBuildItem applicationArchives, TransformedClassesBuildItem transformedClasses, List<GeneratedClassBuildItem> generatedClasses, List<GeneratedResourceBuildItem> generatedResources, Set<ArtifactKey> removedArtifactKeys, List<UberJarMergedResourceBuildItem> mergedResources, List<UberJarIgnoredResourceBuildItem> ignoredResources) { super(curateOutcome, outputTarget, applicationInfo, packageConfig, mainClass, applicationArchives, transformedClasses, generatedClasses, generatedResources, removedArtifactKeys); this.mergedResources = mergedResources; this.ignoredResources = ignoredResources; } @Override public JarBuildItem build() throws IOException { //we use the -runner jar name, unless we are building both types final Path runnerJar = outputTarget.getOutputDirectory() .resolve(outputTarget.getBaseName() + packageConfig.computedRunnerSuffix() + DOT_JAR); // If the runner jar appears to exist already we create a new one with a tmp suffix. // Deleting an existing runner jar may result in deleting the original (non-runner) jar (in case the runner suffix is empty) // which is used as a source of content for the runner jar. final Path tmpRunnerJar; if (Files.exists(runnerJar)) { tmpRunnerJar = outputTarget.getOutputDirectory() .resolve(outputTarget.getBaseName() + packageConfig.computedRunnerSuffix() + ".tmp"); Files.deleteIfExists(tmpRunnerJar); } else { tmpRunnerJar = runnerJar; } buildUberJar0(tmpRunnerJar); if (tmpRunnerJar != runnerJar) { Files.copy(tmpRunnerJar, runnerJar, StandardCopyOption.REPLACE_EXISTING); tmpRunnerJar.toFile().deleteOnExit(); } //for uberjars we move the original jar, so there is only a single jar in the output directory final Path standardJar = outputTarget.getOutputDirectory() .resolve(outputTarget.getOriginalBaseName() + DOT_JAR); final Path originalJar = Files.exists(standardJar) ? standardJar : null; ResolvedDependency appArtifact = curateOutcome.getApplicationModel().getAppArtifact(); final String classifier = suffixToClassifier(packageConfig.computedRunnerSuffix()); if (classifier != null && !classifier.isEmpty()) { appArtifact = ResolvedDependencyBuilder.newInstance() .setGroupId(appArtifact.getGroupId()) .setArtifactId(appArtifact.getArtifactId()) .setClassifier(classifier) .setType(appArtifact.getType()) .setVersion(appArtifact.getVersion()) .setResolvedPaths(appArtifact.getResolvedPaths()) .addDependencies(appArtifact.getDependencies()) .setWorkspaceModule(appArtifact.getWorkspaceModule()) .setFlags(appArtifact.getFlags()) .build(); } final ApplicationManifestConfig manifestConfig = ApplicationManifestConfig.builder() .setMainComponent(ApplicationComponent.builder() .setPath(runnerJar) .setResolvedDependency(appArtifact) .build()) .setRunnerPath(runnerJar) .addComponents(curateOutcome.getApplicationModel().getDependencies()) .build(); return new JarBuildItem(runnerJar, originalJar, null, UBER_JAR, suffixToClassifier(packageConfig.computedRunnerSuffix()), manifestConfig); } private void buildUberJar0(Path runnerJar) throws IOException { try (ZipFileSystemArchiveCreator archiveCreator = new ZipFileSystemArchiveCreator(runnerJar, packageConfig.jar().compress(), packageConfig.outputTimestamp().orElse(null))) { LOG.info("Building uber jar: " + runnerJar); final Map<String, String> seen = new HashMap<>(); final Map<String, Set<Dependency>> duplicateCatcher = new HashMap<>(); final Map<String, List<byte[]>> concatenatedEntries = new HashMap<>(); final Set<String> mergeResourcePaths = mergedResources.stream() .map(UberJarMergedResourceBuildItem::getPath) .collect(Collectors.toSet()); Set<String> ignoredEntries = new HashSet<>(); packageConfig.jar().userConfiguredIgnoredEntries().ifPresent(ignoredEntries::addAll); ignoredResources.stream() .map(UberJarIgnoredResourceBuildItem::getPath) .forEach(ignoredEntries::add); Predicate<String> allIgnoredEntriesPredicate = new Predicate<String>() { @Override public boolean test(String path) { return UBER_JAR_IGNORED_ENTRIES_PREDICATE.test(path) || ignoredEntries.contains(path); } }; ResolvedDependency appArtifact = curateOutcome.getApplicationModel().getAppArtifact(); // the manifest needs to be the first entry in the jar, otherwise JarInputStream does not work properly // see https://bugs.openjdk.java.net/browse/JDK-8031748 generateManifest(archiveCreator, "", packageConfig, appArtifact, mainClass.getClassName(), applicationInfo); for (ResolvedDependency appDep : curateOutcome.getApplicationModel().getRuntimeDependencies()) { // Exclude files that are not jars (typically, we can have XML files here, see https://github.com/quarkusio/quarkus/issues/2852) // and are not part of the optional dependencies to include if (!includeAppDependency(appDep, outputTarget.getIncludedOptionalDependencies(), removedArtifactKeys)) { continue; } for (Path resolvedDep : appDep.getResolvedPaths()) { Set<String> existingEntries = new HashSet<>(); Set<String> transformedFilesByJar = transformedClasses.getTransformedFilesByJar().get(resolvedDep); if (transformedFilesByJar != null) { existingEntries.addAll(transformedFilesByJar); } generatedResources.stream() .map(GeneratedResourceBuildItem::getName) .forEach(existingEntries::add); if (!Files.isDirectory(resolvedDep)) { try (FileSystem artifactFs = ZipUtils.newFileSystem(resolvedDep)) { for (final Path root : artifactFs.getRootDirectories()) { walkFileDependencyForDependency(root, archiveCreator, duplicateCatcher, concatenatedEntries, allIgnoredEntriesPredicate, appDep, existingEntries, mergeResourcePaths); } } } else { walkFileDependencyForDependency(resolvedDep, archiveCreator, duplicateCatcher, concatenatedEntries, allIgnoredEntriesPredicate, appDep, existingEntries, mergeResourcePaths); } } } Set<Set<Dependency>> explained = new HashSet<>(); for (Map.Entry<String, Set<Dependency>> entry : duplicateCatcher.entrySet()) { if (entry.getValue().size() > 1) { if (explained.add(entry.getValue())) { LOG.warn("Dependencies with duplicate files detected. The dependencies " + entry.getValue() + " contain duplicate files, e.g. " + entry.getKey()); } } } copyCommonContent(archiveCreator, concatenatedEntries, allIgnoredEntriesPredicate); // now that all entries have been added, check if there's a META-INF/versions/ entry. If present, // mark this jar as multi-release jar. Strictly speaking, the jar spec expects META-INF/versions/N // directory where N is an integer greater than 8, but we don't do that level of checks here but that // should be OK. if (archiveCreator.isMultiVersion()) { LOG.debug("uber jar will be marked as multi-release jar"); archiveCreator.makeMultiVersion(); } } runnerJar.toFile().setReadable(true, false); } private void walkFileDependencyForDependency(Path root, ArchiveCreator archiveCreator, Map<String, Set<Dependency>> duplicateCatcher, Map<String, List<byte[]>> concatenatedEntries, Predicate<String> ignoredEntriesPredicate, Dependency appDep, Set<String> existingEntries, Set<String> mergeResourcePaths) throws IOException { final Path metaInfDir = root.resolve("META-INF"); Files.walkFileTree(root, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final String relativePath = toUri(root.relativize(dir)); if (!relativePath.isEmpty()) { archiveCreator.addDirectory(relativePath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { final String relativePath = toUri(root.relativize(file)); //if this has been transformed we do not copy it // if it's a signature file (under the <jar>/META-INF directory), // then we don't add it to the uber jar if (isBlockOrSF(relativePath) && file.relativize(metaInfDir).getNameCount() == 1) { if (LOG.isDebugEnabled()) { LOG.debug("Signature file " + file.toAbsolutePath() + " from app " + "dependency " + appDep + " will not be included in uberjar"); } return FileVisitResult.CONTINUE; } if (!existingEntries.contains(relativePath)) { if (UBER_JAR_CONCATENATED_ENTRIES_PREDICATE.test(relativePath) || mergeResourcePaths.contains(relativePath)) { concatenatedEntries.computeIfAbsent(relativePath, (u) -> new ArrayList<>()) .add(Files.readAllBytes(file)); return FileVisitResult.CONTINUE; } else if (!ignoredEntriesPredicate.test(relativePath)) { duplicateCatcher.computeIfAbsent(relativePath, (a) -> new HashSet<>()) .add(appDep); archiveCreator.addFileIfNotExists(file, relativePath, appDep.toString()); } } return FileVisitResult.CONTINUE; } }); } // same as the impl in sun.security.util.SignatureFileVerifier#isBlockOrSF() private static boolean isBlockOrSF(final String s) { if (s == null) { return false; } return s.endsWith(".SF") || s.endsWith(".DSA") || s.endsWith(".RSA") || s.endsWith(".EC"); } private static
UberJarBuilder
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/CompositeSerializer.java
{ "start": 7519, "end": 7660 }
class ____ composite serializer parameters which can be precomputed in advanced for * better performance. */ protected static
holds
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumPostgresEndpointBuilderFactory.java
{ "start": 129030, "end": 131394 }
interface ____ { /** * Debezium PostgresSQL Connector (camel-debezium-postgres) * Capture changes from a PostgresSQL database. * * Category: database * Since: 3.0 * Maven coordinates: org.apache.camel:camel-debezium-postgres * * @return the dsl builder for the headers' name. */ default DebeziumPostgresHeaderNameBuilder debeziumPostgres() { return DebeziumPostgresHeaderNameBuilder.INSTANCE; } /** * Debezium PostgresSQL Connector (camel-debezium-postgres) * Capture changes from a PostgresSQL database. * * Category: database * Since: 3.0 * Maven coordinates: org.apache.camel:camel-debezium-postgres * * Syntax: <code>debezium-postgres:name</code> * * Path parameter: name (required) * Unique name for the connector. Attempting to register again with the * same name will fail. * * @param path name * @return the dsl builder */ default DebeziumPostgresEndpointBuilder debeziumPostgres(String path) { return DebeziumPostgresEndpointBuilderFactory.endpointBuilder("debezium-postgres", path); } /** * Debezium PostgresSQL Connector (camel-debezium-postgres) * Capture changes from a PostgresSQL database. * * Category: database * Since: 3.0 * Maven coordinates: org.apache.camel:camel-debezium-postgres * * Syntax: <code>debezium-postgres:name</code> * * Path parameter: name (required) * Unique name for the connector. Attempting to register again with the * same name will fail. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path name * @return the dsl builder */ default DebeziumPostgresEndpointBuilder debeziumPostgres(String componentName, String path) { return DebeziumPostgresEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Debezium PostgresSQL Connector component. */ public static
DebeziumPostgresBuilders
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/reflect/FastMember.java
{ "start": 757, "end": 1767 }
class ____ { protected FastClass fc; protected Member member; protected int index; protected FastMember(FastClass fc, Member member, int index) { this.fc = fc; this.member = member; this.index = index; } abstract public Class[] getParameterTypes(); abstract public Class[] getExceptionTypes(); public int getIndex() { return index; } public String getName() { return member.getName(); } public Class getDeclaringClass() { return fc.getJavaClass(); } public int getModifiers() { return member.getModifiers(); } @Override public String toString() { return member.toString(); } @Override public int hashCode() { return member.hashCode(); } @Override public boolean equals(Object o) { if (o == null || !(o instanceof FastMember other)) { return false; } return member.equals(other.member); } }
FastMember
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/prefetch/TestS3ABlockManager.java
{ "start": 1237, "end": 3020 }
class ____ extends AbstractHadoopTestBase { static final int FILE_SIZE = 12; static final int BLOCK_SIZE = 3; @Test public void testArgChecks() throws Exception { BlockData blockData = new BlockData(FILE_SIZE, BLOCK_SIZE); MockS3ARemoteObject s3File = new MockS3ARemoteObject(FILE_SIZE, false); S3ARemoteObjectReader reader = new S3ARemoteObjectReader(s3File); // Should not throw. new S3ABlockManager(reader, blockData); // Verify it throws correctly. intercept( IllegalArgumentException.class, "'reader' must not be null", () -> new S3ABlockManager(null, blockData)); intercept( IllegalArgumentException.class, "'blockData' must not be null", () -> new S3ABlockManager(reader, null)); intercept( IllegalArgumentException.class, "'blockNumber' must not be negative", () -> new S3ABlockManager(reader, blockData).get(-1)); intercept( IllegalArgumentException.class, "'data' must not be null", () -> new S3ABlockManager(reader, blockData).release(null)); } @Test public void testGet() throws IOException { BlockData blockData = new BlockData(FILE_SIZE, BLOCK_SIZE); MockS3ARemoteObject s3File = new MockS3ARemoteObject(FILE_SIZE, false); S3ARemoteObjectReader reader = new S3ARemoteObjectReader(s3File); S3ABlockManager blockManager = new S3ABlockManager(reader, blockData); for (int b = 0; b < blockData.getNumBlocks(); b++) { BufferData data = blockManager.get(b); ByteBuffer buffer = data.getBuffer(); long startOffset = blockData.getStartOffset(b); for (int i = 0; i < BLOCK_SIZE; i++) { assertEquals(startOffset + i, buffer.get()); } } } }
TestS3ABlockManager
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idgen/n_ative/GeneratorSettingsImpl.java
{ "start": 550, "end": 1695 }
class ____ implements GeneratorSettings { private final String defaultCatalog; private final String defaultSchema; private final SqlStringGenerationContext sqlStringGenerationContext; public GeneratorSettingsImpl(Metadata domainModel) { final Database database = domainModel.getDatabase(); final Namespace defaultNamespace = database.getDefaultNamespace(); final Namespace.Name defaultNamespaceName = defaultNamespace.getName(); defaultCatalog = defaultNamespaceName.catalog() == null ? "" : defaultNamespaceName.catalog().render( database.getDialect() ); defaultSchema = defaultNamespaceName.schema() == null ? "" : defaultNamespaceName.schema().render( database.getDialect() ); sqlStringGenerationContext = fromExplicit( database.getJdbcEnvironment(), database, defaultCatalog, defaultSchema ); } @Override public String getDefaultCatalog() { return defaultCatalog; } @Override public String getDefaultSchema() { return defaultSchema; } @Override public SqlStringGenerationContext getSqlStringGenerationContext() { return sqlStringGenerationContext; } }
GeneratorSettingsImpl
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/convert/converters/MultiValuesConverterFactory.java
{ "start": 15857, "end": 19016 }
class ____ extends AbstractConverterFromMultiValues<Iterable> { public MultiValuesToIterableConverter(ConversionService conversionService) { super(conversionService); } @Override protected Optional<Iterable> retrieveSeparatedValue(ArgumentConversionContext<Iterable> conversionContext, String name, ConvertibleMultiValues<String> parameters, String defaultValue, Character delimiter ) { List<String> values = parameters.getAll(name); if (values.isEmpty() && defaultValue != null) { values.add(defaultValue); } List<String> result = new ArrayList<>(values.size()); for (String value: values) { result.addAll(splitByDelimiter(value, delimiter)); } return convertValues(conversionContext, result); } @Override protected Optional<Iterable> retrieveMultiValue(ArgumentConversionContext<Iterable> conversionContext, String name, ConvertibleMultiValues<String> parameters) { List<String> values = parameters.getAll(name); return convertValues(conversionContext, values); } @Override protected Optional<Iterable> retrieveDeepObjectValue(ArgumentConversionContext<Iterable> conversionContext, String name, ConvertibleMultiValues<String> parameters) { List<String> values = new ArrayList<>(); for (int i = 0;; ++i) { String key = name + '[' + i + ']'; String value = parameters.get(key); if (value == null) { break; } values.add(value); } return convertValues(conversionContext, values); } private Optional<Iterable> convertValues(ArgumentConversionContext<Iterable> context, List<String> values) { Argument<?> typeArgument = context.getArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT); List convertedValues; // Convert all the values if (typeArgument.getType().isAssignableFrom(String.class)) { convertedValues = values; } else { ArgumentConversionContext<?> argumentConversionContext = ConversionContext.of(typeArgument); convertedValues = new ArrayList<>(values.size()); for (String value: values) { conversionService.convert(value, argumentConversionContext).ifPresent(convertedValues::add); } } // Convert the collection itself return CollectionUtils.convertCollection((Class) context.getArgument().getType(), convertedValues); } } /** * A converter to convert from {@link ConvertibleMultiValues} to an {@link Map}. */ public static
MultiValuesToIterableConverter
java
quarkusio__quarkus
integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/StaticResourcesTest.java
{ "start": 177, "end": 893 }
class ____ { @Test public void testExisting() { when().get("/test.txt").then().statusCode(200); } @Test public void testNonExisting() { when().get("/test2.txt").then().statusCode(404); } @Test public void testIndexInDirectory() { when().get("/dummy/").then().statusCode(200); } @Test public void testIndexInNestedDirectory() { when().get("/l1/l2/").then().statusCode(200); } @Test public void testNonIndexInDirectory() { when().get("/dummy2/").then().statusCode(404); } @Test public void testIndexInNonExistingDirectory() { when().get("/dummy3/").then().statusCode(404); } }
StaticResourcesTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/scheduler/SingleWorkerAroundTimerSchedulerTest.java
{ "start": 720, "end": 1481 }
class ____ extends AbstractSchedulerTest { @Override protected boolean shouldCheckDisposeTask() { return false; } @Override protected boolean shouldCheckWorkerTimeScheduling() { return false; } @Override protected boolean shouldCheckSupportRestart() { return false; } @Override protected boolean shouldCheckInit() { return false; } @Override protected Scheduler scheduler() { return Schedulers.single(Schedulers.newSingle("singleWorkerTimer")); } @Override protected Scheduler freshScheduler() { return Schedulers.single(Schedulers.factory.newSingle(new ReactorThreadFactory( "SingleSchedulerTest", SingleScheduler.COUNTER, false, true, Schedulers::defaultUncaughtException ))); } }
SingleWorkerAroundTimerSchedulerTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetTimes.java
{ "start": 1923, "end": 1975 }
class ____ the access time on files. * */ public
tests
java
apache__camel
components/camel-cxf/camel-cxf-common/src/generated/java/org/apache/camel/component/cxf/converter/CxfPayloadConverterLoader.java
{ "start": 889, "end": 6303 }
class ____ implements TypeConverterLoader, CamelContextAware { private CamelContext camelContext; public CxfPayloadConverterLoader() { } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { registerConverters(registry); registerFallbackConverters(registry); } private void registerConverters(TypeConverterRegistry registry) { addTypeConverter(registry, javax.xml.transform.Source.class, org.apache.camel.component.cxf.common.CxfPayload.class, true, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.cxfPayLoadToSource((org.apache.camel.component.cxf.common.CxfPayload) value, exchange); if (true && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.apache.camel.StreamCache.class, org.apache.camel.component.cxf.common.CxfPayload.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.cxfPayLoadToStreamCache((org.apache.camel.component.cxf.common.CxfPayload) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.apache.camel.component.cxf.common.CxfPayload.class, javax.xml.transform.Source.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.sourceToCxfPayload((javax.xml.transform.Source) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.apache.camel.component.cxf.common.CxfPayload.class, org.w3c.dom.Document.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.documentToCxfPayload((org.w3c.dom.Document) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.apache.camel.component.cxf.common.CxfPayload.class, org.w3c.dom.Element.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.elementToCxfPayload((org.w3c.dom.Element) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.apache.camel.component.cxf.common.CxfPayload.class, org.w3c.dom.NodeList.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.nodeListToCxfPayload((org.w3c.dom.NodeList) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.w3c.dom.Node.class, org.apache.camel.component.cxf.common.CxfPayload.class, true, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.cxfPayLoadToNode((org.apache.camel.component.cxf.common.CxfPayload) value, exchange); if (true && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.w3c.dom.NodeList.class, org.apache.camel.component.cxf.common.CxfPayload.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.cxf.converter.CxfPayloadConverter.cxfPayloadToNodeList((org.apache.camel.component.cxf.common.CxfPayload) value, exchange); if (false && answer == null) { answer = Void.class; } return answer; }); } private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) { registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method)); } private void registerFallbackConverters(TypeConverterRegistry registry) { addFallbackTypeConverter(registry, false, false, (type, exchange, value) -> org.apache.camel.component.cxf.converter.CxfPayloadConverter.convertTo(type, exchange, value, registry)); } private static void addFallbackTypeConverter(TypeConverterRegistry registry, boolean allowNull, boolean canPromote, SimpleTypeConverter.ConversionMethod method) { registry.addFallbackTypeConverter(new SimpleTypeConverter(allowNull, method), canPromote); } }
CxfPayloadConverterLoader
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/ValidatingPluginWithGenericBuilder.java
{ "start": 2023, "end": 2685 }
class ____<B extends Builder<B>> implements org.apache.logging.log4j.core.util.Builder<ValidatingPluginWithGenericBuilder> { @PluginBuilderAttribute @Required(message = "The name given by the builder is null") private String name; public B setName(final String name) { this.name = name; return asBuilder(); } @SuppressWarnings("unchecked") public B asBuilder() { return (B) this; } @Override public ValidatingPluginWithGenericBuilder build() { return new ValidatingPluginWithGenericBuilder(name); } } }
Builder
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/PropertyBindingSupportConfigurerTest.java
{ "start": 11878, "end": 13365 }
class ____ { private int age; private boolean rider; private Company work; // has no default value but Camel can automatic // create one if there is a setter private boolean goldCustomer; private Map<String, String> products; // no default value - should auto-create this via the setter public int getAge() { return age; } public boolean isRider() { return rider; } public Company getWork() { return work; } public boolean isGoldCustomer() { return goldCustomer; } public Map<String, String> getProducts() { return products; } public void setProducts(Map<String, String> products) { this.products = products; } // this has no setter but only builders // and mix the builders with both styles (with as prefix and no prefix // at all) public Bar withAge(int age) { this.age = age; return this; } public Bar withRider(boolean rider) { this.rider = rider; return this; } public Bar work(Company work) { this.work = work; return this; } public Bar goldCustomer(boolean goldCustomer) { this.goldCustomer = goldCustomer; return this; } } private static
Bar
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java
{ "start": 29987, "end": 30106 }
class ____ { BeanB b; BeanC c; public BeanA(BeanB b, BeanC c) { this.b = b; this.c = c; } } static
BeanA
java
google__guice
core/src/com/google/inject/internal/InternalFactory.java
{ "start": 1018, "end": 3063 }
class ____<T> { /** * Accessed in a double checked manner and updated under the `this` lock. See {@link * HandleCache#getHandleAndMaybeUpdateCache(boolean, MethodHandleResult)} */ private volatile HandleCache handleCache = HandleCache.EMPTY; /** * Creates an object to be injected. * * @param context of this injection * @param linked true if getting as a result of a linked binding * @throws com.google.inject.internal.InternalProvisionException if a value cannot be provided * @return instance that was created */ abstract T get(InternalContext context, Dependency<?> dependency, boolean linked) throws InternalProvisionException; /** Returns a provider for the object to be injected. */ Provider<T> makeProvider(InjectorImpl injector, Dependency<?> dependency) { return makeDefaultProvider(this, injector, dependency); } /** * Returns the method handle for the object to be injected. * * <p>The signature of the method handle is {@code (InternalContext) -> T} where `T` is the type * of the object to be injected as determined by the {@link Dependency}. * * @param context the linkage context * @param linked true if getting as a result of a linked binding * @return the method handle for the object to be injected */ final MethodHandle getHandle(LinkageContext context, boolean linked) { var currentCache = handleCache; var local = currentCache.getHandle(linked); if (local != null) { return local; } // NOTE: we do not hold a lock while actually constructing the handle, instead we atomically // update the handleCache using double-checked locking. The `updateCache` methods ensure that // we converge quickly on a terminal state so we will method will simply ensure that we only // save one. The reason for this is that the `getHandle` method can be invoked by multiple // threads concurrently and can be re-entrant. For a single thread the re-entrancy is managed by // the `LinkageContext`
InternalFactory
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/command/DataQueueCommand.java
{ "start": 1116, "end": 2432 }
class ____ extends StreamQueueCommand { private final byte[] data; private final int compressFlag; private final boolean endStream; private DataQueueCommand( TripleStreamChannelFuture streamChannelFuture, byte[] data, int compressFlag, boolean endStream) { super(streamChannelFuture); this.data = data; this.compressFlag = compressFlag; this.endStream = endStream; } public static DataQueueCommand create( TripleStreamChannelFuture streamChannelFuture, byte[] data, boolean endStream, int compressFlag) { return new DataQueueCommand(streamChannelFuture, data, compressFlag, endStream); } @Override public void doSend(ChannelHandlerContext ctx, ChannelPromise promise) { if (data == null) { ctx.write(new DefaultHttp2DataFrame(endStream), promise); } else { ByteBuf buf = ctx.alloc().buffer(); buf.writeByte(compressFlag); buf.writeInt(data.length); buf.writeBytes(data); ctx.write(new DefaultHttp2DataFrame(buf, endStream), promise); } } // for test public byte[] getData() { return data; } // for test public boolean isEndStream() { return endStream; } }
DataQueueCommand
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/introspect/POJOPropertiesCollector.java
{ "start": 10010, "end": 28175 }
class ____). */ public Set<String> getIgnoredPropertyNames() { return _ignoredPropertyNames; } /** * Accessor to find out whether type specified requires inclusion * of Object Identifier. */ public ObjectIdInfo getObjectIdInfo() { ObjectIdInfo info = _annotationIntrospector.findObjectIdInfo(_config, _classDef); if (info != null) { info = _annotationIntrospector.findObjectReferenceInfo(_config, _classDef, info); } return info; } // Method called by main "getProperties()" method; left // "protected" for unit tests protected Map<String, POJOPropertyBuilder> getPropertyMap() { if (!_collected) { collectAll(); } return _properties; } // 14-May-2024, tatu: Not 100% sure this is needed in Jackson 3.x; was added // in 2.x, merged in 2.18 timeframe to 3.0 for easier merges. /** * @since 2.17 */ public JsonFormat.Value getFormatOverrides() { if (_formatOverrides == null) { JsonFormat.Value format = null; // Let's check both per-type defaults and annotations; // per-type defaults having higher precedence, so start with annotations if (_annotationIntrospector != null) { format = _annotationIntrospector.findFormat(_config, _classDef); } JsonFormat.Value v = _config.getDefaultPropertyFormat(_type.getRawClass()); if (v != null) { if (format == null) { format = v; } else { format = format.withOverrides(v); } } _formatOverrides = (format == null) ? JsonFormat.Value.empty() : format; } return _formatOverrides; } /* /********************************************************************** /* Public API: main-level collection /********************************************************************** */ /** * Internal method that will collect actual property information. */ protected void collectAll() { //System.out.println(" PojoPropsCollector.collectAll() for "+_classDef.getRawType().getName()); _potentialCreators = new PotentialCreators(); // First: gather basic accessors LinkedHashMap<String, POJOPropertyBuilder> props = new LinkedHashMap<>(); // 14-Nov-2024, tatu: Previously skipped checking fields for Records; with 2.18+ won't // (see [databind#3628], [databind#3895], [databind#3992], [databind#4626]) _addFields(props); // note: populates _fieldRenameMappings _addMethods(props); // 25-Jan-2016, tatu: Avoid introspecting (constructor-)creators for non-static // inner classes, see [databind#1502] // 14-Nov-2024, tatu: Similarly need Creators for Records too (2.18+) if (!_classDef.isNonStaticInnerClass()) { _addCreators(props); } // 11-Jun-2025, tatu: [databind#5152] May need to "fix" mis-matching leading case // wrt Fields vs Accessors if (_config.isEnabled(MapperFeature.FIX_FIELD_NAME_UPPER_CASE_PREFIX)) { _fixLeadingFieldNameCase(props); } // Remove ignored properties, first; this MUST precede annotation merging // since logic relies on knowing exactly which accessor has which annotation _removeUnwantedProperties(props); // and then remove unneeded accessors (wrt read-only, read-write) _removeUnwantedAccessors(props); // Rename remaining properties _renameProperties(props); // and now add injectables, but taking care to avoid overlapping ones // via creator and regular properties _addInjectables(props); // then merge annotations, to simplify further processing: has to be done AFTER // preceding renaming step to get right propagation for (POJOPropertyBuilder property : props.values()) { property.mergeAnnotations(_forSerialization); } // And use custom naming strategy, if applicable... // 18-Jan-2021, tatu: To be done before trimming, to resolve // [databind#3368] PropertyNamingStrategy naming = _findNamingStrategy(); if (naming != null) { _renameUsing(props, naming); } // Sort by visibility (explicit over implicit); drop all but first of member // type (getter, setter etc) if there is visibility difference for (POJOPropertyBuilder property : props.values()) { property.trimByVisibility(); } // 22-Jul-2024, tatu: And now drop Record Fields once their effect // (annotations) has been applied. But just for deserialization if (_isRecordType && !_forSerialization) { for (POJOPropertyBuilder property : props.values()) { property.removeFields(); } } // and, if required, apply wrapper name: note, MUST be done after // annotations are merged. if (_config.isEnabled(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)) { _renameWithWrappers(props); } // well, almost last: there's still ordering... _sortProperties(props); _properties = props; _collected = true; } /** * [databind#5215] JsonAnyGetter Serializer behavior change from 2.18.4 to 2.19.0 * Put anyGetter in the end, before actual sorting further down {@link POJOPropertiesCollector#_sortProperties(Map)} */ private Map<String, POJOPropertyBuilder> _putAnyGettersInTheEnd( Map<String, POJOPropertyBuilder> sortedProps) { AnnotatedMember anyAccessor; if (_anyGetters != null) { anyAccessor = _anyGetters.getFirst(); } else if (_anyGetterField != null) { anyAccessor = _anyGetterField.getFirst(); } else { return sortedProps; } // Here we'll use insertion-order preserving map, since possible alphabetic // sorting already done earlier Map<String, POJOPropertyBuilder> newAll = new LinkedHashMap<>(sortedProps.size() * 2); POJOPropertyBuilder anyGetterProp = null; for (POJOPropertyBuilder prop : sortedProps.values()) { if (prop.hasFieldOrGetter(anyAccessor)) { anyGetterProp = prop; } else { newAll.put(prop.getName(), prop); } } if (anyGetterProp != null) { newAll.put(anyGetterProp.getName(), anyGetterProp); } return newAll; } /* /********************************************************************** /* Property introspection: Fields /********************************************************************** */ /** * Method for collecting basic information on all fields found */ protected void _addFields(Map<String, POJOPropertyBuilder> props) { final AnnotationIntrospector ai = _annotationIntrospector; // 28-Mar-2013, tatu: For deserialization we may also want to remove // final fields, as often they won't make very good mutators... // (although, maybe surprisingly, JVM _can_ force setting of such fields!) final boolean pruneFinalFields = !_forSerialization && !_config.isEnabled(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS); final boolean transientAsIgnoral = _config.isEnabled(MapperFeature.PROPAGATE_TRANSIENT_MARKER); for (AnnotatedField f : _classDef.fields()) { // @JsonKey? if (Boolean.TRUE.equals(ai.hasAsKey(_config, f))) { if (_jsonKeyAccessors == null) { _jsonKeyAccessors = new LinkedList<>(); } _jsonKeyAccessors.add(f); } // @JsonValue? if (Boolean.TRUE.equals(ai.hasAsValue(_config, f))) { if (_jsonValueAccessors == null) { _jsonValueAccessors = new LinkedList<>(); } _jsonValueAccessors.add(f); continue; } // 12-October-2020, dominikrebhan: [databind#1458] Support @JsonAnyGetter on // fields and allow @JsonAnySetter to be declared as well. boolean anyGetter = Boolean.TRUE.equals(ai.hasAnyGetter(_config, f)); boolean anySetter = Boolean.TRUE.equals(ai.hasAnySetter(_config, f)); if (anyGetter || anySetter) { // @JsonAnyGetter? if (anyGetter) { if (_anyGetterField == null) { _anyGetterField = new LinkedList<>(); } _anyGetterField.add(f); } // @JsonAnySetter? if (anySetter) { if (_anySetterField == null) { _anySetterField = new LinkedList<>(); } _anySetterField.add(f); // 07-Feb-2025: [databind#4775]: Skip the rest of processing, but only // for "any-setter', not any-getter continue; } } String implName = ai.findImplicitPropertyName(_config, f); if (implName == null) { implName = f.getName(); } // 27-Aug-2020, tatu: [databind#2800] apply naming strategy for // fields too, to allow use of naming conventions. implName = _accessorNaming.modifyFieldName(f, implName); if (implName == null) { continue; } final PropertyName implNameP = _propNameFromSimple(implName); // [databind#2527: Field-based renaming can be applied early (here), // or at a later point, but probably must be done before pruning // final fields. So let's do it early here final PropertyName rename = ai.findRenameByField(_config, f, implNameP); if ((rename != null) && !rename.equals(implNameP)) { if (_fieldRenameMappings == null) { _fieldRenameMappings = new HashMap<>(); } _fieldRenameMappings.put(rename, implNameP); } PropertyName pn; if (_forSerialization) { // 18-Aug-2011, tatu: As per existing unit tests, we should only // use serialization annotation (@JsonSerialize) when serializing // fields, and similarly for deserialize-only annotations... so // no fallbacks in this particular case. pn = ai.findNameForSerialization(_config, f); } else { pn = ai.findNameForDeserialization(_config, f); } boolean hasName = (pn != null); boolean nameExplicit = hasName; if (nameExplicit && pn.isEmpty()) { // empty String meaning "use default name", here just means "same as field name" pn = _propNameFromSimple(implName); nameExplicit = false; } // having explicit name means that field is visible; otherwise need to check the rules boolean visible = (pn != null); if (!visible) { visible = _visibilityChecker.isFieldVisible(f); } // and finally, may also have explicit ignoral boolean ignored = ai.hasIgnoreMarker(_config, f); // 13-May-2015, tatu: Moved from earlier place (AnnotatedClass) in 2.6 if (f.isTransient()) { // 20-May-2016, tatu: as per [databind#1184] explicit annotation should override // "default" `transient` if (!hasName) { // 25-Nov-2022, tatu: [databind#3682] Drop transient Fields early; // only retain if also have ignoral annotations (for name or ignoral) if (transientAsIgnoral) { ignored = true; // 18-Jul-2023, tatu: [databind#3948] Need to retain if there was explicit // ignoral marker } else if (!ignored) { continue; } } } /* [databind#190]: this is the place to prune final fields, if they are not * to be used as mutators. Must verify they are not explicitly included. * Also: if 'ignored' is set, need to include until a later point, to * avoid losing ignoral information. */ if (pruneFinalFields && (pn == null) && !ignored && Modifier.isFinal(f.getModifiers())) { continue; } _property(props, implName).addField(f, pn, nameExplicit, visible, ignored); } } /* /********************************************************************** /* Property introspection: Creators (constructors, factory methods) /********************************************************************** */ // Completely rewritten in 2.18 protected void _addCreators(Map<String, POJOPropertyBuilder> props) { final PotentialCreators creators = _potentialCreators; // First, resolve explicit annotations for all potential Creators // (but do NOT filter out DISABLED ones yet!) List<PotentialCreator> constructors = _collectCreators(_classDef.getConstructors()); List<PotentialCreator> factories = _collectCreators(_classDef.getFactoryMethods()); // Note! 0-param ("default") constructor is NOT included in 'constructors': PotentialCreator zeroParamsConstructor; { AnnotatedConstructor ac = _classDef.getDefaultConstructor(); zeroParamsConstructor = (ac == null) ? null : _potentialCreator(ac); } // Then find what is the Primary Constructor (if one exists for type): // for Java Records and potentially other types too ("data classes"): // Needs to be done early to get implicit names populated final PotentialCreator primaryCreator; if (_isRecordType) { primaryCreator = RecordUtil.findCanonicalRecordConstructor(_config, _classDef, constructors); } else { primaryCreator = _annotationIntrospector.findPreferredCreator(_config, _classDef, constructors, factories, Optional.ofNullable(zeroParamsConstructor)); } // Next: remove creators marked as explicitly disabled _removeDisabledCreators(constructors); _removeDisabledCreators(factories); if (zeroParamsConstructor != null && _isDisabledCreator(zeroParamsConstructor)) { zeroParamsConstructor = null; } // And then remove non-annotated static methods that do not look like factories _removeNonFactoryStaticMethods(factories, primaryCreator); // and use annotations to find explicitly chosen Creators if (_useAnnotations) { // can't have explicit ones without Annotation introspection // Start with Constructors as they have higher precedence // 08-Sep-2025, tatu: [databind#5045] Need to ensure 0-param ("default") // constructor considered if annotated (disabled case handled above). if (zeroParamsConstructor != null && zeroParamsConstructor.isAnnotated()) { creators.setPropertiesBased(_config, zeroParamsConstructor, "explicit"); } _addExplicitlyAnnotatedCreators(creators, constructors, props, false); // followed by Factory methods (lower precedence) _addExplicitlyAnnotatedCreators(creators, factories, props, creators.hasPropertiesBased()); } // If no Explicitly annotated creators (or Primary one) found, look // for ones with explicitly-named ({@code @JsonProperty}) parameters if (!creators.hasPropertiesBased()) { // only discover constructor Creators? _addCreatorsWithAnnotatedNames(creators, constructors, primaryCreator); } // But if no annotation-based Creators found, find/use Primary Creator // detected earlier, if any if (primaryCreator != null) { // ... but only process if still included as a candidate if (constructors.remove(primaryCreator) || factories.remove(primaryCreator)) { // and then consider delegating- vs properties-based if (_isDelegatingConstructor(primaryCreator)) { // 08-Oct-2024, tatu: [databind#4724] Only add if no explicit // candidates added if (!creators.hasDelegating()) { // ... not technically explicit but simpler this way creators.addExplicitDelegating(primaryCreator); } } else { // primary creator is properties-based if (!creators.hasPropertiesBased()) { creators.setPropertiesBased(_config, primaryCreator, "Primary"); } } } } // One more thing: if neither explicit (constructor or factory) nor // canonical (constructor?), consider implicit Constructor with all named. final ConstructorDetector ctorDetector = _config.getConstructorDetector(); if (!creators.hasPropertiesBasedOrDelegating() && !ctorDetector.requireCtorAnnotation()) { // But only if no Default (0-params) constructor available OR if we are configured // to prefer properties-based Creators // 19-Sep-2025, tatu: [databind#5318] Actually let's potentially allow // implicit constructor even if
annotations
java
apache__flink
flink-python/src/test/java/org/apache/flink/table/runtime/operators/python/aggregate/AbstractPythonStreamAggregateOperatorTest.java
{ "start": 2183, "end": 4821 }
class ____ { protected LogicalType[] getOutputLogicalType() { return new LogicalType[] { DataTypes.STRING().getLogicalType(), DataTypes.BIGINT().getLogicalType() }; } protected RowType getInputType() { return new RowType( Arrays.asList( new RowType.RowField("f1", new VarCharType()), new RowType.RowField("f2", new BigIntType()))); } protected RowType getOutputType() { return new RowType( Arrays.asList( new RowType.RowField("f1", new VarCharType()), new RowType.RowField("f2", new BigIntType()))); } private RowType getKeyType() { return new RowType( Collections.singletonList(new RowType.RowField("f1", new VarCharType()))); } int[] getGrouping() { return new int[] {0}; } private RowDataHarnessAssertor assertor = new RowDataHarnessAssertor(getOutputLogicalType()); protected OneInputStreamOperatorTestHarness getTestHarness(Configuration config) throws Exception { RowType outputType = getOutputType(); OneInputStreamOperator operator = getTestOperator(config); KeyedOneInputStreamOperatorTestHarness testHarness = new KeyedOneInputStreamOperatorTestHarness( operator, KeySelectorUtil.getRowDataSelector( Thread.currentThread().getContextClassLoader(), getGrouping(), InternalTypeInfo.of(getInputType())), InternalTypeInfo.of(getKeyType()), 1, 1, 0); testHarness .getStreamConfig() .setManagedMemoryFractionOperatorOfUseCase(ManagedMemoryUseCase.PYTHON, 0.5); testHarness.setup(new RowDataSerializer(outputType)); return testHarness; } protected RowData newRow(boolean accumulateMsg, Object... fields) { if (accumulateMsg) { return row(fields); } else { RowData row = row(fields); row.setRowKind(RowKind.DELETE); return row; } } protected void assertOutputEquals( String message, Collection<Object> expected, Collection<Object> actual) { assertor.assertOutputEquals(message, expected, actual); } abstract OneInputStreamOperator getTestOperator(Configuration config); }
AbstractPythonStreamAggregateOperatorTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java
{ "start": 2579, "end": 8300 }
class ____ { private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests"; public final SpringTestContext spring = new SpringTestContext(this); @Autowired private MockMvc mvc; @Test public void servletLoginWhenUsingDefaultConfigurationThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("Simple")).autowire(); // @formatter:off this.mvc.perform(get("/good-login")) .andExpect(status().isOk()) .andExpect(content().string("user")); // @formatter:on } @Test public void servletAuthenticateWhenUsingDefaultConfigurationThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("Simple")).autowire(); // @formatter:off this.mvc.perform(get("/authenticate")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/login")); // @formatter:on } @Test public void servletLogoutWhenUsingDefaultConfigurationThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("Simple")).autowire(); MvcResult result = this.mvc.perform(get("/good-login")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); // @formatter:off result = this.mvc.perform(get("/do-logout").session(session)) .andExpect(status().isOk()) .andExpect(content().string("")) .andReturn(); // @formatter:on session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNull(); } @Test public void servletAuthenticateWhenUsingHttpBasicThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("HttpBasic")).autowire(); // @formatter:off this.mvc.perform(get("/authenticate")) .andExpect(status().isUnauthorized()) .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("discworld"))); // @formatter:on } @Test public void servletAuthenticateWhenUsingFormLoginThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("FormLogin")).autowire(); // @formatter:off this.mvc.perform(get("/authenticate")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/login")); // @formatter:on } @Test public void servletLoginWhenUsingMultipleHttpConfigsThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("MultiHttp")).autowire(); // @formatter:off this.mvc.perform(get("/good-login")) .andExpect(status().isOk()) .andExpect(content().string("user")); this.mvc.perform(get("/v2/good-login")) .andExpect(status().isOk()) .andExpect(content().string("user2")); // @formatter:on } @Test public void servletAuthenticateWhenUsingMultipleHttpConfigsThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("MultiHttp")).autowire(); // @formatter:off this.mvc.perform(get("/authenticate")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/login")); this.mvc.perform(get("/v2/authenticate")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/login2")); // @formatter:on } @Test public void servletLogoutWhenUsingMultipleHttpConfigsThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("MultiHttp")).autowire(); MvcResult result = this.mvc.perform(get("/good-login")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); // @formatter:off result = this.mvc.perform(get("/do-logout").session(session)) .andExpect(status().isOk()) .andExpect(content().string("")) .andReturn(); // @formatter:on session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); // @formatter:off result = this.mvc.perform(get("/v2/good-login")) .andReturn(); // @formatter:on session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); // @formatter:off result = this.mvc.perform(get("/v2/do-logout").session(session)) .andExpect(status().isOk()) .andExpect(content().string("")) .andReturn(); // @formatter:on session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNull(); } @Test public void servletLogoutWhenUsingCustomLogoutThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("Logout")).autowire(); this.mvc.perform(get("/authenticate")).andExpect(status().isFound()).andExpect(redirectedUrl("/signin")); // @formatter:off MvcResult result = this.mvc.perform(get("/good-login")) .andReturn(); // @formatter:on MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); // @formatter:off result = this.mvc.perform(get("/do-logout").session(session)) .andExpect(status().isOk()) .andExpect(content().string("")) .andExpect(cookie().maxAge("JSESSIONID", 0)) .andReturn(); // @formatter:on session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); } /** * SEC-2926: Role Prefix is set */ @Test @WithMockUser public void servletIsUserInRoleWhenUsingDefaultConfigThenRoleIsSet() throws Exception { this.spring.configLocations(this.xml("Simple")).autowire(); // @formatter:off this.mvc.perform(get("/role")) .andExpect(content().string("true")); // @formatter:on } private String xml(String configName) { return CONFIG_LOCATION_PREFIX + "-" + configName + ".xml"; } @RestController public static
SecurityContextHolderAwareRequestConfigTests
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/query/projection/internal/EntityAuditProjection.java
{ "start": 592, "end": 1832 }
class ____ implements AuditProjection { private final String alias; private final boolean distinct; public EntityAuditProjection(String alias, boolean distinct) { this.alias = alias; this.distinct = distinct; } @Override public String getAlias(String baseAlias) { return alias == null ? baseAlias : alias; } @Override public void addProjectionToQuery( EnversService enversService, AuditReaderImplementor auditReader, Map<String, String> aliasToEntityNameMap, Map<String, String> aliasToComponentPropertyNameMap, String baseAlias, QueryBuilder queryBuilder) { String projectionEntityAlias = getAlias( baseAlias ); queryBuilder.addProjection( null, projectionEntityAlias, null, distinct ); } @Override public Object convertQueryResult( final EnversService enversService, final EntityInstantiator entityInstantiator, final String entityName, final Number revision, final Object value) { final Object result; if ( enversService.getEntitiesConfigurations().isVersioned( entityName ) ) { result = entityInstantiator.createInstanceFromVersionsEntity( entityName, (Map) value, revision ); } else { result = value; } return result; } }
EntityAuditProjection
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/EnclosedByReverseHeuristicTest.java
{ "start": 3024, "end": 3576 }
class ____ { abstract void target(Object first, Object second); void reverse(Object first, Object second) { // BUG: Diagnostic contains: true target(second, first); } } """) .doTest(); } @Test public void enclosedByReverse_returnsTrue_nestedInReverseClass() { CompilationTestHelper.newInstance(EnclosedByReverseHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/spi/PostCollectionUpdateEvent.java
{ "start": 345, "end": 915 }
class ____ extends AbstractCollectionEvent { public PostCollectionUpdateEvent( CollectionPersister collectionPersister, PersistentCollection<?> collection, EventSource source) { super( collectionPersister, collection, source, getLoadedOwnerOrNull( collection, source ), getLoadedOwnerIdOrNull( collection, source ) ); } public PostCollectionUpdateEvent( PersistentCollection<?> collection, Object id, String entityName, Object loadedOwner) { super( collection, entityName, loadedOwner, id ); } }
PostCollectionUpdateEvent
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java
{ "start": 999, "end": 1947 }
class ____ { @TempDir @SuppressWarnings("NullAway.Init") File tempDir; @Test @SuppressWarnings("NullAway") // Test null check void nameMustNotBeNull() { assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null)) .withMessageContaining("'name' must not be null"); } @Test void acceptNameMatch() throws Exception { File file = new File(this.tempDir, "thefile.txt"); file.createNewFile(); assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isTrue(); } @Test void doesNotAcceptNameMismatch() throws Exception { File file = new File(this.tempDir, "notthefile.txt"); file.createNewFile(); assertThat(new TriggerFileFilter("thefile.txt").accept(file)).isFalse(); } @Test void testName() throws Exception { File file = new File(this.tempDir, ".triggerfile"); file.createNewFile(); assertThat(new TriggerFileFilter(".triggerfile").accept(file)).isTrue(); } }
TriggerFileFilterTests
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/QueryHints.java
{ "start": 2868, "end": 3152 }
enum ____ implements QueryHints { INSTANCE; @Override public QueryHints withFetchGraphs(EntityManager em) { return this; } @Override public QueryHints forCounts() { return this; } @Override public void forEach(BiConsumer<String, Object> action) {} } }
NoHints
java
elastic__elasticsearch
modules/analysis-common/src/test/java/org/elasticsearch/analysis/common/ESWordnetSynonymParserTests.java
{ "start": 1236, "end": 3807 }
class ____ extends ESTokenStreamTestCase { public void testLenientParser() throws IOException, ParseException { ESWordnetSynonymParser parser = new ESWordnetSynonymParser(true, false, true, new StandardAnalyzer()); String rules = """ s(100000001,1,'&',a,1,0). s(100000001,2,'and',a,1,0). s(100000002,1,'come',v,1,0). s(100000002,2,'advance',v,1,0). s(100000002,3,'approach',v,1,0)."""; StringReader rulesReader = new StringReader(rules); parser.parse(rulesReader); SynonymMap synonymMap = parser.build(); Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader("approach quietly then advance & destroy")); TokenStream ts = new SynonymFilter(tokenizer, synonymMap, false); assertTokenStreamContents(ts, new String[] { "come", "quietly", "then", "come", "destroy" }); } public void testLenientParserWithSomeIncorrectLines() throws IOException, ParseException { CharArraySet stopSet = new CharArraySet(1, true); stopSet.add("bar"); ESWordnetSynonymParser parser = new ESWordnetSynonymParser(true, false, true, new StandardAnalyzer(stopSet)); String rules = """ s(100000001,1,'foo',v,1,0). s(100000001,2,'bar',v,1,0). s(100000001,3,'baz',v,1,0)."""; StringReader rulesReader = new StringReader(rules); parser.parse(rulesReader); SynonymMap synonymMap = parser.build(); Tokenizer tokenizer = new StandardTokenizer(); tokenizer.setReader(new StringReader("first word is foo, then bar and lastly baz")); TokenStream ts = new SynonymFilter(new StopFilter(tokenizer, stopSet), synonymMap, false); assertTokenStreamContents(ts, new String[] { "first", "word", "is", "foo", "then", "and", "lastly", "foo" }); } public void testNonLenientParser() { ESWordnetSynonymParser parser = new ESWordnetSynonymParser(true, false, false, new StandardAnalyzer()); String rules = """ s(100000001,1,'&',a,1,0). s(100000001,2,'and',a,1,0). s(100000002,1,'come',v,1,0). s(100000002,2,'advance',v,1,0). s(100000002,3,'approach',v,1,0)."""; StringReader rulesReader = new StringReader(rules); ParseException ex = expectThrows(ParseException.class, () -> parser.parse(rulesReader)); assertThat(ex.getMessage(), containsString("Invalid synonym rule at line 1")); } }
ESWordnetSynonymParserTests
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/event/ContextStartedEvent.java
{ "start": 959, "end": 1258 }
class ____ extends ApplicationContextEvent { /** * Create a new {@code ContextStartedEvent}. * @param source the {@code ApplicationContext} that has been started * (must not be {@code null}) */ public ContextStartedEvent(ApplicationContext source) { super(source); } }
ContextStartedEvent
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XJEndpointBuilderFactory.java
{ "start": 15340, "end": 30438 }
interface ____ extends EndpointProducerBuilder { default XJEndpointBuilder basic() { return (XJEndpointBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * To use a custom org.xml.sax.EntityResolver with * javax.xml.transform.sax.SAXSource. * * The option is a: <code>org.xml.sax.EntityResolver</code> type. * * Group: advanced * * @param entityResolver the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder entityResolver(org.xml.sax.EntityResolver entityResolver) { doSetProperty("entityResolver", entityResolver); return this; } /** * To use a custom org.xml.sax.EntityResolver with * javax.xml.transform.sax.SAXSource. * * The option will be converted to a * <code>org.xml.sax.EntityResolver</code> type. * * Group: advanced * * @param entityResolver the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder entityResolver(String entityResolver) { doSetProperty("entityResolver", entityResolver); return this; } /** * Allows to configure to use a custom * javax.xml.transform.ErrorListener. Beware when doing this then the * default error listener which captures any errors or fatal errors and * store information on the Exchange as properties is not in use. So * only use this option for special use-cases. * * The option is a: <code>javax.xml.transform.ErrorListener</code> type. * * Group: advanced * * @param errorListener the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder errorListener(javax.xml.transform.ErrorListener errorListener) { doSetProperty("errorListener", errorListener); return this; } /** * Allows to configure to use a custom * javax.xml.transform.ErrorListener. Beware when doing this then the * default error listener which captures any errors or fatal errors and * store information on the Exchange as properties is not in use. So * only use this option for special use-cases. * * The option will be converted to a * <code>javax.xml.transform.ErrorListener</code> type. * * Group: advanced * * @param errorListener the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder errorListener(String errorListener) { doSetProperty("errorListener", errorListener); return this; } /** * Allows you to use a custom * org.apache.camel.builder.xml.ResultHandlerFactory which is capable of * using custom org.apache.camel.builder.xml.ResultHandler types. * * The option is a: * <code>org.apache.camel.component.xslt.ResultHandlerFactory</code> * type. * * Group: advanced * * @param resultHandlerFactory the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder resultHandlerFactory(org.apache.camel.component.xslt.ResultHandlerFactory resultHandlerFactory) { doSetProperty("resultHandlerFactory", resultHandlerFactory); return this; } /** * Allows you to use a custom * org.apache.camel.builder.xml.ResultHandlerFactory which is capable of * using custom org.apache.camel.builder.xml.ResultHandler types. * * The option will be converted to a * <code>org.apache.camel.component.xslt.ResultHandlerFactory</code> * type. * * Group: advanced * * @param resultHandlerFactory the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder resultHandlerFactory(String resultHandlerFactory) { doSetProperty("resultHandlerFactory", resultHandlerFactory); return this; } /** * To use a custom Saxon configuration. * * The option is a: <code>net.sf.saxon.Configuration</code> type. * * Group: advanced * * @param saxonConfiguration the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder saxonConfiguration(net.sf.saxon.Configuration saxonConfiguration) { doSetProperty("saxonConfiguration", saxonConfiguration); return this; } /** * To use a custom Saxon configuration. * * The option will be converted to a * <code>net.sf.saxon.Configuration</code> type. * * Group: advanced * * @param saxonConfiguration the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder saxonConfiguration(String saxonConfiguration) { doSetProperty("saxonConfiguration", saxonConfiguration); return this; } /** * Allows you to use a custom * net.sf.saxon.lib.ExtensionFunctionDefinition. You would need to add * camel-saxon to the classpath. The function is looked up in the * registry, where you can comma to separate multiple values to lookup. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param saxonExtensionFunctions the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder saxonExtensionFunctions(String saxonExtensionFunctions) { doSetProperty("saxonExtensionFunctions", saxonExtensionFunctions); return this; } /** * Feature for XML secure processing (see javax.xml.XMLConstants). This * is enabled by default. However, when using Saxon Professional you may * need to turn this off to allow Saxon to be able to use Java extension * functions. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param secureProcessing the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder secureProcessing(boolean secureProcessing) { doSetProperty("secureProcessing", secureProcessing); return this; } /** * Feature for XML secure processing (see javax.xml.XMLConstants). This * is enabled by default. However, when using Saxon Professional you may * need to turn this off to allow Saxon to be able to use Java extension * functions. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param secureProcessing the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder secureProcessing(String secureProcessing) { doSetProperty("secureProcessing", secureProcessing); return this; } /** * To use a custom XSLT transformer factory. * * The option is a: <code>javax.xml.transform.TransformerFactory</code> * type. * * Group: advanced * * @param transformerFactory the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder transformerFactory(javax.xml.transform.TransformerFactory transformerFactory) { doSetProperty("transformerFactory", transformerFactory); return this; } /** * To use a custom XSLT transformer factory. * * The option will be converted to a * <code>javax.xml.transform.TransformerFactory</code> type. * * Group: advanced * * @param transformerFactory the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder transformerFactory(String transformerFactory) { doSetProperty("transformerFactory", transformerFactory); return this; } /** * To use a custom XSLT transformer factory, specified as a FQN class * name. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param transformerFactoryClass the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder transformerFactoryClass(String transformerFactoryClass) { doSetProperty("transformerFactoryClass", transformerFactoryClass); return this; } /** * A configuration strategy to apply on freshly created instances of * TransformerFactory. * * The option is a: * <code>org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy</code> type. * * Group: advanced * * @param transformerFactoryConfigurationStrategy the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder transformerFactoryConfigurationStrategy(org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy transformerFactoryConfigurationStrategy) { doSetProperty("transformerFactoryConfigurationStrategy", transformerFactoryConfigurationStrategy); return this; } /** * A configuration strategy to apply on freshly created instances of * TransformerFactory. * * The option will be converted to a * <code>org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy</code> type. * * Group: advanced * * @param transformerFactoryConfigurationStrategy the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder transformerFactoryConfigurationStrategy(String transformerFactoryConfigurationStrategy) { doSetProperty("transformerFactoryConfigurationStrategy", transformerFactoryConfigurationStrategy); return this; } /** * To use a custom javax.xml.transform.URIResolver. * * The option is a: <code>javax.xml.transform.URIResolver</code> type. * * Group: advanced * * @param uriResolver the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder uriResolver(javax.xml.transform.URIResolver uriResolver) { doSetProperty("uriResolver", uriResolver); return this; } /** * To use a custom javax.xml.transform.URIResolver. * * The option will be converted to a * <code>javax.xml.transform.URIResolver</code> type. * * Group: advanced * * @param uriResolver the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder uriResolver(String uriResolver) { doSetProperty("uriResolver", uriResolver); return this; } /** * A consumer to messages generated during XSLT transformations. * * The option is a: * <code>org.apache.camel.component.xslt.XsltMessageLogger</code> type. * * Group: advanced * * @param xsltMessageLogger the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder xsltMessageLogger(org.apache.camel.component.xslt.XsltMessageLogger xsltMessageLogger) { doSetProperty("xsltMessageLogger", xsltMessageLogger); return this; } /** * A consumer to messages generated during XSLT transformations. * * The option will be converted to a * <code>org.apache.camel.component.xslt.XsltMessageLogger</code> type. * * Group: advanced * * @param xsltMessageLogger the value to set * @return the dsl builder */ default AdvancedXJEndpointBuilder xsltMessageLogger(String xsltMessageLogger) { doSetProperty("xsltMessageLogger", xsltMessageLogger); return this; } } public
AdvancedXJEndpointBuilder
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/Hadoop20JHParser.java
{ "start": 1263, "end": 2468 }
class ____ implements JobHistoryParser { final LineReader reader; static final String endLineString = " ."; static final int internalVersion = 1; /** * Can this parser parse the input? * * @param input * @return Whether this parser can parse the input. * @throws IOException * * We will deem a stream to be a good 0.20 job history stream if the * first line is exactly "Meta VERSION=\"1\" ." */ public static boolean canParse(InputStream input) throws IOException { try { LineReader reader = new LineReader(input); Text buffer = new Text(); return reader.readLine(buffer) != 0 && buffer.toString().equals("Meta VERSION=\"1\" ."); } catch (EOFException e) { return false; } } public Hadoop20JHParser(InputStream input) throws IOException { super(); reader = new LineReader(input); } public Hadoop20JHParser(LineReader reader) throws IOException { super(); this.reader = reader; } Map<String, HistoryEventEmitter> liveEmitters = new HashMap<String, HistoryEventEmitter>(); Queue<HistoryEvent> remainingEvents = new LinkedList<HistoryEvent>();
Hadoop20JHParser
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/ingest/IngestCtxMapTests.java
{ "start": 15377, "end": 15906 }
class ____ implements Map.Entry<String, Object> { String key; Object value; TestEntry(String key, Object value) { this.key = key; this.value = value; } @Override public String getKey() { return key; } @Override public Object getValue() { return value; } @Override public Object setValue(Object value) { throw new UnsupportedOperationException(); } } }
TestEntry
java
apache__camel
components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppSubmitSmCommandTest.java
{ "start": 2243, "end": 37773 }
class ____ { private static TimeZone defaultTimeZone; private SMPPSession session; private SmppConfiguration config; private SmppSubmitSmCommand command; @BeforeAll public static void setUpBeforeClass() { defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } @AfterAll public static void tearDownAfterClass() { if (defaultTimeZone != null) { TimeZone.setDefault(defaultTimeZone); } } @BeforeEach public void setUp() { session = mock(SMPPSession.class); config = new SmppConfiguration(); config.setServiceType("CMT"); command = new SmppSubmitSmCommand(session, config); } @Test public void executeWithConfigurationData() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setBody( "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .getBytes()))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test @Disabled() public void executeLongBody() throws Exception { byte[] firstSM = new byte[] { 5, 0, 3, 1, 2, 1, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51 }; byte[] secondSM = new byte[] { 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setBody( "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq(firstSM))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq(secondSM))) .thenReturn(new SubmitSmResult(new MessageId("2"), null)); command.execute(exchange); assertEquals(Arrays.asList("1", "2"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(2, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void executeLongBodyRejection() throws Exception { byte[] firstSM = new byte[] { 5, 0, 3, 1, 2, 1, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51 }; byte[] secondSM = new byte[] { 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SPLITTING_POLICY, "REJECT"); exchange.getIn().setBody( "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq(firstSM))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq(secondSM))) .thenReturn(new SubmitSmResult(new MessageId("2"), null)); assertThrows(SmppException.class, () -> command.execute(exchange)); } @Test public void executeLongBodyTruncation() throws Exception { byte[] firstSM = new byte[] { 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SPLITTING_POLICY, "TRUNCATE"); exchange.getIn().setBody( "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq(firstSM))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void execute() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818"); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR, "1919"); exchange.getIn().setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, new Date(1111111)); exchange.getIn().setHeader(SmppConstants.VALIDITY_PERIOD, new Date(2222222)); exchange.getIn().setHeader(SmppConstants.PROTOCOL_ID, (byte) 1); exchange.getIn().setHeader(SmppConstants.PRIORITY_FLAG, (byte) 2); exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY, new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value()); exchange.getIn().setHeader(SmppConstants.REPLACE_IF_PRESENT_FLAG, ReplaceIfPresentFlag.REPLACE.value()); exchange.getIn().setBody("short message body"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"), eq(TypeOfNumber.INTERNATIONAL), eq(NumberingPlanIndicator.INTERNET), eq("1919"), eq(new ESMClass()), eq((byte) 1), eq((byte) 2), eq("-300101001831100+"), eq("-300101003702200+"), eq(new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE)), eq(ReplaceIfPresentFlag.REPLACE.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq("short message body".getBytes()))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void executeWithOptionalParameter() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818"); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR, "1919"); exchange.getIn().setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, new Date(1111111)); exchange.getIn().setHeader(SmppConstants.VALIDITY_PERIOD, new Date(2222222)); exchange.getIn().setHeader(SmppConstants.PROTOCOL_ID, (byte) 1); exchange.getIn().setHeader(SmppConstants.PRIORITY_FLAG, (byte) 2); exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY, new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value()); exchange.getIn().setHeader(SmppConstants.REPLACE_IF_PRESENT_FLAG, ReplaceIfPresentFlag.REPLACE.value()); exchange.getIn().setBody("short message body"); Map<String, String> optionalParameters = new LinkedHashMap<>(); optionalParameters.put("SOURCE_SUBADDRESS", "1292"); optionalParameters.put("ADDITIONAL_STATUS_INFO_TEXT", "urgent"); optionalParameters.put("DEST_ADDR_SUBUNIT", "4"); optionalParameters.put("DEST_TELEMATICS_ID", "2"); optionalParameters.put("QOS_TIME_TO_LIVE", "3600000"); optionalParameters.put("ALERT_ON_MESSAGE_DELIVERY", null); exchange.getIn().setHeader(SmppConstants.OPTIONAL_PARAMETERS, optionalParameters); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"), eq(TypeOfNumber.INTERNATIONAL), eq(NumberingPlanIndicator.INTERNET), eq("1919"), eq(new ESMClass()), eq((byte) 1), eq((byte) 2), eq("-300101001831100+"), eq("-300101003702200+"), eq(new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE)), eq(ReplaceIfPresentFlag.REPLACE.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq("short message body".getBytes()), eq(new OptionalParameter.Source_subaddress("1292".getBytes())), eq(new OptionalParameter.Additional_status_info_text("urgent".getBytes())), eq(new OptionalParameter.Dest_addr_subunit((byte) 4)), eq(new OptionalParameter.Dest_telematics_id((short) 2)), eq(new OptionalParameter.Qos_time_to_live(3600000)), eq(new OptionalParameter.Alert_on_message_delivery((byte) 0)))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void executeWithOptionalParameterNewStyle() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818"); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR, "1919"); exchange.getIn().setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, new Date(1111111)); exchange.getIn().setHeader(SmppConstants.VALIDITY_PERIOD, new Date(2222222)); exchange.getIn().setHeader(SmppConstants.PROTOCOL_ID, (byte) 1); exchange.getIn().setHeader(SmppConstants.PRIORITY_FLAG, (byte) 2); exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY, new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value()); exchange.getIn().setHeader(SmppConstants.REPLACE_IF_PRESENT_FLAG, ReplaceIfPresentFlag.REPLACE.value()); exchange.getIn().setBody("short message body"); Map<Short, Object> optionalParameters = new LinkedHashMap<>(); // standard optional parameter optionalParameters.put((short) 0x0202, "1292".getBytes("UTF-8")); optionalParameters.put((short) 0x001D, "urgent"); optionalParameters.put((short) 0x0005, Byte.valueOf("4")); optionalParameters.put((short) 0x0008, (short) 2); optionalParameters.put((short) 0x0017, 3600000); optionalParameters.put((short) 0x130C, null); // vendor specific optional parameter optionalParameters.put((short) 0x2150, "0815".getBytes("UTF-8")); optionalParameters.put((short) 0x2151, "0816"); optionalParameters.put((short) 0x2152, Byte.valueOf("6")); optionalParameters.put((short) 0x2153, (short) 9); optionalParameters.put((short) 0x2154, 7400000); optionalParameters.put((short) 0x2155, null); exchange.getIn().setHeader(SmppConstants.OPTIONAL_PARAMETER, optionalParameters); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"), eq(TypeOfNumber.INTERNATIONAL), eq(NumberingPlanIndicator.INTERNET), eq("1919"), eq(new ESMClass()), eq((byte) 1), eq((byte) 2), eq("-300101001831100+"), eq("-300101003702200+"), eq(new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE)), eq(ReplaceIfPresentFlag.REPLACE.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq("short message body".getBytes()), eq(new OptionalParameter.OctetString(Tag.SOURCE_SUBADDRESS, "1292")), eq(new OptionalParameter.COctetString(Tag.ADDITIONAL_STATUS_INFO_TEXT.code(), "urgent")), eq(new OptionalParameter.Byte(Tag.DEST_ADDR_SUBUNIT, (byte) 4)), eq(new OptionalParameter.Short(Tag.DEST_TELEMATICS_ID.code(), (short) 2)), eq(new OptionalParameter.Int(Tag.QOS_TIME_TO_LIVE, 3600000)), eq(new OptionalParameter.Null(Tag.ALERT_ON_MESSAGE_DELIVERY)), eq(new OptionalParameter.OctetString((short) 0x2150, "1292", "UTF-8")), eq(new OptionalParameter.COctetString((short) 0x2151, "0816")), eq(new OptionalParameter.Byte((short) 0x2152, (byte) 6)), eq(new OptionalParameter.Short((short) 0x2153, (short) 9)), eq(new OptionalParameter.Int((short) 0x2154, 7400000)), eq(new OptionalParameter.Null((short) 0x2155)))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void executeWithValidityPeriodAsString() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_TON, TypeOfNumber.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR_NPI, NumberingPlanIndicator.NATIONAL.value()); exchange.getIn().setHeader(SmppConstants.SOURCE_ADDR, "1818"); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_TON, TypeOfNumber.INTERNATIONAL.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR_NPI, NumberingPlanIndicator.INTERNET.value()); exchange.getIn().setHeader(SmppConstants.DEST_ADDR, "1919"); exchange.getIn().setHeader(SmppConstants.SCHEDULE_DELIVERY_TIME, new Date(1111111)); exchange.getIn().setHeader(SmppConstants.VALIDITY_PERIOD, "000003000000000R"); // three days exchange.getIn().setHeader(SmppConstants.PROTOCOL_ID, (byte) 1); exchange.getIn().setHeader(SmppConstants.PRIORITY_FLAG, (byte) 2); exchange.getIn().setHeader(SmppConstants.REGISTERED_DELIVERY, new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE).value()); exchange.getIn().setHeader(SmppConstants.REPLACE_IF_PRESENT_FLAG, ReplaceIfPresentFlag.REPLACE.value()); exchange.getIn().setBody("short message body"); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.NATIONAL), eq(NumberingPlanIndicator.NATIONAL), eq("1818"), eq(TypeOfNumber.INTERNATIONAL), eq(NumberingPlanIndicator.INTERNET), eq("1919"), eq(new ESMClass()), eq((byte) 1), eq((byte) 2), eq("-300101001831100+"), eq("000003000000000R"), eq(new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE)), eq(ReplaceIfPresentFlag.REPLACE.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), eq("short message body".getBytes()))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Arrays.asList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(1, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } @Test public void alphabetUpdatesDataCoding() throws Exception { final byte incorrectDataCoding = (byte) 0x00; byte[] body = { 'A', 'B', 'C' }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ALPHABET, Alphabet.ALPHA_8_BIT.value()); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), argThat(not(DataCodings.newInstance(incorrectDataCoding))), eq((byte) 0), eq(body))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Arrays.asList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void bodyWithSmscDefaultDataCodingNarrowedToCharset() throws Exception { final byte dataCoding = (byte) 0x00; /* SMSC-default */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (byte) 0x7F, 'C', '?' }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(dataCoding)), eq((byte) 0), eq(bodyNarrowed))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Arrays.asList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void bodyWithLatin1DataCodingNarrowedToCharset() throws Exception { final byte dataCoding = (byte) 0x03; /* ISO-8859-1 (Latin1) */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (byte) 0x7F, 'C', '?' }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(dataCoding)), eq((byte) 0), eq(bodyNarrowed))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void bodyWithSMPP8bitDataCodingNotModified() throws Exception { final byte dataCoding = (byte) 0x04; /* SMPP 8-bit */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(dataCoding)), eq((byte) 0), eq(body))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void bodyWithGSM8bitDataCodingNotModified() throws Exception { final byte dataCoding = (byte) 0xF7; /* GSM 8-bit class 3 */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.DATA_CODING, dataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(dataCoding)), eq((byte) 0), eq(body))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void eightBitDataCodingOverridesDefaultAlphabet() throws Exception { final byte binDataCoding = (byte) 0x04; /* SMPP 8-bit */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ALPHABET, Alphabet.ALPHA_DEFAULT.value()); exchange.getIn().setHeader(SmppConstants.DATA_CODING, binDataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(binDataCoding)), eq((byte) 0), eq(body))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void latin1DataCodingOverridesEightBitAlphabet() throws Exception { final byte latin1DataCoding = (byte) 0x03; /* ISO-8859-1 (Latin1) */ byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF }; byte[] bodyNarrowed = { '?', 'A', 'B', '\0', '?', (byte) 0x7F, 'C', '?' }; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.ALPHABET, Alphabet.ALPHA_8_BIT.value()); exchange.getIn().setHeader(SmppConstants.DATA_CODING, latin1DataCoding); exchange.getIn().setBody(body); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass()), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance(latin1DataCoding)), eq((byte) 0), eq(bodyNarrowed))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); command.execute(exchange); assertEquals(Collections.singletonList("1"), exchange.getMessage().getHeader(SmppConstants.ID)); } @Test public void singleDlrRequestOverridesDeliveryReceiptFlag() throws Exception { String longSms = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890123456789012345678901"; Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitSm"); exchange.getIn().setHeader(SmppConstants.SINGLE_DLR, "true"); exchange.getIn().setBody(longSms.getBytes()); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass((byte) 64)), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), any(byte[].class))) .thenReturn(new SubmitSmResult(new MessageId("1"), null)); when(session.submitShortMessage(eq("CMT"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1616"), eq(TypeOfNumber.UNKNOWN), eq(NumberingPlanIndicator.UNKNOWN), eq("1717"), eq(new ESMClass((byte) 64)), eq((byte) 0), eq((byte) 1), (String) isNull(), (String) isNull(), eq(new RegisteredDelivery(SMSCDeliveryReceipt.SUCCESS_FAILURE)), eq(ReplaceIfPresentFlag.DEFAULT.value()), eq(DataCodings.newInstance((byte) 0)), eq((byte) 0), any(byte[].class))) .thenReturn(new SubmitSmResult(new MessageId("2"), null)); command.execute(exchange); assertEquals(Arrays.asList("1", "2"), exchange.getMessage().getHeader(SmppConstants.ID)); assertEquals(2, exchange.getMessage().getHeader(SmppConstants.SENT_MESSAGE_COUNT)); } }
SmppSubmitSmCommandTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/TestRMAppAttemptTransitions.java
{ "start": 10286, "end": 10486 }
class ____ implements EventHandler<SchedulerEvent> { @Override public void handle(SchedulerEvent event) { scheduler.handle(event); } } private final
TestSchedulerEventDispatcher
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/lib/TestChainMapReduce.java
{ "start": 6807, "end": 6911 }
class ____ extends IDMap { public DMap() { super("D", "X", false); } } public static
DMap
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/AbstractHttpConfigurer.java
{ "start": 1472, "end": 1624 }
class ____ {@link SecurityConfigurer} instances that operate on * {@link HttpSecurity}. * * @author Rob Winch * @author Ding Hao */ public abstract
for
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTestHarness.java
{ "start": 22805, "end": 23213 }
class ____ extends NoOpMetricRegistry { private final Map<String, Metric> metrics; TestMetricRegistry(Map<String, Metric> metrics) { super(); this.metrics = metrics; } @Override public void register(Metric metric, String metricName, AbstractMetricGroup<?> group) { metrics.put(metricName, metric); } } }
TestMetricRegistry
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/IdentityWrapper.java
{ "start": 928, "end": 1326 }
class ____ { private final Object object; IdentityWrapper(@NonNull Object object) { this.object = Objects.requireNonNull(object); } @Override public boolean equals(Object o) { return o instanceof IdentityWrapper iw && iw.object == this.object; } @Override public int hashCode() { return System.identityHashCode(object); } }
IdentityWrapper
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/config/TransactionalService.java
{ "start": 863, "end": 1049 }
class ____ implements Serializable { @Transactional("synch") public void setSomething(String name) { } @Transactional("noSynch") public void doSomething() { } }
TransactionalService
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 82757, "end": 83366 }
class ____ { public void method() { // BUG: Diagnostic contains: instantiation of 'T' is mutable, the declaration of type // 'MutableClass' is not annotated with @com.google.errorprone.annotations.Immutable new Clazz().method(78, new MutableClass()); } } """) .doTest(); } @Test public void containerOfAsImmutableTypeParameter_noViolation() { withImmutableTypeParameterGeneric() .addSourceLines( "Container.java", """ import com.google.errorprone.annotations.Immutable; @Immutable(containerOf = {"T"})
Invoker
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/CombineTextInputFormat.java
{ "start": 1444, "end": 2120 }
class ____ extends CombineFileInputFormat<LongWritable,Text> { public RecordReader<LongWritable,Text> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException { return new CombineFileRecordReader<LongWritable,Text>( (CombineFileSplit)split, context, TextRecordReaderWrapper.class); } /** * A record reader that may be passed to <code>CombineFileRecordReader</code> * so that it can be used in a <code>CombineFileInputFormat</code>-equivalent * for <code>TextInputFormat</code>. * * @see CombineFileRecordReader * @see CombineFileInputFormat * @see TextInputFormat */ private static
CombineTextInputFormat
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/eval/EvalMethodBitLengthTest.java
{ "start": 185, "end": 384 }
class ____ extends TestCase { public void test_reverse() throws Exception { assertEquals("1100", SQLEvalVisitorUtils.evalExpr(JdbcConstants.MYSQL, "BIN(12)")); } }
EvalMethodBitLengthTest
java
spring-projects__spring-framework
spring-core/src/jmh/java/org/springframework/util/ConcurrentReferenceHashMapBenchmark.java
{ "start": 2951, "end": 3646 }
class ____ { @Param({"500"}) public int capacity; private Function<String, String> generator = key -> key + "value"; public List<String> elements; public Map<String, WeakReference<String>> map; @Setup(Level.Iteration) public void setup() { this.elements = new ArrayList<>(this.capacity); this.map = Collections.synchronizedMap(new WeakHashMap<>()); Random random = new Random(); random.ints(this.capacity).forEach(value -> { String element = String.valueOf(value); this.elements.add(element); this.map.put(element, new WeakReference<>(this.generator.apply(element))); }); this.elements.sort(String::compareTo); } } }
SynchronizedMapBenchmarkData
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/DFSHAAdmin.java
{ "start": 2129, "end": 11531 }
class ____ extends HAAdmin { private static final String FORCEFENCE = "forcefence"; private static final Logger LOG = LoggerFactory.getLogger(DFSHAAdmin.class); private String nameserviceId; private final static Map<String, UsageInfo> USAGE_DFS_ONLY = ImmutableMap.<String, UsageInfo> builder() .put("-transitionToObserver", new UsageInfo("<serviceId>", "Transitions the service into Observer state")) .put("-failover", new UsageInfo( "[--"+FORCEFENCE+"] [--"+FORCEACTIVE+"] " + "<serviceId> <serviceId>", "Failover from the first service to the second.\n" + "Unconditionally fence services if the --" + FORCEFENCE + " option is used.\n" + "Try to failover to the target service " + "even if it is not ready if the " + "--" + FORCEACTIVE + " option is used.")).build(); private final static Map<String, UsageInfo> USAGE_DFS_MERGED = ImmutableSortedMap.<String, UsageInfo> naturalOrder() .putAll(USAGE) .putAll(USAGE_DFS_ONLY) .build(); protected void setErrOut(PrintStream errOut) { this.errOut = errOut; } protected void setOut(PrintStream out) { this.out = out; } @Override public void setConf(Configuration conf) { if (conf != null) { conf = addSecurityConfiguration(conf); } super.setConf(conf); } /** * Add the requisite security principal settings to the given Configuration, * returning a copy. * @param conf the original config * @return a copy with the security settings added */ public static Configuration addSecurityConfiguration(Configuration conf) { // Make a copy so we don't mutate it. Also use an HdfsConfiguration to // force loading of hdfs-site.xml. conf = new HdfsConfiguration(conf); String nameNodePrincipal = conf.get( DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, ""); if (LOG.isDebugEnabled()) { LOG.debug("Using NN principal: " + nameNodePrincipal); } conf.set(CommonConfigurationKeys.HADOOP_SECURITY_SERVICE_USER_NAME_KEY, nameNodePrincipal); return conf; } /** * Try to map the given namenode ID to its service address. */ @Override protected HAServiceTarget resolveTarget(String nnId) { HdfsConfiguration conf = (HdfsConfiguration)getConf(); return new NNHAServiceTarget(conf, nameserviceId, nnId); } @Override protected String getUsageString() { return "Usage: haadmin [-ns <nameserviceId>]"; } /** * Add CLI options which are specific to the failover command and no * others. */ private void addFailoverCliOpts(Options failoverOpts) { failoverOpts.addOption(FORCEFENCE, false, "force fencing"); failoverOpts.addOption(FORCEACTIVE, false, "force failover"); // Don't add FORCEMANUAL, since that's added separately for all commands // that change state. } @Override protected boolean checkParameterValidity(String[] argv){ return checkParameterValidity(argv, USAGE_DFS_MERGED); } @Override protected int runCmd(String[] argv) throws Exception { if(argv.length < 1){ printUsage(errOut, USAGE_DFS_MERGED); return -1; } int i = 0; String cmd = argv[i++]; //Process "-ns" Option if ("-ns".equals(cmd)) { if (i == argv.length) { errOut.println("Missing nameservice ID"); printUsage(errOut, USAGE_DFS_MERGED); return -1; } nameserviceId = argv[i++]; if (i >= argv.length) { errOut.println("Missing command"); printUsage(errOut, USAGE_DFS_MERGED); return -1; } argv = Arrays.copyOfRange(argv, i, argv.length); cmd = argv[0]; } if (!checkParameterValidity(argv)){ return -1; } /* "-help" command has to to be handled here because it should be supported both by HAAdmin and DFSHAAdmin but it is contained in USAGE_DFS_ONLY */ if ("-help".equals(cmd)){ return help(argv, USAGE_DFS_MERGED); } if (!USAGE_DFS_ONLY.containsKey(cmd)) { return super.runCmd(argv); } Options opts = new Options(); // Add command-specific options if ("-failover".equals(cmd)) { addFailoverCliOpts(opts); } // Mutative commands take FORCEMANUAL option if ("-transitionToObserver".equals(cmd) || "-failover".equals(cmd)) { opts.addOption(FORCEMANUAL, false, "force manual control even if auto-failover is enabled"); } CommandLine cmdLine = parseOpts(cmd, opts, argv, USAGE_DFS_MERGED); if (cmdLine == null) { return -1; } if (cmdLine.hasOption(FORCEMANUAL)) { if (!confirmForceManual()) { LOG.error("Aborted"); return -1; } // Instruct the NNs to honor this request even if they're // configured for manual failover. setRequestSource(RequestSource.REQUEST_BY_USER_FORCED); } if ("-transitionToObserver".equals(cmd)) { return transitionToObserver(cmdLine); } else if ("-failover".equals(cmd)) { return failover(cmdLine); } else { // This line should not be reached throw new AssertionError("Should not get here, command: " + cmd); } } /** * returns the list of all namenode ids for the given configuration. */ @Override protected Collection<String> getTargetIds(String namenodeToActivate) { return DFSUtilClient.getNameNodeIds( getConf(), (nameserviceId != null)? nameserviceId : DFSUtil.getNamenodeNameServiceId(getConf())); } /** * Check if the target supports the Observer state. * @param target the target to check * @return true if the target support Observer state, false otherwise. */ private boolean checkSupportObserver(HAServiceTarget target) { if (target.supportObserver()) { return true; } else { errOut.println( "The target " + target + " doesn't support Observer state."); return false; } } private int transitionToObserver(final CommandLine cmd) throws IOException { String[] argv = cmd.getArgs(); if (argv.length != 1) { errOut.println("transitionToObserver: incorrect number of arguments"); printUsage(errOut, "-transitionToObserver", USAGE_DFS_MERGED); return -1; } HAServiceTarget target = resolveTarget(argv[0]); if (!checkSupportObserver(target)) { return -1; } if (!checkManualStateManagementOK(target)) { return -1; } try { HAServiceProtocol proto = target.getProxy(getConf(), 0); HAServiceProtocolHelper.transitionToObserver(proto, createReqInfo()); } catch (ServiceFailedException e) { errOut.println("transitionToObserver failed! " + e.getLocalizedMessage()); return -1; } return 0; } private int failover(CommandLine cmd) throws IOException, ServiceFailedException { boolean forceFence = cmd.hasOption(FORCEFENCE); boolean forceActive = cmd.hasOption(FORCEACTIVE); int numOpts = cmd.getOptions() == null ? 0 : cmd.getOptions().length; final String[] args = cmd.getArgs(); if (numOpts > 3 || args.length != 2) { errOut.println("failover: incorrect arguments"); printUsage(errOut, "-failover", USAGE_DFS_MERGED); return -1; } HAServiceTarget fromNode = resolveTarget(args[0]); HAServiceTarget toNode = resolveTarget(args[1]); fromNode.setTransitionTargetHAStatus( HAServiceProtocol.HAServiceState.STANDBY); toNode.setTransitionTargetHAStatus( HAServiceProtocol.HAServiceState.ACTIVE); // Check that auto-failover is consistently configured for both nodes. Preconditions.checkState( fromNode.isAutoFailoverEnabled() == toNode.isAutoFailoverEnabled(), "Inconsistent auto-failover configs between %s and %s!", fromNode, toNode); if (fromNode.isAutoFailoverEnabled()) { if (forceFence || forceActive) { // -forceActive doesn't make sense with auto-HA, since, if the node // is not healthy, then its ZKFC will immediately quit the election // again the next time a health check runs. // // -forceFence doesn't seem to have any real use cases with auto-HA // so it isn't implemented. errOut.println(FORCEFENCE + " and " + FORCEACTIVE + " flags not " + "supported with auto-failover enabled."); return -1; } try { return gracefulFailoverThroughZKFCs(toNode); } catch (UnsupportedOperationException e){ errOut.println("Failover command is not supported with " + "auto-failover enabled: " + e.getLocalizedMessage()); return -1; } } FailoverController fc = new FailoverController(getConf(), getRequestSource()); try { fc.failover(fromNode, toNode, forceFence, forceActive); out.println("Failover from "+args[0]+" to "+args[1]+" successful"); } catch (FailoverFailedException ffe) { errOut.println("Failover failed: " + ffe.getLocalizedMessage()); return -1; } return 0; } public static void main(String[] argv) throws Exception { int res = ToolRunner.run(new DFSHAAdmin(), argv); System.exit(res); } }
DFSHAAdmin
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EqualsUsingHashCodeTest.java
{ "start": 1273, "end": 1687 }
class ____ { private int a; @Override public boolean equals(Object o) { Test that = (Test) o; return o.hashCode() == hashCode() && a == that.a; } } """) .doTest(); } @Test public void positive() { helper .addSourceLines( "Test.java", """
Test
java
elastic__elasticsearch
libs/geo/src/test/java/org/elasticsearch/geometry/MultiPolygonTests.java
{ "start": 938, "end": 5666 }
class ____ extends BaseGeometryTestCase<MultiPolygon> { @Override protected MultiPolygon createTestInstance(boolean hasAlt) { int size = randomIntBetween(1, 10); List<Polygon> arr = new ArrayList<>(); for (int i = 0; i < size; i++) { arr.add(GeometryTestUtils.randomPolygon(hasAlt)); } return new MultiPolygon(arr); } public void testBasicSerialization() throws IOException, ParseException { GeometryValidator validator = GeographyValidator.instance(true); assertEquals( "MULTIPOLYGON (((3.0 1.0, 4.0 2.0, 5.0 3.0, 3.0 1.0)))", WellKnownText.toWKT( new MultiPolygon( Collections.singletonList(new Polygon(new LinearRing(new double[] { 3, 4, 5, 3 }, new double[] { 1, 2, 3, 1 }))) ) ) ); assertEquals( new MultiPolygon( Collections.singletonList(new Polygon(new LinearRing(new double[] { 3, 4, 5, 3 }, new double[] { 1, 2, 3, 1 }))) ), WellKnownText.fromWKT(validator, true, "MULTIPOLYGON (((3.0 1.0, 4.0 2.0, 5.0 3.0, 3.0 1.0)))") ); assertEquals("MULTIPOLYGON EMPTY", WellKnownText.toWKT(MultiPolygon.EMPTY)); assertEquals(MultiPolygon.EMPTY, WellKnownText.fromWKT(validator, true, "MULTIPOLYGON EMPTY)")); } public void testValidation() { IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, () -> StandardValidator.instance(false) .validate( new MultiPolygon( Collections.singletonList( new Polygon( new LinearRing(new double[] { 3, 4, 5, 3 }, new double[] { 1, 2, 3, 1 }, new double[] { 1, 2, 3, 1 }) ) ) ) ) ); assertEquals("found Z value [1.0] but [ignore_z_value] parameter is [false]", ex.getMessage()); StandardValidator.instance(true) .validate( new MultiPolygon( Collections.singletonList( new Polygon(new LinearRing(new double[] { 3, 4, 5, 3 }, new double[] { 1, 2, 3, 1 }, new double[] { 1, 2, 3, 1 })) ) ) ); } public void testParseMultiPolygonZorMWithThreeCoordinates() throws IOException, ParseException { GeometryValidator validator = GeographyValidator.instance(true); MultiPolygon expected = new MultiPolygon( List.of( new Polygon( new LinearRing( new double[] { 20.0, 30.0, 40.0, 20.0 }, new double[] { 10.0, 15.0, 10.0, 10.0 }, new double[] { 100.0, 200.0, 300.0, 100.0 } ) ), new Polygon( new LinearRing( new double[] { 0.0, 10.0, 10.0, 0.0 }, new double[] { 0.0, 0.0, 10.0, 0.0 }, new double[] { 10.0, 20.0, 30.0, 10.0 } ) ) ) ); String polygonA = "(20.0 10.0 100.0, 30.0 15.0 200.0, 40.0 10.0 300.0, 20.0 10.0 100.0)"; String polygonB = "(0.0 0.0 10.0, 10.0 0.0 20.0, 10.0 10.0 30.0, 0.0 0.0 10.0)"; assertEquals(expected, WellKnownText.fromWKT(validator, true, "MULTIPOLYGON Z ((" + polygonA + "), (" + polygonB + "))")); assertEquals(expected, WellKnownText.fromWKT(validator, true, "MULTIPOLYGON M ((" + polygonA + "), (" + polygonB + "))")); } public void testParseMultiPolygonZorMWithTwoCoordinatesThrowsException() { GeometryValidator validator = GeographyValidator.instance(true); List<String> multiPolygonsWkt = List.of( "MULTIPOLYGON Z (((20.0 10.0, 30.0 15.0, 40.0 10.0, 20.0 10.0)), ((0.0 0.0, 10.0 0.0, 10.0 10.0, 0.0 0.0)))", "MULTIPOLYGON M (((20.0 10.0, 30.0 15.0, 40.0 10.0, 20.0 10.0)), ((0.0 0.0, 10.0 0.0, 10.0 10.0, 0.0 0.0)))" ); for (String multiPolygon : multiPolygonsWkt) { IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, () -> WellKnownText.fromWKT(validator, true, multiPolygon) ); assertEquals(ZorMMustIncludeThreeValuesMsg, ex.getMessage()); } } @Override protected MultiPolygon mutateInstance(MultiPolygon instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } }
MultiPolygonTests
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/MultiInterfaceResLocatorTest.java
{ "start": 1176, "end": 2942 }
class ____ { @RegisterExtension static QuarkusUnitTest testExtension = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { JavaArchive war = ShrinkWrap.create(JavaArchive.class); war.addClass(MultiInterfaceResLocatorIntf1.class); war.addClass(MultiInterfaceResLocatorIntf2.class); war.addClasses(PortProviderUtil.class, MultiInterfaceResLocatorResource.class, MultiInterfaceResLocatorSubresource.class); return war; } }); private String generateURL(String path) { return PortProviderUtil.generateURL(path, MultiInterfaceResLocatorTest.class.getSimpleName()); } /** * @tpTestDetails Test for resource with more interfaces. * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Test") public void test() throws Exception { Client client = ClientBuilder.newClient(); Response response = client.target(generateURL("/test/hello1")).request().get(); String entity = response.readEntity(String.class); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("resourceMethod1", entity, "Wrong content of response"); response = client.target(generateURL("/test/hello2")).request().get(); entity = response.readEntity(String.class); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertEquals("resourceMethod2", entity, "Wrong content of response"); client.close(); } }
MultiInterfaceResLocatorTest
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AsyncAppenderExceptionHandlingTest.java
{ "start": 2188, "end": 4587 }
class ____ { @ParameterizedTest @ValueSource( strings = { FailOnceAppender.ThrowableClassName.RUNTIME_EXCEPTION, FailOnceAppender.ThrowableClassName.LOGGING_EXCEPTION, FailOnceAppender.ThrowableClassName.EXCEPTION, FailOnceAppender.ThrowableClassName.ERROR, FailOnceAppender.ThrowableClassName.THROWABLE, FailOnceAppender.ThrowableClassName.THREAD_DEATH }) void AsyncAppender_should_not_stop_on_appender_failures(final String throwableClassName) { // Create the logger. final String throwableClassNamePropertyName = "throwableClassName"; System.setProperty(throwableClassNamePropertyName, throwableClassName); try (final LoggerContext loggerContext = Configurator.initialize("Test", "AsyncAppenderExceptionHandlingTest.xml")) { final Logger logger = loggerContext.getRootLogger(); // Log the 1st message, which should fail due to the FailOnceAppender. logger.info("message #1"); // Log the 2nd message, which should succeed. final String lastLogMessage = "message #2"; logger.info(lastLogMessage); // Stop the AsyncAppender to drain the queued events. final Configuration configuration = loggerContext.getConfiguration(); final AsyncAppender asyncAppender = configuration.getAppender("Async"); assertNotNull(asyncAppender, "couldn't obtain the FailOnceAppender"); asyncAppender.stop(); // Verify the logged message. final FailOnceAppender failOnceAppender = configuration.getAppender("FailOnce"); assertNotNull(failOnceAppender, "couldn't obtain the FailOnceAppender"); assertTrue(failOnceAppender.isFailed(), "FailOnceAppender hasn't failed yet"); final List<String> accumulatedMessages = failOnceAppender.drainEvents().stream() .map(LogEvent::getMessage) .map(Message::getFormattedMessage) .collect(Collectors.toList()); assertEquals(Collections.singletonList(lastLogMessage), accumulatedMessages); } finally { System.setProperty(throwableClassNamePropertyName, Strings.EMPTY); } } }
AsyncAppenderExceptionHandlingTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/metrics/KafkaConsumerMetrics.java
{ "start": 1353, "end": 5089 }
class ____ implements AutoCloseable { private final Metrics metrics; private final MetricName lastPollMetricName; private final Sensor timeBetweenPollSensor; private final Sensor pollIdleSensor; private final Sensor committedSensor; private final Sensor commitSyncSensor; private long lastPollMs; private long pollStartMs; private long timeSinceLastPollMs; public KafkaConsumerMetrics(Metrics metrics) { this.metrics = metrics; final String metricGroupName = CONSUMER_METRIC_GROUP; Measurable lastPoll = (mConfig, now) -> { if (lastPollMs == 0L) // if no poll is ever triggered, just return -1. return -1d; else return TimeUnit.SECONDS.convert(now - lastPollMs, TimeUnit.MILLISECONDS); }; this.lastPollMetricName = metrics.metricName("last-poll-seconds-ago", metricGroupName, "The number of seconds since the last poll() invocation."); metrics.addMetric(lastPollMetricName, lastPoll); this.timeBetweenPollSensor = metrics.sensor("time-between-poll"); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-avg", metricGroupName, "The average delay between invocations of poll() in milliseconds."), new Avg()); this.timeBetweenPollSensor.add(metrics.metricName("time-between-poll-max", metricGroupName, "The max delay between invocations of poll() in milliseconds."), new Max()); this.pollIdleSensor = metrics.sensor("poll-idle-ratio-avg"); this.pollIdleSensor.add(metrics.metricName("poll-idle-ratio-avg", metricGroupName, "The average fraction of time the consumer's poll() is idle as opposed to waiting for the user code to process records."), new Avg()); this.commitSyncSensor = metrics.sensor("commit-sync-time-ns-total"); this.commitSyncSensor.add( metrics.metricName( "commit-sync-time-ns-total", metricGroupName, "The total time the consumer has spent in commitSync in nanoseconds" ), new CumulativeSum() ); this.committedSensor = metrics.sensor("committed-time-ns-total"); this.committedSensor.add( metrics.metricName( "committed-time-ns-total", metricGroupName, "The total time the consumer has spent in committed in nanoseconds" ), new CumulativeSum() ); } public void recordPollStart(long pollStartMs) { this.pollStartMs = pollStartMs; this.timeSinceLastPollMs = lastPollMs != 0L ? pollStartMs - lastPollMs : 0; this.timeBetweenPollSensor.record(timeSinceLastPollMs); this.lastPollMs = pollStartMs; } public void recordPollEnd(long pollEndMs) { long pollTimeMs = pollEndMs - pollStartMs; double pollIdleRatio = pollTimeMs * 1.0 / (pollTimeMs + timeSinceLastPollMs); this.pollIdleSensor.record(pollIdleRatio); } public void recordCommitSync(long duration) { this.commitSyncSensor.record(duration); } public void recordCommitted(long duration) { this.committedSensor.record(duration); } @Override public void close() { metrics.removeMetric(lastPollMetricName); metrics.removeSensor(timeBetweenPollSensor.name()); metrics.removeSensor(pollIdleSensor.name()); metrics.removeSensor(commitSyncSensor.name()); metrics.removeSensor(committedSensor.name()); } }
KafkaConsumerMetrics
java
quarkusio__quarkus
extensions/oidc-client/runtime/src/main/java/io/quarkus/oidc/client/runtime/OidcClientsImpl.java
{ "start": 6169, "end": 7228 }
class ____ { private final Vertx vertx; private final Set<Long> timerIds; private PeriodicTask(Vertx vertx) { this.vertx = vertx; this.timerIds = new CopyOnWriteArraySet<>(); } private void add(CancellableTask task, Duration refreshInterval) { final long timerId = scheduleTask(task, refreshInterval); timerIds.add(timerId); } private void cancel() { for (long timerId : timerIds) { vertx.cancelTimer(timerId); } } private long scheduleTask(CancellableTask task, Duration refreshInterval) { final long timerId = vertx.setPeriodic(0L, refreshInterval.toMillis(), task); task.cancel = new Runnable() { @Override public void run() { timerIds.remove(timerId); vertx.cancelTimer(timerId); } }; return timerId; } } private static abstract
PeriodicTask
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/HazelcastSedaEndpointBuilderFactory.java
{ "start": 1679, "end": 11854 }
interface ____ extends EndpointConsumerBuilder { default AdvancedHazelcastSedaEndpointConsumerBuilder advanced() { return (AdvancedHazelcastSedaEndpointConsumerBuilder) this; } /** * To specify a default operation to use, if no operation header has * been provided. * * The option is a: * <code>org.apache.camel.component.hazelcast.HazelcastOperation</code> * type. * * Group: common * * @param defaultOperation the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder defaultOperation(org.apache.camel.component.hazelcast.HazelcastOperation defaultOperation) { doSetProperty("defaultOperation", defaultOperation); return this; } /** * To specify a default operation to use, if no operation header has * been provided. * * The option will be converted to a * <code>org.apache.camel.component.hazelcast.HazelcastOperation</code> * type. * * Group: common * * @param defaultOperation the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder defaultOperation(String defaultOperation) { doSetProperty("defaultOperation", defaultOperation); return this; } /** * Hazelcast configuration file. * * This option can also be loaded from an existing file, by prefixing * with file: or classpath: followed by the location of the file. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param hazelcastConfigUri the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder hazelcastConfigUri(String hazelcastConfigUri) { doSetProperty("hazelcastConfigUri", hazelcastConfigUri); return this; } /** * The hazelcast instance reference which can be used for hazelcast * endpoint. * * The option is a: <code>com.hazelcast.core.HazelcastInstance</code> * type. * * Group: common * * @param hazelcastInstance the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder hazelcastInstance(com.hazelcast.core.HazelcastInstance hazelcastInstance) { doSetProperty("hazelcastInstance", hazelcastInstance); return this; } /** * The hazelcast instance reference which can be used for hazelcast * endpoint. * * The option will be converted to a * <code>com.hazelcast.core.HazelcastInstance</code> type. * * Group: common * * @param hazelcastInstance the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder hazelcastInstance(String hazelcastInstance) { doSetProperty("hazelcastInstance", hazelcastInstance); return this; } /** * The hazelcast instance reference name which can be used for hazelcast * endpoint. If you don't specify the instance reference, camel use the * default hazelcast instance from the camel-hazelcast instance. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param hazelcastInstanceName the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder hazelcastInstanceName(String hazelcastInstanceName) { doSetProperty("hazelcastInstanceName", hazelcastInstanceName); return this; } /** * To use concurrent consumers polling from the SEDA queue. * * The option is a: <code>int</code> type. * * Default: 1 * Group: seda * * @param concurrentConsumers the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder concurrentConsumers(int concurrentConsumers) { doSetProperty("concurrentConsumers", concurrentConsumers); return this; } /** * To use concurrent consumers polling from the SEDA queue. * * The option will be converted to a <code>int</code> type. * * Default: 1 * Group: seda * * @param concurrentConsumers the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder concurrentConsumers(String concurrentConsumers) { doSetProperty("concurrentConsumers", concurrentConsumers); return this; } /** * Milliseconds before consumer continues polling after an error has * occurred. * * The option is a: <code>int</code> type. * * Default: 1000 * Group: seda * * @param onErrorDelay the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder onErrorDelay(int onErrorDelay) { doSetProperty("onErrorDelay", onErrorDelay); return this; } /** * Milliseconds before consumer continues polling after an error has * occurred. * * The option will be converted to a <code>int</code> type. * * Default: 1000 * Group: seda * * @param onErrorDelay the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder onErrorDelay(String onErrorDelay) { doSetProperty("onErrorDelay", onErrorDelay); return this; } /** * The timeout used when consuming from the SEDA queue. When a timeout * occurs, the consumer can check whether it is allowed to continue * running. Setting a lower value allows the consumer to react more * quickly upon shutdown. * * The option is a: <code>int</code> type. * * Default: 1000 * Group: seda * * @param pollTimeout the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder pollTimeout(int pollTimeout) { doSetProperty("pollTimeout", pollTimeout); return this; } /** * The timeout used when consuming from the SEDA queue. When a timeout * occurs, the consumer can check whether it is allowed to continue * running. Setting a lower value allows the consumer to react more * quickly upon shutdown. * * The option will be converted to a <code>int</code> type. * * Default: 1000 * Group: seda * * @param pollTimeout the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder pollTimeout(String pollTimeout) { doSetProperty("pollTimeout", pollTimeout); return this; } /** * If set to true then the consumer runs in transaction mode, where the * messages in the seda queue will only be removed if the transaction * commits, which happens when the processing is complete. * * The option is a: <code>boolean</code> type. * * Default: false * Group: seda * * @param transacted the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder transacted(boolean transacted) { doSetProperty("transacted", transacted); return this; } /** * If set to true then the consumer runs in transaction mode, where the * messages in the seda queue will only be removed if the transaction * commits, which happens when the processing is complete. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: seda * * @param transacted the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder transacted(String transacted) { doSetProperty("transacted", transacted); return this; } /** * If set to true the whole Exchange will be transfered. If header or * body contains not serializable objects, they will be skipped. * * The option is a: <code>boolean</code> type. * * Default: false * Group: seda * * @param transferExchange the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder transferExchange(boolean transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } /** * If set to true the whole Exchange will be transfered. If header or * body contains not serializable objects, they will be skipped. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: seda * * @param transferExchange the value to set * @return the dsl builder */ default HazelcastSedaEndpointConsumerBuilder transferExchange(String transferExchange) { doSetProperty("transferExchange", transferExchange); return this; } } /** * Advanced builder for endpoint consumers for the Hazelcast SEDA component. */ public
HazelcastSedaEndpointConsumerBuilder
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonQueueTest.java
{ "start": 1337, "end": 2581 }
class ____ { private String key; private String traceId; private long createdAt; private UUID uuid = UUID.randomUUID(); public TestModel() { } public TestModel(String key, String traceId, long createdAt) { this.key = key; this.traceId = traceId; this.createdAt = createdAt; } } @Test public void testRemoveWithCodec() { RQueue<TestModel> queue = redisson.getQueue("queue"); TestModel msg = new TestModel("key", "traceId", 0L); queue.add(msg); assertThat(queue.contains(queue.peek())).isTrue(); } @Test public void testRemove() { RQueue<Integer> queue = getQueue(); queue.add(1); queue.add(2); queue.add(3); queue.add(4); queue.remove(); queue.remove(); assertThat(queue).containsExactly(3, 4); queue.remove(); queue.remove(); Assertions.assertTrue(queue.isEmpty()); } @Test public void testRemoveEmpty() { Assertions.assertThrows(NoSuchElementException.class, () -> { RQueue<Integer> queue = getQueue(); queue.remove(); }); } }
TestModel
java
netty__netty
handler-proxy/src/test/java/io/netty/handler/proxy/ProxyHandlerTest.java
{ "start": 28494, "end": 30422 }
class ____ { final String name; final InetSocketAddress destination; final ChannelHandler[] clientHandlers; protected TestItem(String name, InetSocketAddress destination, ChannelHandler... clientHandlers) { this.name = name; this.destination = destination; this.clientHandlers = clientHandlers; } abstract void test() throws Exception; protected void assertProxyHandlers(boolean success) { for (ChannelHandler h: clientHandlers) { if (h instanceof ProxyHandler) { ProxyHandler ph = (ProxyHandler) h; String type = StringUtil.simpleClassName(ph); Future<Channel> f = ph.connectFuture(); if (!f.isDone()) { logger.warn("{}: not done", type); } else if (f.isSuccess()) { if (success) { logger.debug("{}: success", type); } else { logger.warn("{}: success", type); } } else { if (success) { logger.warn("{}: failure", type, f.cause()); } else { logger.debug("{}: failure", type, f.cause()); } } } } for (ChannelHandler h: clientHandlers) { if (h instanceof ProxyHandler) { ProxyHandler ph = (ProxyHandler) h; assertTrue(ph.connectFuture().isDone()); assertEquals(ph.connectFuture().isSuccess(), success); } } } @Override public String toString() { return name; } } private static final
TestItem
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/ConstructorDetectorTest.java
{ "start": 3187, "end": 3660 }
class ____ { private final Boolean field; // @JsonCreator gone! public Input3241(@ImplicitName("field") Boolean field) { if (field == null) { throw new NullPointerException("Field should not remain null!"); } this.field = field; } public Boolean field() { return field; } } // [databind#4860] @JsonPropertyOrder({ "id", "name "}) static
Input3241
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/MinLongAggregatorFunctionTests.java
{ "start": 735, "end": 1611 }
class ____ extends AggregatorFunctionTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { long max = randomLongBetween(1, Long.MAX_VALUE / size); return new SequenceLongBlockSourceOperator(blockFactory, LongStream.range(0, size).map(l -> randomLongBetween(-max, max))); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new MinLongAggregatorFunctionSupplier(); } @Override protected String expectedDescriptionOfAggregator() { return "min of longs"; } @Override public void assertSimpleOutput(List<Page> input, Block result) { long min = input.stream().flatMapToLong(p -> allLongs(p.getBlock(0))).min().getAsLong(); assertThat(((LongBlock) result).getLong(0), equalTo(min)); } }
MinLongAggregatorFunctionTests
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/multiplepersistenceunits/MultiplePersistenceUnitsCdiStatelessSessionTest.java
{ "start": 793, "end": 2668 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(DefaultEntity.class) .addClass(User.class) .addClass(Plane.class) .addAsResource("application-multiple-persistence-units.properties", "application.properties")); @Inject StatelessSession defaultSession; @Inject @PersistenceUnit("users") StatelessSession usersSession; @Inject @PersistenceUnit("inventory") StatelessSession inventorySession; @Test @Transactional public void defaultEntityManagerInTransaction() { DefaultEntity defaultEntity = new DefaultEntity("default"); defaultSession.insert(defaultEntity); DefaultEntity savedDefaultEntity = defaultSession.get(DefaultEntity.class, defaultEntity.getId()); assertEquals(defaultEntity.getName(), savedDefaultEntity.getName()); } @Transactional public void usersEntityManagerInTransaction() { User user = new User("gsmet"); usersSession.insert(user); User savedUser = usersSession.get(User.class, user.getId()); assertEquals(user.getName(), savedUser.getName()); } @Test @Transactional public void inventoryEntityManagerInTransaction() { Plane plane = new Plane("Airbus A380"); inventorySession.insert(plane); Plane savedPlane = inventorySession.get(Plane.class, plane.getId()); assertEquals(plane.getName(), savedPlane.getName()); } @Test @Transactional public void testUserInInventorySession() { User user = new User("gsmet"); assertThatThrownBy(() -> inventorySession.insert(user)).isInstanceOf(UnknownEntityTypeException.class); } }
MultiplePersistenceUnitsCdiStatelessSessionTest
java
apache__camel
components/camel-knative/camel-knative-api/src/generated/java/org/apache/camel/component/knative/spi/KnativeSinkBindingConfigurer.java
{ "start": 730, "end": 2960 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.knative.spi.KnativeSinkBinding target = (org.apache.camel.component.knative.spi.KnativeSinkBinding) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "name": target.setName(property(camelContext, java.lang.String.class, value)); return true; case "objectapiversion": case "objectApiVersion": target.setObjectApiVersion(property(camelContext, java.lang.String.class, value)); return true; case "objectkind": case "objectKind": target.setObjectKind(property(camelContext, java.lang.String.class, value)); return true; case "type": target.setType(property(camelContext, org.apache.camel.component.knative.spi.Knative.Type.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "name": return java.lang.String.class; case "objectapiversion": case "objectApiVersion": return java.lang.String.class; case "objectkind": case "objectKind": return java.lang.String.class; case "type": return org.apache.camel.component.knative.spi.Knative.Type.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.knative.spi.KnativeSinkBinding target = (org.apache.camel.component.knative.spi.KnativeSinkBinding) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "name": return target.getName(); case "objectapiversion": case "objectApiVersion": return target.getObjectApiVersion(); case "objectkind": case "objectKind": return target.getObjectKind(); case "type": return target.getType(); default: return null; } } }
KnativeSinkBindingConfigurer
java
grpc__grpc-java
xds/third_party/zero-allocation-hashing/test/java/io/grpc/xds/XxHash64Test.java
{ "start": 5097, "end": 64858 }
class ____ { @SuppressWarnings("ConstantOverflow") @Test public void collisionTest() { XxHash64 f = XxHash64.INSTANCE; ByteBuffer sequence = ByteBuffer.allocate(128); sequence.order(ByteOrder.LITTLE_ENDIAN); sequence.putLong(0, 1); sequence.putLong(16, 42); sequence.putLong(32, 2); long h1 = f.hashBytes(sequence.array()); sequence.putLong(0, 1 + 0xBA79078168D4BAFL); sequence.putLong(32, 2 + 0x9C90005B80000000L); long h2 = f.hashBytes(sequence.array()); assertEquals(h1, h2); sequence.putLong(0, 1 + 0xBA79078168D4BAFL * 2); sequence.putLong(32, 2 + 0x9C90005B80000000L * 2); long h3 = f.hashBytes(sequence.array()); assertEquals(h2, h3); } } /* * Test data is output of the following program with xxHash implementation * from https://github.com/Cyan4973/xxHash * * #include "xxhash.c" * #include <stdlib.h> * #include <stdio.h> * int main() * { * char* src = (char*) malloc(1024); * const int N = 1024; * for (int i = 0; i < N; i++) { * src[i] = (char) i; * } * * printf("without seed\n"); * for (int i = 0; i <= N; i++) { * printf("%lldL,\n", (long long) XXH64(src, i, 0)); * } * * printf("with seed 42\n"); * for (int i = 0; i <= N; i++) { * printf("%lldL,\n", (long long) XXH64(src, i, 42)); * } * } */ private static final long[] HASHES_OF_LOOPING_BYTES_WITHOUT_SEED = { -1205034819632174695L, -1642502924627794072L, 5216751715308240086L, -1889335612763511331L, -13835840860730338L, -2521325055659080948L, 4867868962443297827L, 1498682999415010002L, -8626056615231480947L, 7482827008138251355L, -617731006306969209L, 7289733825183505098L, 4776896707697368229L, 1428059224718910376L, 6690813482653982021L, -6248474067697161171L, 4951407828574235127L, 6198050452789369270L, 5776283192552877204L, -626480755095427154L, -6637184445929957204L, 8370873622748562952L, -1705978583731280501L, -7898818752540221055L, -2516210193198301541L, 8356900479849653862L, -4413748141896466000L, -6040072975510680789L, 1451490609699316991L, -7948005844616396060L, 8567048088357095527L, -4375578310507393311L, -3749919242623962444L, 888155921178136237L, -228195649085979072L, -521095004075279741L, -2458702038214709156L, -2792334161285995319L, 7509323632532862410L, 46046374822258777L, -731200582691896855L, 933917387460394992L, 5623144551929396680L, 6456984547425914359L, -6398540474588876142L, 1224372500617079775L, -931727396974525131L, 979677643219401656L, -8078270932489049756L, -92767506898879473L, 2379112167176776082L, 2065719310945572007L, -4972682801816081667L, -7346559332994187462L, 4674729779638751546L, 5844780159702313017L, 925606237565008152L, 8164325403643669774L, 5124005065773312983L, -4646462236086916483L, 4733593776494364101L, -6408850806317360L, 7405089268865026700L, -2131704682637193649L, -592659849139514384L, -4386868621773355429L, -2216833672566288862L, 4022619316305276641L, -60464713570988944L, 2416749694506796597L, 3576590985110933976L, 3368688771415645536L, -357157638897078259L, 3484358739758473117L, 2078888409435083535L, 8053093288416703076L, -4934736471585554038L, -7784370683223414061L, -4109284735634941390L, 5982490102027564625L, -4991107002810882893L, 8664747912276562373L, 8536879438728327651L, 2358675440174594061L, 5352236919104495867L, 6340852522718110192L, 5075606340464035668L, -6313168920073458239L, -6428599582591385786L, -7278654800402467208L, -6630626099856243581L, -7548742438664634646L, 5514383762309532642L, -5996126265702944431L, 4011116741319319261L, -7289240093981845088L, 4975257207486779926L, -3945500877932691916L, 1973955144068521079L, 3884425912161913184L, 7692681977284421015L, -1616730378439673826L, 4799493270916844476L, -6107310582897997679L, 3643294092300179537L, 5406040598516899149L, -3032420409304067208L, 5044227119457305622L, 9165032773225506149L, 7553488247682850248L, 2247298339072845043L, 7380491470304042584L, -456791943260357427L, -1906500292613319324L, -4025157985304129897L, 6167829983725509611L, -8678196943431064825L, -636391087313417831L, 5757999497725839182L, 8999325347316115948L, -6042339776328081249L, 7988836354190359013L, 2818448030979902104L, -8484201484113382447L, -1140175406473847155L, 3042776987426497381L, 3147338037480432386L, 5065714330193756569L, 8827021486636772242L, 838335823706922959L, 481844220820054909L, 5333474685474667077L, -3722898251196013565L, 7909417627390150381L, 7116148225996109646L, 7520381989775811302L, 6045444672904719015L, 169039646730338133L, -2144629916252757106L, -3752608501798118554L, 8374704774878780935L, -5830926781667225570L, 3202139393110256022L, 4400219135677717216L, -5663710220155589201L, -2589002340345751622L, -8240133511464343390L, -4036798392879835146L, 501599054729008501L, -4851415719238782188L, 7565157933617774080L, -6428091359957700043L, 4081845077806300175L, -9016659258880122392L, 7811786097015457596L, 1357606791019752376L, 6522211979684949668L, -3462397075047559451L, 3075504459164148117L, 3055992297861390732L, -7230492327399411047L, -1128103378253532506L, 1834607408788151585L, 7065978976369231860L, 6566122632438908362L, -3440855531356735824L, 6271453770746181891L, 413365468403580071L, -8342682158827061522L, -3713303136987568731L, -8959326895824091541L, -2793862582117663595L, -184756427409317729L, -7052502019782453427L, 3666196071825438258L, 170204095295428634L, -1880693509859077843L, 5179169206996749826L, 2866097700453114958L, 1859104195026275510L, 3782323564639128125L, -6485194456269981193L, 6761934873296236857L, 5764605515941066448L, 597754945258033208L, -4888986062036739232L, -6490228233091577705L, 3234089784845854336L, -5506883591180767430L, 1491493862343818933L, 3232293217886687768L, -4079803366160739972L, 4884134040093556099L, -7274733680156962461L, 5265680254123454403L, 1036855740788018258L, 423439784169709263L, -3627743032115866622L, -6311378083791982305L, -3058076915688265687L, 5826550132901840796L, 8049712006832885455L, 1707844692241288946L, -3293048440386932248L, -2458638193238955307L, 943059295184967928L, 3899561579431348819L, -1516862862245909493L, 4448476568037673976L, 8738531437146688925L, -1033913449611929894L, 733668166271378558L, 438686375775205249L, -4325889118346169305L, -238178883117433622L, -7972205050662019794L, -1263398103237492853L, -8333197763892905802L, 7796341294364809534L, -1381767618016537445L, 2892579485651013970L, -3376209887503828920L, -8575120126045607817L, -1609355362031172055L, -386138918275547508L, 4598874691849543747L, -2961781601824749597L, -3032925351997820092L, -4256249198066449735L, 6712291718681474012L, -4281614253751277086L, 3727487933918100016L, -2744649548868700294L, 8662377383917584333L, -9154398439761221404L, -6895275824272461794L, 3394857180017540444L, 2010825527298793302L, 4894417464710366872L, -6879244364314087051L, 83677167865178033L, -8258406393927169823L, 5042126978317943321L, 6485279223034053259L, 4442956705009100620L, 316801800427881731L, 1381431847939703076L, 5172932759041399062L, -69656533526213521L, -5302643413630076306L, -3956089084400440856L, 372087412941022771L, 4711314482928419386L, 3255220726505012060L, 8917854303046844847L, 1116214654602499731L, 2282408585429094475L, -9207590323584417562L, 8881688165595519866L, 1731908113181957442L, 3847295165012256987L, 4457829016858233661L, 4944046822375522396L, 3445091217248591320L, -5055680960069278553L, -399195423199498362L, -8109174165388156886L, 4967185977968814820L, -5911973391056763118L, 2239508324487797550L, -954783563382788523L, 8523699184200726144L, 932575865292832326L, -7491448407022023047L, 1809887519026638446L, -8610524715250756725L, 6158809695983348998L, 4948400960714316843L, -4513370424175692831L, -3955280856263842959L, 6440233015885550592L, 8756942107256956958L, 7895095834297147376L, 370033091003609904L, 948078545203432448L, -8523229038380945151L, 100794871657160943L, -2186420796072284323L, -9221115378196347951L, 8102537654803861332L, 5857339063191690550L, -4554257374958739421L, 6607496554818971053L, -778402196622557070L, -3817535277727878318L, 3564122000469288769L, -44446230828995950L, 1322708749649533240L, 6150374672341998205L, -3300275952549095391L, 5700833512536085850L, -8559358370491270937L, 5434443260519512697L, -8031025173259990945L, 7117462129248544172L, 5425177419943569451L, -7215427371174054838L, -5728669976971194528L, -2096361446095323077L, -4247416835972286805L, 4912769047482466787L, 7755341152739082452L, 6797061233443658471L, 4089361562209715474L, 5830701413838808929L, 5514515889578551370L, 609334005368729318L, 177310574483850759L, -820431153866372784L, 7188454041446661654L, 7480194911613035473L, 4564607884390103056L, 888496928954372093L, -5480535802290619117L, 9100964700413324707L, 510523132632789099L, 8249362675875046694L, 5340321809639671537L, -4633081050124361874L, -839915092967986193L, -7377542419053401928L, 1820485955145562839L, 8517645770425584256L, -1877318739474090786L, 7674371564231889244L, -3311130470964498678L, -880090321525066135L, -5670998531776225745L, -8828737503035152589L, -6029750416835830307L, -6535608738168818581L, -550872341393232043L, 2831504667559924912L, -4613341433216920241L, 502960879991989691L, 576723875877375776L, -2575765564594953903L, -4642144349520453953L, 7939746291681241029L, 6486356905694539404L, -9086235573768687853L, 5369903658359590823L, 3199947475395774092L, 8384948078622146995L, -3365598033653273878L, -2525526479099052030L, 2648498634302427751L, 3715448294999624219L, -4734466095330028983L, -8440427851760401644L, -371198022355334589L, 8864079431738600817L, -4205600060099565684L, 6617166152874298882L, -6515522971156180292L, 7254251246745292298L, -420587237082849417L, 1190495815435763349L, -474540026828753709L, -8150622114536376016L, -5790621848044235275L, -2780522220219318167L, -2991155855957250848L, 1692932912262846366L, 8814949734565782733L, -8746818869495012552L, 7931250816026891600L, -7434629709560596700L, 4388261932396122996L, 7154847153195510802L, -2810154398655124882L, 2601892684639182965L, 7781574423676509607L, -6647000723020388462L, -8679132292226137672L, -2447013202020963672L, 3658855631326217196L, 2176620921764007759L, 3654402165357492705L, 4511989090021652156L, -3254638803798424003L, 9050506214967102331L, 922579360317805810L, 609820949221381248L, 5723875594772949290L, 4637721466210023638L, 6195303339320487374L, -38202587086649325L, -2142927092331878341L, 5355751314914287101L, -7170892783575760055L, -7506612729078573199L, 8645580445823695595L, 3221950179890871958L, 1638211443525398634L, 7356718304253861777L, -296260062751271549L, -1790105985391377345L, -7004118620405119098L, 7056012094479909462L, -7673357898031223798L, -8929502135696203556L, 7527161467311997998L, 6182865571027510002L, -2163310275402596869L, 6285112477695252864L, 3703909999924067987L, 962491298117560533L, 138936592567072793L, 6094857527471100960L, 5914305068838335718L, -8896724991235492552L, -2667562314507789198L, -7456492499188304500L, -3422709784851063201L, -1511644999824238281L, -7130158069449057322L, 6243266426571961929L, 2713895636371672711L, 5765589573821453640L, 2624585483746388367L, 3933828437519859601L, -5664404238108533781L, 7086393398544811684L, 1322058227068490376L, -8232508114671021371L, -5963804389649678229L, -3318229976491806899L, -6261789542948241754L, 199130260709663583L, 7521707465510595039L, 507353862067534334L, -7737968456769005928L, -8964687882992257099L, -7735003539801528311L, 6989812739838460574L, -6986289777499051441L, 1881562796144865699L, -6077719780113966592L, -5427071388091979746L, 1660707436425817310L, -4338189980197421104L, 5330934977599207307L, 4461280425701571033L, -7426107478263746863L, 4258305289832328199L, -8003283151332860979L, -2500604212764835216L, -8883941775298564436L, -5059709834257638733L, -4582947579039913741L, 1371959565630689983L, -1925163414161391371L, -1180269729544278896L, -6603171789097590304L, 8985062706306079731L, -3588748723254272836L, -6052032019910018725L, 6200960040430493088L, 2146343936795524980L, 7785948646708747443L, 4524411768393719400L, 749211414228926779L, -163844243342465015L, 1066801203344117463L, -3687825939602944988L, -4873811917429870500L, -3765115783578949524L, 3344884226049804020L, -22793631121165636L, -5636541624133159076L, -6201449576244177151L, -4533734412127714050L, -2064657727206266594L, -1325853623186040989L, -2651306529045029511L, 903264360879626406L, 6082283797495873520L, 6185446819995987847L, -5727850940826115079L, 8356646143516726527L, -7705915341280821272L, 9137633133909463406L, 6613483969797411894L, 8598514961735984460L, 6805925079991408361L, 6009403222422527608L, 2216303622650116705L, -3736062178532154638L, -7139008962939637477L, -1537711200058404375L, 8896755073380580322L, -6063426810787442347L, -3472064301690015285L, -4568131486464952371L, -8141256104294687045L, 5627435360893599536L, 1136003802967708029L, 2730027518034735037L, 1985287040172139729L, -3643431491383365431L, -9042919736106376701L, 8879968900590373568L, 8504486139877409399L, 5832665747670146536L, 4202923651402292496L, 1738511892080946286L, 4512683881549777042L, 9200194457599870145L, -1948301178705617139L, 8655715314401162523L, 412698981651521600L, -1479274044808688580L, 2688302549664693359L, -3059920027366623178L, -4275753325231806565L, -8321791698013769889L, -3678119714812414102L, -2500922551770832553L, 9018541633115002061L, 5713301371152396803L, 4180584812840471799L, 3062416401091271879L, -8125716681035757962L, -2076056159878596225L, 8855540523533374738L, 2402007906402689092L, 2020584786288649542L, 1707405964421070701L, -3681994462249973122L, -3982567775984742012L, 7133200226358561844L, -5270514263562558963L, 9060760368219219429L, -6967162372382490281L, -9094664463528453384L, -3968518633408880046L, 8618660189330281694L, -4668946581954397558L, -8596433172676363407L, -1264942061713169049L, -5309493221793643795L, -1099320768477039529L, 8925041285873295227L, -6809278181760513499L, -7039439984223885585L, 6188209901527865226L, 1487353394192637059L, 2402097349430126337L, -3818359601525025681L, 4123217079279439249L, -1424515143377220376L, 1742298536803356877L, -2836832784751148874L, -4838603242771410698L, 2383745618623084414L, -2790832243316548423L, -1176683649587660160L, 1862928178605117401L, 5208694030074527671L, 4339841406618876548L, -7704801448691668472L, 500068664415229033L, -2111184635274274347L, -1387769336519960517L, -2368660677263980293L, -4980481392402938776L, -6856361166068680884L, 1708658704968066797L, -9013068514618931938L, -2616479975851677179L, 7121103440247327570L, -7094192881960646061L, -4042342930006488618L, 5294323611741266775L, 5235545113690922502L, -2562011392475214878L, -4613304566070234734L, -3784386310583029381L, -4526148219816534267L, -8643470129031767968L, -4573761335510927866L, -8255399593563317902L, -1925488377092111963L, -1747797357090594237L, 7292772921748919564L, 3951718848780851600L, 5339305877764077075L, 7889570407201305102L, -8935437555550449315L, -1858205318388884024L, 381779657795494278L, -3769854251228686168L, -7957724087073627355L, 4349540075286824743L, -2476434494603040708L, -4506107235113109706L, -7120863144673563848L, -8534342596639587598L, 2205658724629050493L, 604438195864305027L, 4530331938860561927L, -2074141653226683751L, -1114378227875974007L, 3377301950002508302L, 5369356700690664306L, -1747063224581819445L, -6320380781966280801L, -2075443262555773155L, 1028541493355576591L, -4694402890123574860L, -5250660999767019003L, 3847087895315315136L, -4448050214964317066L, -4591316307978008151L, 4894820902772635901L, 3088847887353411593L, -6699208183127463352L, 4636731998354510780L, 9095126525233209263L, 4135373626035182291L, 3835688804093949701L, -3490782692819028324L, -561453348486424761L, -3329283619698366365L, 3251154327320814221L, -8006986328190314286L, 5856651505286251345L, -8871425101391073L, 7806993676637210959L, 7586479850833664643L, -7091216108599847229L, -3410137297792125447L, -8251963871271100526L, -8849730915506517177L, 8400334327557485676L, 1676125861848906502L, -8480324002538122254L, -1402216371589796114L, 5951911012328622382L, 8596811512609928773L, -2266336480397111285L, -8840962712683931463L, 4301675602445909557L, 1843369157327547440L, 2169755460218905712L, -1592865257954325910L, -8763867324602133653L, -4283855559993550994L, -7577702976577664015L, -5152834259238990784L, 4596243922610406362L, -4326545138850544854L, 1480440096894990716L, 8548031958586152418L, 6705615952497668303L, -2915454802887967935L, -6137002913510169520L, 2908515186908319288L, 5834242853393037250L, -6721431559266056630L, -7810820823419696676L, 1954209413716096740L, 6657013078387802473L, 2214178984740031680L, 8789512881373922013L, 1240231669311237626L, 8694612319028097761L, 492180561068515854L, -6047127535609489112L, 7436686740711762797L, -4520261623507558716L, 938282189116272147L, 3232025564608101134L, -5425498066931840551L, 932123105892452494L, 9054941090932531526L, 8066693670021084601L, 764877609198828864L, -489112437588815338L, 4827691353685521957L, 1948321254606741278L, 6117773063719937712L, 4645962658121906639L, -7846887104148029590L, 4210795945791252618L, -8879516722990993098L, -2621063563373927241L, 2094675051444850863L, -8681225697045319537L, 6072534474938492189L, 6181923696407824226L, 5463607676777614919L, 3708342890820711111L, 8844501223821777366L, -1459359143442302680L, 2225439088478089068L, -3866259492807347627L, 5715020051188773955L, 3922300588924895992L, -9142841818158905228L, 2234845285375211931L, 2466598091809457099L, -5086614780930363190L, -59740786891006359L, 3484340182077240897L, 5684798394905475931L, 8492255409537329167L, 5276601975076232447L, -723955912320185993L, 9032937149732310432L, 2226206333274026280L, 5631303328800272036L, 3943832708526382713L, -3756282686478033644L, -5407377327559185078L, 2025162219823732106L, -8802502232162774782L, 9039368856081455195L, 663058667658971174L, 3624269418844967319L, 1835338408542062149L, 6821836507221295281L, 6273547355770435776L, -3104373869480308814L, 1150888014781722836L, 7638478751521711777L, -6407096352658729423L, -2242514077180426481L, -3181824045541296523L, -4562287221569080073L, -5550768647534615669L, -5786611484859469238L, -6147722345444149090L, 3737249616177808079L, 3401215612108618403L, -713522925214097648L, 7938558781452631257L, -2822931074351003413L, -6484774850345918944L, 3384659068511379086L, 6976459554734427695L, 4254162229878558339L, -3312164339867139602L, 7263045146222903358L, 4561625003713187235L, -3350421200373539593L, -6329267008823047447L, -6889593333717619051L, -6470291206680780949L, -1925391510610223335L, 4955720513801530785L, -6515999401129420095L, -5146900596178823847L, 2572121582663686783L, -4958678197003031937L, -1295912792184970105L, -8320363273488883198L, -8213501149234986129L, -3883775881968950160L, -8925953418077243474L, 3199784299548492168L, -6836506744583692202L, -5007347279129330642L, 7387675960164975441L, -5841389805259238070L, 6263589037534776610L, 3327727201189139791L, 3673450414312153409L, -1563909967243907088L, -3758518049401683145L, 6368282934319908146L, -6025191831649813215L, 1223512633484628943L, -8540335264335924099L, -8569704496403127098L, -5712355262561236939L, -6468621715016340600L, 7015005898276272746L, -1037164971883038884L, -6108649908647520338L, -6781540054819591698L, -2762739023866345855L, -270930832663123436L, -2387080926579956105L, -3984603512651136889L, 2367015942733558542L, 2997123688964990405L, -424413420483149165L, 2906467516125124288L, 7979917630945955701L, 2879736983084566817L, 558436267366797870L, 6471658168855475843L, -3453803644372811678L, 95470628886709014L, 5666911245054448862L, 1594133734978640945L, 3790246368687946045L, 8636400206261643605L, 5901994795106283147L, -6774812279971490610L, -4622588246534854941L, 5395884908872287278L, 7381412950348018556L, 5461775216423433041L, 2851500852422732203L, 1153428834012773824L, 2567326223464897798L, 6290362916558214218L, 6095765709335097474L, -3526424734043456674L, -8411274175041022530L, 7565408328520233290L, -1318636864706103626L, 1261242784453012654L, -472643963000448611L, -7126293899612852456L, 5072187962931197668L, 4775251504230927816L, -1624676500499667689L, 2252385971292411863L, 7908437759266752884L, -8948829914565397845L, 5258787823809553293L, 3885696202809019506L, -4551784314460062669L, 5315762970089305011L, 7218180419200466576L, 109471822471146966L, 3901499100759315793L, -5613018173558603696L, 5782419706003468119L, 8285176821902721729L, -2944182278904878473L, 8089487615165958290L, 6934039118340963316L, 8481603619533191729L, -6321491167299496492L, 6441589800192421521L, 6436057639713571196L, 6819921695214365155L, 1185928916708893611L, 2597068862418243401L, -7637601550649263782L, 9129303862479379164L, 4047905726243458335L, 6672087858539795207L, -4841432774404255351L, 5501215987763227677L, -5300305896512100453L, 1635946349436492617L, -5017459781050596604L, -7313558338536196566L, 4625509831332846264L, -1241826701278444028L, 2916178164108211239L, -6947453283344846915L, 5520544791845620925L, 5009241392834567026L, -630825152277572403L, 6246654103747517292L, -5632205909016659384L, -5099826214945383802L, 2466330894206710401L, -1463559257726812272L, 4922422449110036517L, -4940410396057186660L, 8835766963654337957L, -1984334093384497740L, 5616151800825184227L, -8442970605804311782L, -5396399970392474268L, 2711274356126287353L, -5090439840321959043L, 6638617029380445409L, -6424875729377006548L, -7243574969986334324L, -904268348341193502L, -6196811069886893217L, -7742123331454617135L, 1449632469607275832L, 3212140938119717436L, 8676942774083692265L, -6625590425417154859L, 8720904664575676760L, 9151723732605931383L, 7642401923610349184L, -3454390566366389884L, -232373658792783206L, -8933620623437682010L, 2514068248201398743L, 6757007617821370359L, -2870340646674679163L, 416331333845426881L, -5319172016123138702L, 3294412564645954555L, 2812538484970453169L, -9128349093860081905L, 6784456254618976198L, -2861881330654872638L, 3912429093271518508L, -2562542119887175820L, 4835616088583228965L, 427639171891209425L, 2590582080178010045L, -6288067880951692635L, -3204510905067065501L, 9008426291442999873L, -4085962609397876083L, -3786041297813905157L, -6006475053574578261L, -6174022276199807178L, 7958957647277035097L, 2915785807118517755L, 2139592530283433011L, -8562048562533248017L, -4991735207930685025L, 393144860250454082L, -5852177196425420458L, -2652303154023739579L, 2079679586901234739L, -1386526064824772584L, 1574420554361329695L, -855542130447493508L, 8291940350733154044L, -5330200233059892402L, 5140782607921164290L, -977254437067235218L, -261520846651909307L, -7369143208070837455L, -4728766390712852111L, -8572213434879266955L, -6754813768712497692L, 7946121307356573089L, 504268959085012646L, -5536654029698676818L, -6021520522792328781L, 6968613512520500871L, 4029920623217569312L, 2738878342460920492L, 4562432005481165726L, -1279037845195368028L, 1746645308450474697L, 2538150989161378915L, 2012299649948738944L, -3997559675475377347L, -5939431505669672858L, 2077103722387383456L, -6188261335534632204L, 8772504603740967633L, -1653698997940568281L, 1676948989756529271L, 2377579815165102226L, -2667481192445387240L, -5498860615033631762L, -2490865541169744469L, -1233441883399707566L, 5445263795307566596L, 2288458809413275798L, -5908274826918996877L, 2909363406069168415L, 2376032171261335687L, -5215189045919902574L, -6083327007632847329L, 2462785604224107327L, -6684045035730714275L, 2409356208468676804L, 2814747114160772803L, -4529204412661254980L, -8437511853472556883L, 1819323657613892915L, 6862685309651627151L, -9210337863564319258L, -3641041551811494963L, -6791020794026796740L, -5261661996953805298L, -1953516254626596632L, -5901591005960707793L, -7413695905040596911L, 2952256922297384020L, -8427771021447591769L, -6920139339436245233L, 2967149838604559395L, -3253499104068010353L, -8473804925120692039L, -3561285603521886085L, -4453849179065102447L, 2050092642498054323L, -5626434133619314199L, 7995075368278704248L, 7685996432951370136L, -8037783900933102779L, 4601459625295412851L, -4491938778497306775L, -9089886217821142309L, -3947191644612298897L, 1364225714229764884L, 2580394324892542249L, -3765315378396862242L, 6023794482194323576L, -662753714084561214L, 3080495347149127717L, 911710215008202776L, -803705685664586056L, -6101059689379533503L, -2122356322512227634L, 8012110874513406695L, -4158551223425336367L, 8282080141813519654L, 4172879384244246799L, 708522065347490110L, -6997269001146828181L, 1887955086977822594L, 8014460039616323415L }; private static final long[] HASHES_OF_LOOPING_BYTES_WITH_SEED_42 = { -7444071767201028348L, -8959994473701255385L, 7116559933691734543L, 6019482000716350659L, -6625277557348586272L, -5507563483608914162L, 1540412690865189709L, 4522324563441226749L, -7143238906056518746L, -7989831429045113014L, -7103973673268129917L, -2319060423616348937L, -7576144055863289344L, -8903544572546912743L, 6376815151655939880L, 5913754614426879871L, 6466567997237536608L, -869838547529805462L, -2416009472486582019L, -3059673981515537339L, 4211239092494362041L, 1414635639471257331L, 166863084165354636L, -3761330575439628223L, 3524931906845391329L, 6070229753198168844L, -3740381894759773016L, -1268276809699008557L, 1518581707938531581L, 7988048690914090770L, -4510281763783422346L, -8988936099728967847L, -8644129751861931918L, 2046936095001747419L, 339737284852751748L, -8493525091666023417L, -3962890767051635164L, -5799948707353228709L, -6503577434416464161L, 7718729912902936653L, 191197390694726650L, -2677870679247057207L, 20411540801847004L, 2738354376741059902L, -3754251900675510347L, -3208495075154651980L, 5505877218642938179L, 6710910171520780908L, -9060809096139575515L, 6936438027860748388L, -6675099569841255629L, -5358120966884144380L, -4970515091611332076L, -1810965683604454696L, -516197887510505242L, 1240864593087756274L, 6033499571835033332L, 7223146028771530185L, 909128106589125206L, 1567720774747329341L, -1867353301780159863L, 4655107429511759333L, 5356891185236995950L, 182631115370802890L, -3582744155969569138L, 595148673029792797L, 495183136068540256L, 5536689004903505647L, -8472683670935785889L, -4335021702965928166L, 7306662983232020244L, 4285260837125010956L, 8288813008819191181L, -3442351913745287612L, 4883297703151707194L, 9135546183059994964L, 123663780425483012L, 509606241253238381L, 5940344208569311369L, -2650142344608291176L, 3232776678942440459L, -922581627593772181L, 7617977317085633049L, 7154902266379028518L, -5806388675416795571L, 4368003766009575737L, -2922716024457242064L, 4771160713173250118L, 3275897444752647349L, -297220751499763878L, 5095659287766176401L, 1181843887132908826L, 9058283605301070357L, 3984713963471276643L, 6050484112980480005L, 1551535065359244224L, 565337293533335618L, 7412521035272884309L, -4735469481351389369L, 6998597101178745656L, -9107075101236275961L, 5879828914430779796L, 6034964979406620806L, 5666406915264701514L, -4666218379625258428L, 2749972203764815656L, -782986256139071446L, 6830581400521008570L, 2588852022632995043L, -5484725487363818922L, -3319556935687817112L, 6481961252981840893L, 2204492445852963006L, -5301091763401031066L, -2615065677047206256L, -6769817545131782460L, -8421640685322953142L, -3669062629317949176L, -9167016978640750490L, 2783671191687959562L, -7599469568522039782L, -7589134103255480011L, -5932706841188717592L, -8689756354284562694L, -3934347391198581249L, -1344748563236040701L, 2172701592984478834L, -5322052340624064417L, -8493945390573620511L, 3349021988137788403L, -1806262525300459538L, -8091524448239736618L, 4022306289903960690L, -8346915997379834224L, -2106001381993805461L, -5784123934724688161L, 6775158099649720388L, -3869682756870293568L, 4356490186652082006L, 8469371446702290916L, -2972961082318458602L, -7188106622222784561L, -4961006366631572412L, 3199991182014172900L, 2917435868590434179L, 8385845305547872127L, 7706824402560674655L, -1587379863634865277L, -4212156212298809650L, -1305209322000720233L, -7866728337506665880L, 8195089740529247049L, -4876930125798534239L, 798222697981617129L, -2441020897729372845L, -3926158482651178666L, -1254795122048514130L, 5192463866522217407L, -5426289318796042964L, -3267454004443530826L, 471043133625225785L, -660956397365869974L, -6149209189144999161L, -2630977660039166559L, 8512219789663151219L, -3309844068134074620L, -6211275327487847132L, -2130171729366885995L, 6569302074205462321L, 4855778342281619706L, 3867211421508653033L, -3002480002418725542L, -8297543107467502696L, 8049642289208775831L, -5439825716055425635L, 7251760070798756432L, -4774526021749797528L, -3892389575184442548L, 5162451061244344424L, 6000530226398686578L, -5713092252241819676L, 8740913206879606081L, -8693282419677309723L, 1576205127972543824L, 5760354502610401246L, 3173225529903529385L, 1785166236732849743L, -1024443476832068882L, -7389053248306187459L, 1171021620017782166L, 1471572212217428724L, 7720766400407679932L, -8844781213239282804L, -7030159830170200877L, 2195066352895261150L, 1343620937208608634L, 9178233160016731645L, -757883447602665223L, 3303032934975960867L, -3685775162104101116L, -4454903657585596656L, -5721532367620482629L, 8453227136542829644L, 5397498317904798888L, 7820279586106842836L, -2369852356421022546L, 3910437403657116169L, 6072677490463894877L, -2651044781586183960L, 5173762670440434510L, -2970017317595590978L, -1024698859439768763L, -3098335260967738522L, -1983156467650050768L, -8132353894276010246L, -1088647368768943835L, -3942884234250555927L, 7169967005748210436L, 2870913702735953746L, -2207022373847083021L, 1104181306093040609L, 5026420573696578749L, -5874879996794598513L, -4777071762424874671L, -7506667858329720470L, -2926679936584725232L, -5530649174168373609L, 5282408526788020384L, 3589529249264153135L, -6220724706210580398L, -7141769650716479812L, 5142537361821482047L, -7029808662366864423L, -6593520217660744466L, 1454581737122410695L, -139542971769349865L, 1727752089112067235L, -775001449688420017L, -5011311035350652032L, -8671171179275033159L, -2850915129917664667L, -5258897903906998781L, -6954153088230718761L, -4070351752166223959L, -6902592976462171099L, -7850366369290661391L, -4562443925864904705L, 3186922928616271015L, 2208521081203400591L, -2727824999830592777L, -3817861137262331295L, 2236720618756809066L, -4888946967413746075L, -446884183491477687L, -43021963625359034L, -5857689226703189898L, -2156533592262354883L, -2027655907961967077L, 7151844076490292500L, -5029149124756905464L, 526404452686156976L, 8741076980297445408L, 7962851518384256467L, -105985852299572102L, -2614605270539434398L, -8265006689379110448L, 8158561071761524496L, -6923530157382047308L, 5551949335037580397L, 565709346370307061L, -4780869469938333359L, 6931895917517004830L, 565234767538051407L, -8663136372880869656L, 1427340323685448983L, 6492705666640232290L, 1481585578088475369L, -1712711110946325531L, 3281685342714380741L, 6441384790483098576L, -1073539554682358394L, 5704050067194788964L, -5495724689443043319L, -5425043165837577535L, 8349736730194941321L, -4123620508872850061L, 4687874980541143573L, -468891940172550975L, -3212254545038049829L, -6830802881920725628L, 9033050533972480988L, 4204031879107709260L, -677513987701096310L, -3286978557209370155L, 1644111582609113135L, 2040089403280131741L, 3323690950628902653L, -7686964480987925756L, -4664519769497402737L, 3358384147145476542L, -4699919744264452277L, -4795197464927839170L, 5051607253379734527L, -8987703459734976898L, 8993686795574431834L, -2688919474688811047L, 375938183536293311L, 1049459889197081920L, -1213022037395838295L, 4932989235110984138L, -6647247877090282452L, -7698817539128166242L, -3264029336002462659L, 6487828018122309795L, -2660821091484592878L, 7104391069028909121L, -1765840012354703384L, 85428166783788931L, -6732726318028261938L, 7566202549055682933L, 229664898114413280L, -1474237851782211353L, -1571058880058007603L, -7926453582850712144L, 2487148368914275243L, 8740031015380673473L, 1908345726881363169L, -2510061320536523178L, 7854780026906019630L, -6023415596650016493L, -6264841978089051107L, 4024998278016087488L, -4266288992025826072L, -3222176619422665563L, -1999258726038299316L, 1715270077442385636L, 6764658837948099754L, -8646962299105812577L, -51484064212171546L, -1482515279051057493L, -8663965522608868414L, -256555202123523670L, 1973279596140303801L, -7280796173024508575L, -5691760367231354704L, -5915786562256300861L, -3697715074906156565L, 3710290115318541949L, 6796151623958134374L, -935299482515386356L, -7078378973978660385L, 5379481350768846927L, -9011221735308556302L, 5936568631579608418L, -6060732654964511813L, -4243141607840017809L, 3198488845875349355L, -7809288876010447646L, 4371587872421472389L, -1304197371105522943L, 7389861473143460103L, -1892352887992004024L, 2214828764044713398L, 6347546952883613388L, 1275694314105480954L, -5262663163358903733L, 1524757505892047607L, 1474285098416162746L, -7976447341881911786L, 4014100291977623265L, 8994982266451461043L, -7737118961020539453L, -2303955536994331092L, 1383016539349937136L, 1771516393548245271L, -5441914919967503849L, 5449813464890411403L, -3321280356474552496L, 4084073849712624363L, 4290039323210935932L, 2449523715173349652L, 7494827882138362156L, 9035007221503623051L, 5722056230130603177L, -5443061851556843748L, -7554957764207092109L, 447883090204372074L, 533916651576859197L, -3104765246501904165L, -4002281505194601516L, -8402008431255610992L, -408273018037005304L, 214196458752109430L, 6458513309998070914L, 2665048360156607904L, 96698248584467992L, -3238403026096269033L, 6759639479763272920L, -4231971627796170796L, -2149574977639731179L, -1437035755788460036L, -6000005629185669767L, 145244292800946348L, -3056352941404947199L, 3748284277779018970L, 7328354565489106580L, -2176895260373660284L, 3077983936372755601L, 1215485830019410079L, 683050801367331140L, -3173237622987755212L, -1951990779107873701L, -4714366021269652421L, 4934690664256059008L, 1674823104333774474L, -3974408282362828040L, 2001478896492417760L, -4115105568354384199L, -2039694725495941666L, -587763432329933431L, -391276713546911316L, -5543400904809469053L, 1882564440421402418L, -4991793588968693036L, 3454088185914578321L, 2290855447126188424L, 3027910585026909453L, 2136873580213167431L, -6243562989966916730L, 5887939953208193029L, -3491821629467655741L, -3138303216306660662L, 8572629205737718669L, 4154439973110146459L, 5542921963475106759L, -2025215496720103521L, -4047933760493641640L, -169455456138383823L, -1164572689128024473L, -8551078127234162906L, -7247713218016599028L, 8725299775220778242L, 6263466461599623132L, 7931568057263751768L, 7365493014712655238L, -7343740914722477108L, 8294118602089088477L, 7677867223984211483L, -7052188421655969232L, -3739992520633991431L, 772835781531324307L, 881441588914692737L, 6321450879891466401L, 5682516032668315027L, 8493068269270840662L, -3895212467022280567L, -3241911302335746277L, -7199586338775635848L, -4606922569968527974L, -806850906331637768L, 2433670352784844513L, -5787982146811444512L, 7852193425348711165L, 8669396209073850051L, -6898875695148963118L, 6523939610287206782L, -8084962379210153174L, 8159432443823995836L, -2631068535470883494L, -338649779993793113L, 6514650029997052016L, 3926259678521802094L, 5443275905907218528L, 7312187582713433551L, -2993773587362997676L, -1068335949405953411L, 4499730398606216151L, 8538015793827433712L, -4057209365270423575L, -1504284818438273559L, -6460688570035010846L, 1765077117408991117L, 8278320303525164177L, 8510128922449361533L, 1305722765578569816L, 7250861238779078656L, -576624504295396147L, -4363714566147521011L, -5932111494795524073L, 1837387625936544674L, -4186755953373944712L, -7657073597826358867L, 140408487263951108L, 5578463635002659628L, 3400326044813475885L, -6092804808386714986L, -2410324417287268694L, 3222007930183458970L, 4932471983280850419L, 3554114546976144528L, -7216067928362857082L, -6115289896923351748L, -6769646077108881947L, 4263895947722578066L, 2939136721007694271L, 1426030606447416658L, -1316192446807442076L, 5366182640480055129L, 6527003877470258527L, 5849680119000207603L, 5263993237214222328L, -6936533648789185663L, -9063642143790846605L, 3795892210758087672L, 4987213125282940176L, 2505500970421590750L, -1014022559552365387L, -3574736245968367770L, 1180676507127340259L, -2261908445207512503L, -8416682633172243509L, 1114990703652673283L, 7753746660364401380L, 1874908722469707905L, 2033421444403047677L, 21412168602505589L, 385957952615286205L, 2053171460074727107L, 1915131899400103774L, 6680879515029368390L, 568807208929724162L, -6211541450459087674L, -5026690733412145448L, 1384781941404886235L, -98027820852587266L, 1806580495924249669L, 6322077317403503963L, 9078162931419569939L, -2809061215428363978L, 7697867577577415733L, -5270063855897737274L, 5649864555290587388L, -6970990547695444247L, 579684606137331754L, 3871931565451195154L, 2030008578322050218L, -5012357307111799829L, -2271365921756144065L, 4551962665158074190L, -3385474923040271312L, -7647625164191633577L, 6634635380316963029L, -5201190933687061585L, 8864818738548593973L, 2855828214210882907L, 9154512990734024165L, -6945306719789457786L, 1200243352799481087L, 875998327415853787L, 1275313054449881011L, -6105772045375948736L, -2926927684328291437L, 9200050852144954779L, 5188726645765880663L, 5197037323312705176L, 3434926231010121611L, -5054013669361906544L, 2582959199749224670L, -6053757512723474059L, -5016308176846054473L, -2509827316698626133L, 7700343644503853204L, -1997627249894596731L, 3993168688325352290L, -8181743677541277704L, 3719056119682565597L, -7264411659282947790L, 7177028972346484464L, -5460831176884283278L, 1799904662416293978L, -6549616005092764514L, 5472403994001122052L, 8683463751708388502L, -7873363037838316398L, 689134758256487260L, -1287443614028696450L, 4452712919702709507L, 762909374167538893L, 6594302592326281411L, 1183786629674781984L, 5021847859620133476L, -2490098069181538915L, 5105145136026716679L, 4437836948098585718L, 1987270426215858862L, 6170312798826946249L, 634297557126003407L, -1672811625495999581L, 6282971595586218191L, 4549149305727581687L, -5652165370435317782L, 1064501550023753890L, -5334885527127139723L, -6904378001629481237L, -1807576691784201230L, -205688432992053911L, 7621619053293393289L, 6258649161313982470L, -1111634238359342096L, -8044260779481691987L, 400270655839010807L, -7806833581382890725L, -2970563349459508036L, -7392591524816802798L, 2918924613160219805L, -6444161627929149002L, 6096497501321778876L, -1477975665655830038L, 1690651307597306138L, -2364076888826085362L, -6521987420014905821L, -4419193480146960582L, 3538587780233092477L, 8374665961716940404L, 7492412312405424500L, 6311662249091276767L, -1240235198282023566L, 5478559631401166447L, 3476714419313462133L, 377427285984503784L, 2570472638778991109L, -2741381313777447835L, -7123472905503039596L, 2493658686946955193L, 1024677789035847585L, -2916713904339582981L, -4532003852004642304L, -2202143560366234111L, 5832267856442755135L, -261740607772957384L, 239435959690278014L, 5755548341947719409L, 6138795458221887696L, -7709506987360146385L, -6657487758065140444L, -7006376793203657499L, 6544409861846502033L, 3171929352014159247L, 1051041925048792869L, 2617300158375649749L, 952652799620095175L, -576661730162168147L, -1634191369221345988L, 4833656816115993519L, 647566759700005786L, 2473810683785291822L, 3005977181064745326L, -3321881966853149523L, 7595337666427588699L, 6004093624251057224L, -563917505657690279L, 6117428527147449302L, -6287297509522976113L, -4527219334756214406L, 742626429298092489L, 3057351806086972041L, 645967551210272605L, -4428701157828864227L, 3236379103879435414L, -8477089892132066300L, -6127365537275859058L, -4052490484706946358L, -8004854976625046469L, -3679456917426613424L, -8212793762082595299L, -818288739465424130L, 1358812099481667095L, 7835987612195254310L, -3663247409614323059L, -2931105150130396604L, 7296136776835614792L, -2014557408985889628L, 7267662411237959788L, 3699280615819277743L, -212010675469091396L, -6518374332458360120L, 145026010541628849L, 1879297324213501001L, -7146296067751816833L, -5002958800391379931L, 6060682439924517608L, -432234782921170964L, -6669688947353256956L, 7728943532792041267L, 830911367341171721L, 3396934884314289432L, -779464156662780749L, 2330041851883352285L, -4783350380736276693L, -5758476056890049254L, -7551552301614791791L, 1253334187723911710L, -2685018208308798978L, 5379636036360946454L, 6154668487114681217L, -8641287462255458898L, 4676087643800649558L, -2405142641398691475L, 1088685126864246881L, 6431149082338374041L, -607357695335069155L, -720970692129524140L, 2648766932394044468L, 8408344790179354573L, -6193808387735667350L, 7722524628524697419L, -6975433852560238120L, -2925851029234475295L, -4274458387165211028L, -8355836377702147319L, 5278146397877332061L, 8502098812383680707L, 2292836642336580326L, -6127608082651070062L, 2222301962240611208L, -1930887695854799378L, 7640503480494894592L, 1162652186586436094L, -1918002592943761683L, 7648998601717261840L, -8472603250832757057L, -988877663117552456L, 2368458128168026494L, -6480813811998475245L, -5896967824416018967L, -2593783161701820446L, 6950098417530252598L, 6362589545555771236L, 7981389665448567125L, 3954017080198558850L, 1626078615050230622L, 6650159066527969109L, 697345338922935394L, -1226816215461768626L, 8740408765973837440L, -4194155864629568323L, 7016680023232424746L, 6043281358142429469L, -4201005667174376809L, 1216727117859013155L, 6367202436544203935L, 35414869396444636L, 3715622794033998412L, 488654435687670554L, -2503747297224687460L, 3147101919441470388L, -8248611218693190922L, 970697264481229955L, 3411465763826851418L, 9117405004661599969L, -5204346498331519734L, -19637460819385174L, -5039124225167977219L, 2990108874601696668L, -2623857460235459202L, 4256291692861397446L, 6724147860870760443L, 3558616688507246537L, 6487680097936412800L, -6470792832935928161L, 4314814550912237614L, -1292878983006062345L, 6791915152630414174L, 5971652079925815310L, 2557529546662864312L, 466175054322801580L, -585216717310746872L, -2486640422147349036L, 7212029603994220134L, 3958995069888972500L, 4950471855791412790L, -3721948842035712763L, -6184503487488243051L, 4079570444585775332L, -3952156172546996872L, 4543894231118208322L, -1739995588466209963L, 9155948355455935530L, 5821980345462207860L, -2431287667309520417L, -3890108130519441316L, -558124689277030490L, 6079823537335801717L, 5409742395192364262L, -2329885777717160453L, -7332804342513677651L, 1466490574975950555L, -420549419907427929L, -5249909814389692516L, -5145692168206210661L, 5934113980649113921L, 3241618428555359661L, -6622110266160980250L, 5048250878669516223L, 5747219637359976174L, 2975906212588223728L, 5730216838646273215L, -176713127129024690L, 6734624279336671146L, 5127866734316017180L, 7111761230887705595L, 3457811808274317235L, 3362961434604932375L, -1877869936854991246L, 7171428594877765665L, -8252167178400462374L, -6306888185035821047L, -6684702191247683887L, -7754928454824190529L, -1902605599135704386L, -4037319846689421239L, 8493746058123583457L, -8156648963857047193L, 2051510355149839497L, -1256416624177218909L, -3344927996254072010L, -1838853051925943568L, 316927471680974556L, -1502257066700798003L, -5836095610125837606L, -1594125583615895424L, 1442211486559637962L, -144295071206619569L, 5159850900959273410L, 4589139881166423678L, -7038726987463097509L, 2886082400772974595L, 2780759114707171916L, 5694649587906297495L, 1260349041268169667L, 4921517488271434890L, 644696475796073018L, 6262811963753436289L, -6128198676595868773L, -3625352083004760261L, -8751453332943236675L, 8749249479868749221L, -2450808199545048250L, -6517435817046180917L, -3433321727429234998L, -2591586258908763451L, 3847750870868804507L, 6603614438546398643L, -7598682191291031287L, 8710261565627204971L, 4753389483755344355L, -4645333069458786881L, -6742695046613492214L, 643070478568866643L, -7543096104151965610L, 7171495384655926161L, 595063872610714431L, 3292310150781130424L, 4326847806055440904L, -4580020566072794152L, 3142286571820373678L, 5530356537440155930L, 546372639737516181L, 7401214477400367500L, 7406531960402873109L, 3287639667219172570L, 4977301681213633671L, 5253257820925174498L, 2906216636104297878L, 6142955758238347523L, -3498651268741727235L, -5875053958265588593L, 3896719087169993883L, -910904726885775073L, 380107493197368177L, -4993591912695447004L, 2970487257212582761L, 2551762717569548774L, 953061649962736812L, 8949739538606589463L, -2962839167079475801L, -1375673191272573835L, 3761793818361866390L, -389577789190726878L, 5661262051502180269L, -6558556411143987683L, -702798336372315031L, -336662820551371779L, 998576401126580155L, -5945021269112582755L, 6108533925730179871L, 2207095297001999618L, -9042779159998880435L, -6177868444342118372L, 6775965402605895077L, -3788428885163306576L, 7790055010527190387L, 3581587652196995358L, -6176354155561607694L, -5859381340906321207L, 395898765763528395L, 8132967590863909348L, -3329092504090544483L, -6785855381158040247L, 1497218517051796750L, -5352392845588925911L, -6271364901230559194L, 2314830370653350118L, -7617588269001325450L, 1423166885758213795L, 8538612578307869519L, -61918791718295474L, -8177103503192338593L, -4740086042584326695L, 3677931948215558698L, 6558856291580149558L, 2674975452453336335L, 5133796555646930522L, 5139252693299337100L, 7949476871295347205L, 4407815324662880678L, -3758305875280581215L, 6066309507576587415L, -7368508486398350973L, -3181640264332856492L, 6905100869343314145L, 3677177673848733417L, 8862933624870506941L, -8575223195813810568L, 9178470351355678144L, 4677809017145408358L, -1194833416287894989L, 3436364743255571183L, -5204770725795363579L, 560599448536335263L, -3192077522964776200L, -751575299648803575L, 6334581746534596579L, -8358187891202563300L, -1462480609823525055L, 5605961062646987941L, 4968399805931440889L, 7968693270782626653L, -5868205923557518188L, 1830234928743560617L, -8435261076693154407L, 2138416970728681332L, 8088740745199685138L, 806532400344230520L, 1800590379902909333L, -8909128842071238901L, -7357495566969170860L, 3679766664126940553L, 2060050474865839094L, 2363972840121763414L, 525695004292982714L, -1224842191746529593L, 7011317848855545003L, -6337167558180299938L, -5184688833363785939L, -8426673387248359061L, -5035438815930785229L, 3521810320608058994L, 4803742557254962242L, 6623527039545786598L, -1221475882122634738L, -3344794405518401087L, 6510298498414053658L, 2844753907937720338L, 90502309714994895L, -750403235344282494L, -4825474181021465833L, -3405519947983849510L, 3503875590944089793L, 7286294700691822468L, 7828126881500292486L, 8437899353709338096L, 136052254470293480L, 1113259077339995086L, -8244887265606191121L, 8089569503800461649L, -1429698194850157567L, 1575595674002364989L, 3576095286627428675L, -7653655285807569222L, -6053506977362539111L, -3923855345805787169L, -8001149080454232377L, -4382867706931832271L, 4212860258835896297L, 4207674254247034014L, 5519424058779519159L, -754483042161434654L, 1434113479814210082L, -6416645032698336896L, 5624329676066514819L, -8229557208322175959L, 3922640911653270376L, 7826932478782081910L, -4862787164488635842L, 1449234668827944573L, -1781657689570106327L, 5442827552725289699L, 3589862161007644641L, 4787115581650652778L, -3512152721942525726L, -6750103117958685206L, 5012970446659949261L, 6797752795961689017L, 5086454597639943700L, -7616068364979994076L, 1492846825433110217L, 2967476304433704510L, -8413824338284112078L, -1319049442043273974L, -1756090916806844109L, -9061091728950139525L, -6864767830358160810L, 4879532090226251157L, 5528644708740739488L }; }
CollisionTest
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/server/authentication/RegisterSessionServerAuthenticationSuccessHandler.java
{ "start": 1314, "end": 2080 }
class ____ implements ServerAuthenticationSuccessHandler { private final ReactiveSessionRegistry sessionRegistry; public RegisterSessionServerAuthenticationSuccessHandler(ReactiveSessionRegistry sessionRegistry) { Assert.notNull(sessionRegistry, "sessionRegistry cannot be null"); this.sessionRegistry = sessionRegistry; } @Override public Mono<Void> onAuthenticationSuccess(WebFilterExchange exchange, Authentication authentication) { return exchange.getExchange() .getSession() .map((session) -> new ReactiveSessionInformation(Objects.requireNonNull(authentication.getPrincipal()), session.getId(), session.getLastAccessTime())) .flatMap(this.sessionRegistry::saveSessionInformation); } }
RegisterSessionServerAuthenticationSuccessHandler
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.java
{ "start": 944, "end": 1325 }
class ____ extends BaseRule { private VirtualServiceSpec spec; public VirtualServiceSpec getSpec() { return spec; } public void setSpec(VirtualServiceSpec spec) { this.spec = spec; } @Override public String toString() { return "VirtualServiceRule{" + "base=" + super.toString() + ", spec=" + spec + '}'; } }
VirtualServiceRule
java
apache__camel
components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlProducerToDTest.java
{ "start": 1409, "end": 2956 }
class ____ extends CamelTestSupport { @BindToRegistry("myDS") EmbeddedDatabase db; @Override public void doPreSetup() throws Exception { db = new EmbeddedDatabaseBuilder() .setName(getClass().getSimpleName()) .setType(EmbeddedDatabaseType.H2) .addScript("sql/createAndPopulateDatabase.sql").build(); } @Override public void doPostTearDown() throws Exception { if (db != null) { db.shutdown(); } } @Test public void testToD() throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:query"); mock.expectedMessageCount(1); template.requestBodyAndHeader("direct:query", "Hi there!", "foo", "AMQ"); MockEndpoint.assertIsSatisfied(context); List list = mock.getReceivedExchanges().get(0).getIn().getBody(List.class); assertEquals(1, list.size()); Map row = (Map) list.get(0); assertEquals("AMQ", row.get("PROJECT")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:query") .setHeader("myQuery", constant("select * from projects where project = :#foo order by id")) .toD("sql:${header.myQuery}?dataSource=#myDS") .to("log:query") .to("mock:query"); } }; } }
SqlProducerToDTest
java
square__retrofit
retrofit-converters/jackson/src/main/java/retrofit2/converter/jackson/JacksonResponseBodyConverter.java
{ "start": 783, "end": 1171 }
class ____<T> implements Converter<ResponseBody, T> { private final ObjectReader adapter; JacksonResponseBodyConverter(ObjectReader adapter) { this.adapter = adapter; } @Override public T convert(ResponseBody value) throws IOException { try { return adapter.readValue(value.byteStream()); } finally { value.close(); } } }
JacksonResponseBodyConverter
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/StaticRetryPolicy.java
{ "start": 986, "end": 1820 }
class ____ extends AbfsRetryPolicy { /** * Represents the constant retry interval to be used with Static Retry Policy */ private final int retryInterval; /** * Initializes a new instance of the {@link StaticRetryPolicy} class. * @param conf The {@link AbfsConfiguration} from which to retrieve retry configuration. */ public StaticRetryPolicy(AbfsConfiguration conf) { super(conf.getMaxIoRetries(), RetryPolicyConstants.STATIC_RETRY_POLICY_ABBREVIATION); this.retryInterval = conf.getStaticRetryInterval(); } /** * Returns a constant backoff interval independent of retry count; * * @param retryCount The current retry attempt count. * @return backoff Interval time */ @Override public long getRetryInterval(final int retryCount) { return retryInterval; } }
StaticRetryPolicy
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/repositories/InvalidRepositoryIT.java
{ "start": 3127, "end": 7697 }
class ____ extends org.elasticsearch.plugins.Plugin implements RepositoryPlugin { @Override public Map<String, Factory> getRepositories( Environment env, NamedXContentRegistry namedXContentRegistry, ClusterService clusterService, BigArrays bigArrays, RecoverySettings recoverySettings, RepositoriesMetrics repositoriesMetrics, SnapshotMetrics snapshotMetrics ) { return Collections.singletonMap( TYPE, (projectId, metadata) -> new UnstableRepository( projectId, metadata, env, namedXContentRegistry, clusterService, bigArrays, recoverySettings, snapshotMetrics ) ); } @Override public List<Setting<?>> getSettings() { return List.of(UNSTABLE_NODES); } } } public void testCreateInvalidRepository() throws Exception { internalCluster().ensureAtLeastNumDataNodes(2); final String repositoryName = "test-duplicate-create-repo"; // put repository for the first time: only let master node create repository successfully createRepository( repositoryName, UnstableRepository.TYPE, Settings.builder() .put("location", randomRepoPath()) .putList( UnstableRepository.UNSTABLE_NODES.getKey(), Arrays.stream(internalCluster().getNodeNames()) .filter(name -> name.equals(internalCluster().getMasterName()) == false) .toList() ) ); // verification should fail with some node has InvalidRepository final var expectedException = expectThrows( RepositoryVerificationException.class, clusterAdmin().prepareVerifyRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repositoryName) ); for (Throwable suppressed : expectedException.getSuppressed()) { Throwable outerCause = suppressed.getCause(); assertThat(outerCause, isA(RepositoryException.class)); assertThat( outerCause.getMessage(), equalTo("[" + repositoryName + "] repository type [" + UnstableRepository.TYPE + "] failed to create on current node") ); Throwable innerCause = suppressed.getCause().getCause().getCause(); assertThat(innerCause, isA(RepositoryException.class)); assertThat( innerCause.getMessage(), equalTo("[" + repositoryName + "] Failed to create repository: current node is not stable") ); } // restart master internalCluster().restartNode(internalCluster().getMasterName()); ensureGreen(); // put repository again: let all node can create repository successfully createRepository(repositoryName, UnstableRepository.TYPE, Settings.builder().put("location", randomRepoPath())); // verification should succeed with all node create repository successfully VerifyRepositoryResponse verifyRepositoryResponse = clusterAdmin().prepareVerifyRepository( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, repositoryName ).get(); assertEquals(verifyRepositoryResponse.getNodes().size(), internalCluster().numDataAndMasterNodes()); } private void createRepository(String name, String type, Settings.Builder settings) { // create assertAcked( clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, name) .setType(type) .setVerify(false) .setSettings(settings) .get() ); // get final GetRepositoriesResponse updatedGetRepositoriesResponse = clusterAdmin().prepareGetRepositories(TEST_REQUEST_TIMEOUT, name) .get(); // assert assertThat(updatedGetRepositoriesResponse.repositories(), hasSize(1)); final RepositoryMetadata updatedRepositoryMetadata = updatedGetRepositoriesResponse.repositories().get(0); assertThat(updatedRepositoryMetadata.type(), equalTo(type)); } }
Plugin
java
greenrobot__EventBus
EventBusPerformance/src/org/greenrobot/eventbusperf/testsubject/SubscribeClassEventBusDefault.java
{ "start": 794, "end": 1314 }
class ____ { private PerfTestEventBus perfTestEventBus; public SubscribeClassEventBusDefault(PerfTestEventBus perfTestEventBus) { this.perfTestEventBus = perfTestEventBus; } @Subscribe public void onEvent(TestEvent event) { perfTestEventBus.eventsReceivedCount.incrementAndGet(); } public void dummy() { } public void dummy2() { } public void dummy3() { } public void dummy4() { } public void dummy5() { } }
SubscribeClassEventBusDefault
java
quarkusio__quarkus
extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/filter/DisabledRestEndpointsFilter.java
{ "start": 717, "end": 2807 }
class ____ implements OASFilter { public static Optional<OASFilter> maybeGetInstance() { var endpoints = DisabledRestEndpoints.get(); if (endpoints != null && !endpoints.isEmpty()) { return Optional.of(new DisabledRestEndpointsFilter(endpoints)); } return Optional.empty(); } final Map<String, List<String>> disabledEndpoints; private DisabledRestEndpointsFilter(Map<String, List<String>> disabledEndpoints) { this.disabledEndpoints = disabledEndpoints; } @Override public void filterOpenAPI(OpenAPI openAPI) { Paths paths = openAPI.getPaths(); disabledEndpoints.entrySet() .stream() .map(pathMethods -> Map.entry(stripSlash(pathMethods.getKey()), pathMethods.getValue())) // Skip paths that are not present in the OpenAPI model .filter(pathMethods -> paths.hasPathItem(pathMethods.getKey())) .forEach(pathMethods -> { String path = pathMethods.getKey(); PathItem pathItem = paths.getPathItem(path); // Remove each operation identified as a disabled HTTP method Optional.ofNullable(pathMethods.getValue()) .orElseGet(Collections::emptyList) .stream() .map(PathItem.HttpMethod::valueOf) .forEach(method -> pathItem.setOperation(method, null)); if (pathItem.getOperations().isEmpty()) { paths.removePathItem(path); } }); } /** * Removes any trailing slash character from the path when it is not the root '/' * path. This is necessary to align with the paths generated in the OpenAPI model. */ static String stripSlash(String path) { if (path.endsWith("/") && path.length() > 1) { return path.substring(0, path.length() - 1); } return path; } }
DisabledRestEndpointsFilter
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExtensionContext.java
{ "start": 1800, "end": 4675 }
interface ____ { /** * Get the parent extension context, if available. * * @return an {@code Optional} containing the parent; never {@code null} but * potentially empty * @see #getRoot() */ Optional<ExtensionContext> getParent(); /** * Get the <em>root</em> {@code ExtensionContext}. * * @return the root extension context; never {@code null} but potentially * <em>this</em> {@code ExtensionContext} * @see #getParent() */ ExtensionContext getRoot(); /** * Get the unique ID of the current test or container. * * @return the unique ID of the test or container; never {@code null} or blank */ String getUniqueId(); /** * Get the display name for the current test or container. * * <p>The display name is either a default name or a custom name configured * via {@link org.junit.jupiter.api.DisplayName @DisplayName}. * * <p>For details on default display names consult the Javadoc for * {@link org.junit.jupiter.api.TestInfo#getDisplayName()}. * * <p>Note that display names are typically used for test reporting in IDEs * and build tools and may contain spaces, special characters, and even emoji. * * @return the display name of the test or container; never {@code null} or blank */ String getDisplayName(); /** * Get the set of all tags for the current test or container. * * <p>Tags may be declared directly on the test element or <em>inherited</em> * from an outer context. * * @return the set of tags for the test or container; never {@code null} but * potentially empty */ Set<String> getTags(); /** * Get the {@link AnnotatedElement} corresponding to the current extension * context, if available. * * <p>For example, if the current extension context encapsulates a test * class, test method, test factory method, or test template method, the * annotated element will be the corresponding {@link Class} or {@link Method} * reference. * * <p>Favor this method over more specific methods whenever the * {@code AnnotatedElement} API suits the task at hand &mdash; for example, * when looking up annotations regardless of concrete element type. * * @return an {@code Optional} containing the {@code AnnotatedElement}; * never {@code null} but potentially empty * @see #getTestClass() * @see #getTestMethod() */ Optional<AnnotatedElement> getElement(); /** * Get the {@link Class} associated with the current test or container, * if available. * * @return an {@code Optional} containing the class; never {@code null} but * potentially empty * @see #getRequiredTestClass() */ Optional<Class<?>> getTestClass(); /** * Get the <em>required</em> {@link Class} associated with the current test * or container. * * <p>Use this method as an alternative to {@link #getTestClass()} for use * cases in which the test
ExtensionContext
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java
{ "start": 3614, "end": 3802 }
class ____ extends ConfigurationBuilderFactory { public ConfigurationFactory() { // TEMP For breakpoints } /** * Allows the ConfigurationFactory
ConfigurationFactory
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StreamToIterableTest.java
{ "start": 2860, "end": 3348 }
class ____ { void test(List<Integer> i) { addAll(Stream.of(1, 2, 3).collect(toImmutableList())); } void addAll(Iterable<Integer> ints) {} } """) .doTest(); } @Test public void lambdaRefactoredToExplicitCollection() { refactoring .addInputLines( "Test.java", """ import java.util.List; import java.util.stream.Stream;
Test