language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__kafka | streams/upgrade-system-tests-37/src/test/java/org/apache/kafka/streams/tests/SmokeTestUtil.java | {
"start": 1483,
"end": 4000
} | class ____ {
static final int END = Integer.MAX_VALUE;
static ProcessorSupplier<Object, Object, Void, Void> printProcessorSupplier(final String topic) {
return printProcessorSupplier(topic, "");
}
static ProcessorSupplier<Object, Object, Void, Void> printProcessorSupplier(final String topic, final String name) {
return () -> new ContextualProcessor<Object, Object, Void, Void>() {
private int numRecordsProcessed = 0;
private long smallestOffset = Long.MAX_VALUE;
private long largestOffset = Long.MIN_VALUE;
@Override
public void init(final ProcessorContext<Void, Void> context) {
super.init(context);
System.out.println("[3.7] initializing processor: topic=" + topic + " taskId=" + context.taskId());
System.out.flush();
numRecordsProcessed = 0;
smallestOffset = Long.MAX_VALUE;
largestOffset = Long.MIN_VALUE;
}
@Override
public void process(final Record<Object, Object> record) {
numRecordsProcessed++;
if (numRecordsProcessed % 100 == 0) {
System.out.printf("%s: %s%n", name, Instant.now());
System.out.println("processed " + numRecordsProcessed + " records from topic=" + topic);
}
context().recordMetadata().ifPresent(recordMetadata -> {
if (smallestOffset > recordMetadata.offset()) {
smallestOffset = recordMetadata.offset();
}
if (largestOffset < recordMetadata.offset()) {
largestOffset = recordMetadata.offset();
}
});
}
@Override
public void close() {
System.out.printf("Close processor for task %s%n", context().taskId());
System.out.println("processed " + numRecordsProcessed + " records");
final long processed;
if (largestOffset >= smallestOffset) {
processed = 1L + largestOffset - smallestOffset;
} else {
processed = 0L;
}
System.out.println("offset " + smallestOffset + " to " + largestOffset + " -> processed " + processed);
System.out.flush();
}
};
}
public static final | SmokeTestUtil |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java | {
"start": 715,
"end": 2113
} | class ____ the hierarchy of the test
*/
public InjectMocksScanner(Class<?> clazz) {
this.clazz = clazz;
}
/**
* Add the fields annotated by @{@link InjectMocks}
*
* @param mockDependentFields Set of fields annotated by @{@link InjectMocks}
*/
public void addTo(Set<Field> mockDependentFields) {
mockDependentFields.addAll(scan());
}
/**
* Scan fields annotated by @InjectMocks
*
* @return Fields that depends on Mock
*/
@SuppressWarnings("unchecked")
private Set<Field> scan() {
Set<Field> mockDependentFields = new HashSet<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (null != field.getAnnotation(InjectMocks.class)) {
assertNoAnnotations(field, Mock.class, Captor.class);
mockDependentFields.add(field);
}
}
return mockDependentFields;
}
private static void assertNoAnnotations(
Field field, Class<? extends Annotation>... annotations) {
for (Class<? extends Annotation> annotation : annotations) {
if (field.isAnnotationPresent(annotation)) {
throw unsupportedCombinationOfAnnotations(
annotation.getSimpleName(), InjectMocks.class.getSimpleName());
}
}
}
}
| in |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/ClientImpl.java | {
"start": 3805,
"end": 13963
} | class ____ implements Client {
private static final Logger log = Logger.getLogger(ClientImpl.class);
private static final int DEFAULT_CONNECT_TIMEOUT = 15000;
private static final int DEFAULT_CONNECTION_POOL_SIZE = 50;
final ClientContext clientContext;
final boolean closeVertx;
final HttpClient httpClient;
final ConfigurationImpl configuration;
final HostnameVerifier hostnameVerifier;
final SSLContext sslContext;
private boolean isClosed;
final HandlerChain handlerChain;
final Vertx vertx;
private final MultiQueryParamMode multiQueryParamMode;
private final String userAgent;
private final String tlsConfigName;
public ClientImpl(HttpClientOptions options, ConfigurationImpl configuration, ClientContext clientContext,
HostnameVerifier hostnameVerifier,
SSLContext sslContext, boolean followRedirects,
MultiQueryParamMode multiQueryParamMode,
LoggingScope loggingScope,
ClientLogger clientLogger, String userAgent,
String tlsConfigName) {
this.userAgent = userAgent;
this.tlsConfigName = tlsConfigName;
configuration = configuration != null ? configuration : new ConfigurationImpl(RuntimeType.CLIENT);
this.configuration = configuration;
this.clientContext = clientContext;
this.hostnameVerifier = hostnameVerifier;
this.sslContext = sslContext;
this.multiQueryParamMode = multiQueryParamMode;
Supplier<Vertx> vertx = clientContext.getVertx();
if (vertx != null) {
this.vertx = vertx.get();
closeVertx = false;
} else {
this.vertx = new LazyVertx(new Supplier<Vertx>() {
@Override
public Vertx get() {
return Vertx.vertx();
}
});
closeVertx = true;
}
Object connectTimeoutMs = configuration.getProperty(CONNECT_TIMEOUT);
if (connectTimeoutMs == null) {
options.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
} else {
options.setConnectTimeout((int) connectTimeoutMs);
}
Object maxRedirects = configuration.getProperty(MAX_REDIRECTS);
if (maxRedirects != null) {
options.setMaxRedirects((Integer) maxRedirects);
}
Object maxHeaderSize = configuration.getProperty(MAX_HEADER_SIZE);
if (maxHeaderSize != null) {
options.setMaxHeaderSize((Integer) maxHeaderSize);
}
Object maxInitialLineLength = configuration.getProperty(MAX_INITIAL_LINE_LENGTH);
if (maxInitialLineLength != null) {
options.setMaxInitialLineLength((Integer) maxInitialLineLength);
}
Object connectionTTL = configuration.getProperty(CONNECTION_TTL);
if (connectionTTL != null) {
options.setKeepAliveTimeout((int) connectionTTL);
options.setHttp2KeepAliveTimeout((int) connectionTTL);
}
Object connectionPoolSize = configuration.getProperty(CONNECTION_POOL_SIZE);
if (connectionPoolSize == null) {
connectionPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
} else {
log.debugf("Setting connectionPoolSize to %d", connectionPoolSize);
}
options.setMaxPoolSize((int) connectionPoolSize);
options.setHttp2MaxPoolSize((int) connectionPoolSize);
Object keepAliveEnabled = configuration.getProperty(KEEP_ALIVE_ENABLED);
if (keepAliveEnabled != null) {
Boolean enabled = (Boolean) keepAliveEnabled;
options.setKeepAlive(enabled);
if (!enabled) {
log.debug("keep alive disabled");
}
}
if (loggingScope == LoggingScope.ALL) {
options.setLogActivity(true);
}
Object name = configuration.getProperty(NAME);
if (name != null) {
log.debugf("Setting client name to %s", name);
options.setName((String) name);
}
Object shared = configuration.getProperty(SHARED);
if (shared != null && (boolean) shared) {
log.debugf("Sharing of the HTTP client '%s' enabled", options.getName());
options.setShared(true);
}
var httpClientBuilder = this.vertx.httpClientBuilder().with(options).with(options.getPoolOptions());
AdvancedRedirectHandler advancedRedirectHandler = configuration.getFromContext(AdvancedRedirectHandler.class);
if (advancedRedirectHandler != null) {
httpClientBuilder.withRedirectHandler(new WrapperVertxAdvancedRedirectHandlerImpl(advancedRedirectHandler));
} else {
RedirectHandler redirectHandler = configuration.getFromContext(RedirectHandler.class);
if (redirectHandler != null) {
httpClientBuilder.withRedirectHandler(new WrapperVertxRedirectHandlerImpl(redirectHandler));
}
}
httpClient = httpClientBuilder.build();
if (loggingScope != LoggingScope.NONE) {
Function<HttpClientResponse, Future<RequestOptions>> defaultRedirectHandler = httpClient.redirectHandler();
httpClient.redirectHandler(response -> {
clientLogger.logResponse(response, true);
return defaultRedirectHandler.apply(response);
});
}
handlerChain = new HandlerChain(isCaptureStacktrace(configuration), options.getMaxChunkSize(),
options.getMaxChunkSize(),
followRedirects,
loggingScope,
clientContext.getMultipartResponsesData(), clientLogger);
}
public HttpClient getVertxHttpClient() {
return httpClient;
}
private boolean isCaptureStacktrace(ConfigurationImpl configuration) {
Object captureStacktraceObj = configuration.getProperty(CAPTURE_STACKTRACE);
if (captureStacktraceObj == null) {
return false;
}
return (boolean) captureStacktraceObj;
}
public ClientContext getClientContext() {
return clientContext;
}
@Override
public void close() {
if (isClosed)
return;
isClosed = true;
httpClient.close();
if (closeVertx) {
vertx.close();
}
log.debug("Client is closed");
}
void abortIfClosed() {
if (isClosed)
throw new IllegalStateException("Client is closed");
}
public String getUserAgent() {
return userAgent;
}
public String getTlsConfigName() {
return tlsConfigName;
}
@Override
public WebTarget target(String uri) {
// close is checked in the other target call
Objects.requireNonNull(uri);
return target(UriBuilder.fromUri(uri));
}
@Override
public WebTarget target(URI uri) {
// close is checked in the other target call
Objects.requireNonNull(uri);
return target(UriBuilder.fromUri(uri));
}
@Override
public WebTarget target(UriBuilder uriBuilder) {
abortIfClosed();
Objects.requireNonNull(uriBuilder);
if (uriBuilder instanceof UriBuilderImpl && multiQueryParamMode != null) {
((UriBuilderImpl) uriBuilder).multiQueryParamMode(multiQueryParamMode);
}
return new WebTargetImpl(this, httpClient, uriBuilder, new ConfigurationImpl(configuration), handlerChain, null);
}
@Override
public WebTarget target(Link link) {
// close is checked in the other target call
Objects.requireNonNull(link);
return target(UriBuilder.fromLink(link));
}
@Override
public Invocation.Builder invocation(Link link) {
abortIfClosed();
Objects.requireNonNull(link);
Builder request = target(link).request();
if (link.getType() != null)
request.accept(link.getType());
return request;
}
@Override
public SSLContext getSslContext() {
abortIfClosed();
return sslContext;
}
@Override
public HostnameVerifier getHostnameVerifier() {
abortIfClosed();
return hostnameVerifier;
}
@Override
public ConfigurationImpl getConfiguration() {
abortIfClosed();
return configuration;
}
@Override
public Client property(String name, Object value) {
abortIfClosed();
configuration.property(name, value);
return this;
}
@Override
public Client register(Class<?> componentClass) {
abortIfClosed();
configuration.register(componentClass);
return this;
}
@Override
public Client register(Class<?> componentClass, int priority) {
abortIfClosed();
configuration.register(componentClass, priority);
return this;
}
@Override
public Client register(Class<?> componentClass, Class<?>... contracts) {
abortIfClosed();
configuration.register(componentClass, contracts);
return this;
}
@Override
public Client register(Class<?> componentClass, Map<Class<?>, Integer> contracts) {
abortIfClosed();
configuration.register(componentClass, contracts);
return this;
}
@Override
public Client register(Object component) {
abortIfClosed();
configuration.register(component);
return this;
}
@Override
public Client register(Object component, int priority) {
abortIfClosed();
configuration.register(component, priority);
return this;
}
@Override
public Client register(Object component, Class<?>... contracts) {
abortIfClosed();
configuration.register(component, contracts);
return this;
}
@Override
public Client register(Object component, Map<Class<?>, Integer> contracts) {
abortIfClosed();
configuration.register(component, contracts);
return this;
}
Vertx getVertx() {
return vertx;
}
/**
* The point of this | ClientImpl |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/parent_reference_3level/Blog.java | {
"start": 743,
"end": 1382
} | class ____ {
private int id;
private String title;
private List<Post> posts;
public Blog() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
if (this.title != null) {
throw new RuntimeException("Setter called twice");
}
this.title = title;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
if (this.posts != null) {
throw new RuntimeException("Setter called twice");
}
this.posts = posts;
}
}
| Blog |
java | apache__camel | core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java | {
"start": 37362,
"end": 37836
} | class ____ the known list of builders.
*/
public MainConfigurationProperties withAdditionalRoutesBuilder(Class... builders) {
addRoutesBuilder(builders);
return this;
}
/**
* Add an additional {@link LambdaRouteBuilder} object to the known list of builders.
*/
public MainConfigurationProperties withAdditionalLambdaRouteBuilder(LambdaRouteBuilder builder) {
addLambdaRouteBuilder(builder);
return this;
}
}
| to |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-quartz/src/main/java/smoketest/quartz/SampleJob.java | {
"start": 844,
"end": 1209
} | class ____ extends QuartzJobBean {
private @Nullable String name;
// Invoked if a Job data map entry with that name
public void setName(@Nullable String name) {
this.name = name;
}
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println(String.format("Hello %s!", this.name));
}
}
| SampleJob |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/xprocessing/Accessibility.java | {
"start": 2765,
"end": 2848
} | class ____ never result in generating code that will not compile.
*/
public final | will |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/internal/ModelPartResultMementoBasicImpl.java | {
"start": 526,
"end": 1285
} | class ____ implements ModelPartResultMementoBasic {
private final NavigablePath navigablePath;
private final BasicValuedModelPart modelPart;
private final String columnName;
public ModelPartResultMementoBasicImpl(
NavigablePath navigablePath,
BasicValuedModelPart modelPart,
String columnName) {
this.navigablePath = navigablePath;
this.modelPart = modelPart;
this.columnName = columnName;
}
@Override
public NavigablePath getNavigablePath() {
return navigablePath;
}
@Override
public ResultBuilderBasicValued resolve(
Consumer<String> querySpaceConsumer,
ResultSetMappingResolutionContext context) {
return new CompleteResultBuilderBasicModelPart( navigablePath, modelPart, columnName );
}
}
| ModelPartResultMementoBasicImpl |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/cat/RestAllocationAction.java | {
"start": 1980,
"end": 8348
} | class ____ extends AbstractCatAction {
private static final String UNASSIGNED = "UNASSIGNED";
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_cat/allocation"), new Route(GET, "/_cat/allocation/{nodes}"));
}
@Override
public String getName() {
return "cat_allocation_action";
}
@Override
protected void documentation(StringBuilder sb) {
sb.append("/_cat/allocation\n");
}
@Override
public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
final String[] nodes = Strings.splitStringByCommaToArray(request.param("nodes", "data:true"));
final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(getMasterNodeTimeout(request));
clusterStateRequest.clear().routingTable(true);
RestUtils.consumeDeprecatedLocalParameter(request);
return channel -> client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void processResponse(final ClusterStateResponse state) {
NodesStatsRequest statsRequest = new NodesStatsRequest(nodes);
statsRequest.setIncludeShardsStats(false);
statsRequest.clear()
.addMetric(NodesStatsRequestParameters.Metric.FS)
.addMetric(NodesStatsRequestParameters.Metric.ALLOCATIONS)
.indices(new CommonStatsFlags(CommonStatsFlags.Flag.Store));
client.admin().cluster().nodesStats(statsRequest, new RestResponseListener<>(channel) {
@Override
public RestResponse buildResponse(NodesStatsResponse stats) throws Exception {
Table tab = buildTable(request, state, stats);
return RestTable.buildResponse(tab, channel);
}
});
}
});
}
@Override
protected Table getTableWithHeader(final RestRequest request) {
final Table table = new Table();
table.startHeaders();
table.addCell("shards", "alias:s;text-align:right;desc:number of shards on node");
table.addCell("shards.undesired", "text-align:right;desc:number of shards that are scheduled to be moved elsewhere in the cluster");
table.addCell("write_load.forecast", "alias:wlf,writeLoadForecast;text-align:right;desc:sum of index write load forecasts");
table.addCell("disk.indices.forecast", "alias:dif,diskIndicesForecast;text-align:right;desc:sum of shard size forecasts");
table.addCell("disk.indices", "alias:di,diskIndices;text-align:right;desc:disk used by ES indices");
table.addCell("disk.used", "alias:du,diskUsed;text-align:right;desc:disk used (total, not just ES)");
table.addCell("disk.avail", "alias:da,diskAvail;text-align:right;desc:disk available");
table.addCell("disk.total", "alias:dt,diskTotal;text-align:right;desc:total capacity of all volumes");
table.addCell("disk.percent", "alias:dp,diskPercent;text-align:right;desc:percent disk used");
table.addCell("host", "alias:h;desc:host of node");
table.addCell("ip", "desc:ip of node");
table.addCell("node", "alias:n;desc:name of node");
table.addCell("node.role", "alias:r,role,nodeRole;desc:node roles");
table.endHeaders();
return table;
}
private Table buildTable(RestRequest request, final ClusterStateResponse state, final NodesStatsResponse stats) {
final Map<String, Integer> shardCounts = new HashMap<>();
for (ShardRouting shard : state.getState().routingTable().allShardsIterator()) {
String nodeId = shard.assignedToNode() ? shard.currentNodeId() : UNASSIGNED;
shardCounts.merge(nodeId, 1, Integer::sum);
}
Table table = getTableWithHeader(request);
for (NodeStats nodeStats : stats.getNodes()) {
DiscoveryNode node = nodeStats.getNode();
ByteSizeValue total = nodeStats.getFs().getTotal().getTotal();
ByteSizeValue avail = nodeStats.getFs().getTotal().getAvailable();
// if we don't know how much we use (non data nodes), it means 0
long used = 0;
short diskPercent = -1;
if (total.getBytes() > 0) {
used = total.getBytes() - avail.getBytes();
if (used >= 0 && avail.getBytes() >= 0) {
diskPercent = (short) (used * 100 / (used + avail.getBytes()));
}
}
NodeAllocationStats nodeAllocationStats = nodeStats.getNodeAllocationStats();
table.startRow();
table.addCell(shardCounts.getOrDefault(node.getId(), 0));
table.addCell(nodeAllocationStats != null ? nodeAllocationStats.undesiredShards() : null);
table.addCell(nodeAllocationStats != null ? nodeAllocationStats.forecastedIngestLoad() : null);
table.addCell(nodeAllocationStats != null ? ByteSizeValue.ofBytes(nodeAllocationStats.forecastedDiskUsage()) : null);
table.addCell(nodeStats.getIndices().getStore().size());
table.addCell(used < 0 ? null : ByteSizeValue.ofBytes(used));
table.addCell(avail.getBytes() < 0 ? null : avail);
table.addCell(total.getBytes() < 0 ? null : total);
table.addCell(diskPercent < 0 ? null : diskPercent);
table.addCell(node.getHostName());
table.addCell(node.getHostAddress());
table.addCell(node.getName());
table.addCell(node.getRoleAbbreviationString());
table.endRow();
}
if (shardCounts.containsKey(UNASSIGNED)) {
table.startRow();
table.addCell(shardCounts.get(UNASSIGNED));
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(UNASSIGNED);
table.addCell(null);
table.endRow();
}
return table;
}
}
| RestAllocationAction |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManySelfReferenceTest.java | {
"start": 1209,
"end": 5751
} | class ____ {
@BeforeEach
public void setUp(SessionFactoryScope scope) {
Event parent = new Event();
scope.inTransaction(
session -> {
parent.setName( "parent" );
parent.setId( 1L );
Event child = new Event();
child.setId( 2L );
child.setName( "child" );
parent.addChid( child );
session.persist( parent );
session.persist( child );
}
);
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testSelectParentFetchChildren(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
TypedQuery<Event> eventTypedQuery = session.createQuery(
"SELECT e FROM Event e left join fetch e.children WHERE e.id = :oid",
Event.class
);
eventTypedQuery.setParameter( "oid", 1L );
Event event = eventTypedQuery.getSingleResult();
Set<Event> children = event.getChildren();
assertTrue(
Hibernate.isInitialized( children ),
"Children collection has not been initialized"
);
assertThat( children.size(), is( 1 ) );
assertThat( children, instanceOf( PersistentSet.class ) );
PersistentSet persistentSet = (PersistentSet) children;
assertThat( persistentSet.getKey(), is(1L) );
Event child = children.iterator().next();
Set<Event> childChildren = child.getChildren();
assertFalse(
Hibernate.isInitialized( childChildren ),
"Child children collection should not be initialized"
);
assertThat( childChildren, instanceOf( PersistentSet.class ) );
PersistentSet childChildrenPersistentSet = (PersistentSet) childChildren;
assertThat( childChildrenPersistentSet.getKey(), is(2L) );
assertThat( childChildren.size(), is(0) );
assertTrue(
Hibernate.isInitialized( childChildren ),
"Child children collection should not be initialized"
);
}
);
}
@Test
public void testSelectParent(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
TypedQuery<Event> eventTypedQuery = session.createQuery(
"SELECT e FROM Event e WHERE e.id = :oid",
Event.class
);
eventTypedQuery.setParameter( "oid", 1L );
Event event = eventTypedQuery.getSingleResult();
Set<Event> children = event.getChildren();
assertFalse(
Hibernate.isInitialized( children ),
"Children collection should not be initialized"
);
assertThat( children.size(), is( 1 ) );
assertTrue(
Hibernate.isInitialized( children ),
"Children collection has not been initialized"
);
Event child = children.iterator().next();
Set<Event> childChildren = child.getChildren();
assertFalse(
Hibernate.isInitialized( childChildren ),
"Child children collection should not be initialized"
);
assertThat( childChildren, instanceOf( PersistentSet.class ) );
PersistentSet childChildrenPersistentSet = (PersistentSet) childChildren;
assertThat( childChildrenPersistentSet.getKey(), is(2L) );
assertThat( childChildren.size(), is(0) );
}
);
}
@Test
public void testSelectChild(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
TypedQuery<Event> eventTypedQuery = session.createQuery(
"SELECT e FROM Event e left join fetch e.children WHERE e.id = :oid",
Event.class
);
eventTypedQuery.setParameter( "oid", 2L );
Event event = eventTypedQuery.getSingleResult();
Set<Event> children = event.getChildren();
assertTrue(
Hibernate.isInitialized( children ),
"Children collection has not been initialized"
);
assertThat( children.size(), is( 0 ) );
assertThat( children, instanceOf( PersistentSet.class ) );
PersistentSet childrenPersistentSet = (PersistentSet) children;
assertThat( childrenPersistentSet.getKey(), is(2L) );
Event parent = event.getParent();
assertThat( parent.getId(), is(1L) );
Set<Event> parentChildren = parent.getChildren();
assertFalse(
Hibernate.isInitialized( parentChildren ),
"Child children collection should not be initialized"
);
PersistentSet parentChildrenPersistentSet = (PersistentSet) parentChildren;
assertThat( parentChildrenPersistentSet.getKey(), is(1L) );
Event next = parentChildren.iterator().next();
assertThat( next, sameInstance(event) );
}
);
}
@Entity(name = "Event")
public static | OneToManySelfReferenceTest |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferInputStream.java | {
"start": 986,
"end": 3488
} | class ____ extends InputStream {
private final DataBuffer dataBuffer;
private final int end;
private final boolean releaseOnClose;
private boolean closed;
private int mark;
public DataBufferInputStream(DataBuffer dataBuffer, boolean releaseOnClose) {
Assert.notNull(dataBuffer, "DataBuffer must not be null");
this.dataBuffer = dataBuffer;
int start = this.dataBuffer.readPosition();
this.end = start + this.dataBuffer.readableByteCount();
this.mark = start;
this.releaseOnClose = releaseOnClose;
}
@Override
public int read() throws IOException {
checkClosed();
if (available() == 0) {
return -1;
}
return this.dataBuffer.read() & 0xFF;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
checkClosed();
int available = available();
if (available == 0) {
return -1;
}
len = Math.min(available, len);
this.dataBuffer.read(b, off, len);
return len;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readLimit) {
Assert.isTrue(readLimit > 0, "readLimit must be greater than 0");
this.mark = this.dataBuffer.readPosition();
}
@Override
public int available() {
return Math.max(0, this.end - this.dataBuffer.readPosition());
}
@Override
public void reset() {
this.dataBuffer.readPosition(this.mark);
}
@Override
public void close() {
if (this.closed) {
return;
}
if (this.releaseOnClose) {
DataBufferUtils.release(this.dataBuffer);
}
this.closed = true;
}
@Override
public byte[] readNBytes(int len) throws IOException {
if (len < 0) {
throw new IllegalArgumentException("len < 0");
}
checkClosed();
int size = Math.min(available(), len);
byte[] out = new byte[size];
this.dataBuffer.read(out);
return out;
}
@Override
public long skip(long n) throws IOException {
checkClosed();
if (n <= 0) {
return 0L;
}
int skipped = Math.min(available(), n > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n);
this.dataBuffer.readPosition(this.dataBuffer.readPosition() + skipped);
return skipped;
}
@Override
public long transferTo(OutputStream out) throws IOException {
Objects.requireNonNull(out, "out");
checkClosed();
if (available() == 0) {
return 0L;
}
byte[] buf = readAllBytes();
out.write(buf);
return buf.length;
}
private void checkClosed() throws IOException {
if (this.closed) {
throw new IOException("DataBufferInputStream is closed");
}
}
}
| DataBufferInputStream |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java | {
"start": 150147,
"end": 150458
} | class ____ {
public int foo(Suit suit) {
switch (suit) {
default:
throw new NullPointerException();
}
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | spring-projects__spring-framework | spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/LifecycleBean.java | {
"start": 4541,
"end": 5052
} | class ____ implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessBeforeInit();
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessAfterInit();
}
return bean;
}
}
}
| PostProcessor |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elasticsearch/RerankTaskSettings.java | {
"start": 984,
"end": 4876
} | class ____ implements TaskSettings {
public static final String NAME = "custom_eland_rerank_task_settings";
public static final String RETURN_DOCUMENTS = "return_documents";
static final RerankTaskSettings DEFAULT_SETTINGS = new RerankTaskSettings(Boolean.TRUE);
public static RerankTaskSettings defaultsFromMap(Map<String, Object> map) {
ValidationException validationException = new ValidationException();
if (map == null || map.isEmpty()) {
return DEFAULT_SETTINGS;
}
Boolean returnDocuments = extractOptionalBoolean(map, RETURN_DOCUMENTS, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
if (returnDocuments == null) {
returnDocuments = true;
}
return new RerankTaskSettings(returnDocuments);
}
/**
* From map without any validation
* @param map source map
* @return Task settings
*/
public static RerankTaskSettings fromMap(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return DEFAULT_SETTINGS;
}
Boolean returnDocuments = extractOptionalBoolean(map, RETURN_DOCUMENTS, new ValidationException());
return new RerankTaskSettings(returnDocuments);
}
/**
* Return either the request or original settings by preferring non-null fields
* from the request settings over the original settings.
*
* @param originalSettings the settings stored as part of the inference entity configuration
* @param requestTaskSettings the settings passed in within the task_settings field of the request
* @return Either {@code originalSettings} or {@code requestTaskSettings}
*/
public static RerankTaskSettings of(RerankTaskSettings originalSettings, RerankTaskSettings requestTaskSettings) {
return requestTaskSettings.returnDocuments() != null ? requestTaskSettings : originalSettings;
}
private final Boolean returnDocuments;
public RerankTaskSettings(StreamInput in) throws IOException {
this(in.readOptionalBoolean());
}
public RerankTaskSettings(@Nullable Boolean doReturnDocuments) {
if (doReturnDocuments == null) {
this.returnDocuments = true;
} else {
this.returnDocuments = doReturnDocuments;
}
}
@Override
public boolean isEmpty() {
return returnDocuments == null;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (returnDocuments != null) {
builder.field(RETURN_DOCUMENTS, returnDocuments);
}
builder.endObject();
return builder;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_14_0;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalBoolean(returnDocuments);
}
public Boolean returnDocuments() {
return returnDocuments;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RerankTaskSettings that = (RerankTaskSettings) o;
return Objects.equals(returnDocuments, that.returnDocuments);
}
@Override
public int hashCode() {
return Objects.hash(returnDocuments);
}
@Override
public TaskSettings updatedTaskSettings(Map<String, Object> newSettings) {
RerankTaskSettings updatedSettings = RerankTaskSettings.fromMap(new HashMap<>(newSettings));
return of(this, updatedSettings);
}
}
| RerankTaskSettings |
java | elastic__elasticsearch | modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateRequestXContentTests.java | {
"start": 1429,
"end": 8044
} | class ____ extends AbstractXContentTestCase<SearchTemplateRequest> {
@Override
public SearchTemplateRequest createTestInstance() {
return SearchTemplateRequestTests.createRandomRequest();
}
@Override
protected SearchTemplateRequest doParseInstance(XContentParser parser) throws IOException {
return SearchTemplateRequest.fromXContent(parser);
}
/**
* Note that when checking equality for xContent parsing, we omit two parts of the request:
* - The 'simulate' option, since this parameter is not included in the
* request's xContent (it's instead used to determine the request endpoint).
* - The random SearchRequest, since this component only affects the request
* parameters and also isn't captured in the request's xContent.
*/
@Override
protected void assertEqualInstances(SearchTemplateRequest expectedInstance, SearchTemplateRequest newInstance) {
assertTrue(
expectedInstance.isExplain() == newInstance.isExplain()
&& expectedInstance.isProfile() == newInstance.isProfile()
&& expectedInstance.getScriptType() == newInstance.getScriptType()
&& Objects.equals(expectedInstance.getScript(), newInstance.getScript())
&& Objects.equals(expectedInstance.getScriptParams(), newInstance.getScriptParams())
);
}
@Override
protected boolean supportsUnknownFields() {
return false;
}
public void testToXContentWithInlineTemplate() throws IOException {
SearchTemplateRequest request = new SearchTemplateRequest();
request.setScriptType(ScriptType.INLINE);
request.setScript("""
{"query": { "match" : { "{{my_field}}" : "{{my_value}}" } } }""");
request.setProfile(true);
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("my_field", "foo");
scriptParams.put("my_value", "bar");
request.setScriptParams(scriptParams);
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder expectedRequest = XContentFactory.contentBuilder(contentType)
.startObject()
.field("source", """
{"query": { "match" : { "{{my_field}}" : "{{my_value}}" } } }""")
.startObject("params")
.field("my_field", "foo")
.field("my_value", "bar")
.endObject()
.field("explain", false)
.field("profile", true)
.endObject();
XContentBuilder actualRequest = XContentFactory.contentBuilder(contentType);
request.toXContent(actualRequest, ToXContent.EMPTY_PARAMS);
assertToXContentEquivalent(BytesReference.bytes(expectedRequest), BytesReference.bytes(actualRequest), contentType);
}
public void testToXContentWithStoredTemplate() throws IOException {
SearchTemplateRequest request = new SearchTemplateRequest();
request.setScriptType(ScriptType.STORED);
request.setScript("match_template");
request.setExplain(true);
Map<String, Object> params = new HashMap<>();
params.put("my_field", "foo");
params.put("my_value", "bar");
request.setScriptParams(params);
XContentType contentType = randomFrom(XContentType.values());
XContentBuilder expectedRequest = XContentFactory.contentBuilder(contentType)
.startObject()
.field("id", "match_template")
.startObject("params")
.field("my_field", "foo")
.field("my_value", "bar")
.endObject()
.field("explain", true)
.field("profile", false)
.endObject();
XContentBuilder actualRequest = XContentFactory.contentBuilder(contentType);
request.toXContent(actualRequest, ToXContent.EMPTY_PARAMS);
assertToXContentEquivalent(BytesReference.bytes(expectedRequest), BytesReference.bytes(actualRequest), contentType);
}
public void testFromXContentWithEmbeddedTemplate() throws Exception {
String source = """
{
'source' : {
'query': {
'terms': {
'status': [
'{{#status}}',
'{{.}}',
'{{/status}}'
]
}
}
}}""";
SearchTemplateRequest request = SearchTemplateRequest.fromXContent(newParser(source));
assertThat(request.getScript(), equalTo("""
{"query":{"terms":{"status":["{{#status}}","{{.}}","{{/status}}"]}}}"""));
assertThat(request.getScriptType(), equalTo(ScriptType.INLINE));
assertThat(request.getScriptParams(), nullValue());
}
public void testFromXContentWithEmbeddedTemplateAndParams() throws Exception {
String source = """
{
'source' : {
'query': { 'match' : { '{{my_field}}' : '{{my_value}}' } },
'size' : '{{my_size}}'
},
'params' : {
'my_field' : 'foo',
'my_value' : 'bar',
'my_size' : 5
}
}""";
SearchTemplateRequest request = SearchTemplateRequest.fromXContent(newParser(source));
assertThat(request.getScript(), equalTo(XContentHelper.stripWhitespace("""
{
"query": {
"match": {
"{{my_field}}": "{{my_value}}"
}
},
"size": "{{my_size}}"
}""")));
assertThat(request.getScriptType(), equalTo(ScriptType.INLINE));
assertThat(request.getScriptParams().size(), equalTo(3));
assertThat(request.getScriptParams(), hasEntry("my_field", "foo"));
assertThat(request.getScriptParams(), hasEntry("my_value", "bar"));
assertThat(request.getScriptParams(), hasEntry("my_size", 5));
}
public void testFromXContentWithMalformedRequest() {
// Unclosed template id
expectThrows(XContentParseException.class, () -> SearchTemplateRequest.fromXContent(newParser("{'id' : 'another_temp }")));
}
/**
* Creates a {@link XContentParser} with the given String while replacing single quote to double quotes.
*/
private XContentParser newParser(String s) throws IOException {
assertNotNull(s);
return createParser(JsonXContent.jsonXContent, s.replace("'", "\""));
}
}
| SearchTemplateRequestXContentTests |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/sort/BinaryMergeIterator.java | {
"start": 1368,
"end": 2861
} | class ____<Entry> implements MutableObjectIterator<Entry> {
// heap over the head elements of the stream
private final PartialOrderPriorityQueue<HeadStream<Entry>> heap;
private HeadStream<Entry> currHead;
public BinaryMergeIterator(
List<MutableObjectIterator<Entry>> iterators,
List<Entry> reusableEntries,
Comparator<Entry> comparator)
throws IOException {
checkArgument(iterators.size() == reusableEntries.size());
this.heap =
new PartialOrderPriorityQueue<>(
(o1, o2) -> comparator.compare(o1.getHead(), o2.getHead()),
iterators.size());
for (int i = 0; i < iterators.size(); i++) {
this.heap.add(new HeadStream<>(iterators.get(i), reusableEntries.get(i)));
}
}
@Override
public Entry next(Entry reuse) throws IOException {
// Ignore reuse, because each HeadStream has its own reuse BinaryRowData.
return next();
}
@Override
public Entry next() throws IOException {
if (currHead != null) {
if (!currHead.nextHead()) {
this.heap.poll();
} else {
this.heap.adjustTop();
}
}
if (this.heap.size() > 0) {
currHead = this.heap.peek();
return currHead.getHead();
} else {
return null;
}
}
private static final | BinaryMergeIterator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cache/CachedReadOnlyArrayTest.java | {
"start": 619,
"end": 1000
} | class ____ {
@Test
void testReadFromCache(EntityManagerFactoryScope scope) {
scope.inTransaction(em -> {
Publication entity1 = new Publication();
entity1.id = "123l";
em.persist(entity1);
});
scope.inTransaction(em -> em.find(Publication.class, "123l"/*, ReadOnlyMode.READ_ONLY*/));
}
@Immutable
@Entity
@Cache(usage = READ_ONLY)
static | CachedReadOnlyArrayTest |
java | apache__avro | lang/java/protobuf/src/test/java/org/apache/avro/protobuf/multiplefiles/M.java | {
"start": 1698,
"end": 2288
} | enum ____ implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>A = 1;</code>
*/
A(1),;
static {
com.google.protobuf.RuntimeVersion.validateProtobufGencodeVersion(
com.google.protobuf.RuntimeVersion.RuntimeDomain.PUBLIC, /* major= */ 4, /* minor= */ 26, /* patch= */ 1,
/* suffix= */ "", N.class.getName());
}
/**
* <code>A = 1;</code>
*/
public static final int A_VALUE = 1;
public final int getNumber() {
return value;
}
/**
* @param value The numeric wire value of the corresponding | N |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/contract/s3a/ITestS3AContractRename.java | {
"start": 1830,
"end": 4873
} | class ____ extends AbstractContractRenameTest {
public static final Logger LOG = LoggerFactory.getLogger(
ITestS3AContractRename.class);
@Override
protected int getTestTimeoutMillis() {
return S3A_TEST_TIMEOUT;
}
@Override
protected AbstractFSContract createContract(Configuration conf) {
return new S3AContract(conf);
}
@Test
@Override
public void testRenameDirIntoExistingDir() throws Throwable {
describe("S3A rename into an existing directory returns false");
FileSystem fs = getFileSystem();
String sourceSubdir = "source";
Path srcDir = path(sourceSubdir);
Path srcFilePath = new Path(srcDir, "source-256.txt");
byte[] srcDataset = dataset(256, 'a', 'z');
writeDataset(fs, srcFilePath, srcDataset, srcDataset.length, 1024, false);
Path destDir = path("dest");
Path destFilePath = new Path(destDir, "dest-512.txt");
byte[] destDataset = dataset(512, 'A', 'Z');
writeDataset(fs, destFilePath, destDataset, destDataset.length, 1024,
false);
assertIsFile(destFilePath);
boolean rename = fs.rename(srcDir, destDir);
assertFalse(rename, "s3a doesn't support rename to non-empty directory");
}
/**
* Test that after renaming, the nested file is moved along with all its
* ancestors. It is similar to {@link #testRenamePopulatesDirectoryAncestors}.
*
* This is an extension testRenamePopulatesFileAncestors
* of the superclass version which does better
* logging of the state of the store before the assertions.
*/
@Test
public void testRenamePopulatesFileAncestors2() throws Exception {
final S3AFileSystem fs = (S3AFileSystem) getFileSystem();
Path base = path("testRenamePopulatesFileAncestors2");
final Path src = new Path(base, "src");
Path dest = new Path(base, "dest");
fs.mkdirs(src);
final String nestedFile = "/dir1/dir2/dir3/fileA";
// size of file to create
int filesize = 16 * 1024;
byte[] srcDataset = dataset(filesize, 'a', 'z');
Path srcFile = path(src + nestedFile);
Path destFile = path(dest + nestedFile);
writeDataset(fs, srcFile, srcDataset, srcDataset.length,
1024, false);
S3ATestUtils.MetricDiff fileCopyDiff = new S3ATestUtils.MetricDiff(fs,
Statistic.FILES_COPIED);
S3ATestUtils.MetricDiff fileCopyBytes = new S3ATestUtils.MetricDiff(fs,
Statistic.FILES_COPIED_BYTES);
rename(src, dest);
describe("Rename has completed, examining data under " + base);
fileCopyDiff.assertDiffEquals("Number of files copied", 1);
fileCopyBytes.assertDiffEquals("Number of bytes copied", filesize);
// log everything in the base directory.
S3ATestUtils.lsR(fs, base, true);
// look at the data.
verifyFileContents(fs, destFile, srcDataset);
describe("validating results");
validateAncestorsMoved(src, dest, nestedFile);
}
@Override
public void testRenameFileUnderFileSubdir() throws Exception {
skip("Rename deep paths under files is allowed");
}
}
| ITestS3AContractRename |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/MessageKeyWatcherImpl.java | {
"start": 404,
"end": 3202
} | class ____ implements MessageKeyWatcher, LogListener {
private final String messageKey;
private final boolean resetBeforeEach;
private final List<String> loggerNames = new ArrayList<>();
private final List<String> triggeredMessages = new ArrayList<>();
public MessageKeyWatcherImpl(String messageKey, boolean resetBeforeEach) {
this.messageKey = messageKey;
this.resetBeforeEach = resetBeforeEach;
}
public MessageKeyWatcherImpl(MessageKeyInspection inspectionAnn) {
this( inspectionAnn.messageKey(), inspectionAnn.resetBeforeEach() );
}
public void addLoggerName(String name) {
loggerNames.add( name );
}
public void addLogger(org.hibernate.testing.orm.junit.Logger loggerAnn) {
final Logger logger;
if ( loggerAnn.loggerNameClass() != void.class ) {
logger = Logger.getLogger( loggerAnn.loggerNameClass() );
}
else if ( !loggerAnn.loggerName().trim().isEmpty() ) {
logger = Logger.getLogger( loggerAnn.loggerName().trim() );
}
else {
throw new IllegalStateException(
"@LoggingInspections for prefix '" + messageKey +
"' did not specify proper Logger name. Use `@LoggingInspections#loggerName" +
" or `@LoggingInspections#loggerNameClass`"
);
}
LogInspectionHelper.registerListener( this, logger );
}
public static String loggerKey(org.hibernate.testing.orm.junit.Logger loggerAnn) {
final Logger logger;
if ( loggerAnn.loggerNameClass() != void.class ) {
logger = Logger.getLogger( loggerAnn.loggerNameClass() );
}
else if ( !loggerAnn.loggerName().trim().isEmpty() ) {
logger = Logger.getLogger( loggerAnn.loggerName().trim() );
}
else {
throw new IllegalArgumentException(
"`@Logger` must specify either `#loggerNameClass` or `#loggerName`"
);
}
return logger.getName();
}
public List<String> getLoggerNames() {
return loggerNames;
}
@Override
public String getMessageKey() {
return messageKey;
}
public boolean isResetBeforeEach() {
return resetBeforeEach;
}
@Override
public boolean wasTriggered() {
return ! triggeredMessages.isEmpty();
}
@Override
public List<String> getTriggeredMessages() {
return triggeredMessages;
}
@Override
public String getFirstTriggeredMessage() {
return triggeredMessages.isEmpty() ? null : triggeredMessages.get( 0 );
}
@Override
public void reset() {
triggeredMessages.clear();
}
@Override
public void loggedEvent(Logger.Level level, String renderedMessage, Throwable thrown) {
if ( renderedMessage != null ) {
if ( renderedMessage.startsWith( messageKey ) ) {
triggeredMessages.add( renderedMessage );
}
}
}
@Override
public String toString() {
return "MessageIdWatcherImpl{" +
"messageKey='" + messageKey + '\'' +
", loggerNames=" + loggerNames +
'}';
}
}
| MessageKeyWatcherImpl |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/pl/Oracle_pl_exception_2.java | {
"start": 922,
"end": 4550
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = "DECLARE\n" +
" stock_price NUMBER := 9.73;\n" +
" net_earnings NUMBER := 0;\n" +
" pe_ratio NUMBER;\n" +
"BEGIN\n" +
" pe_ratio := stock_price / net_earnings; -- raises ZERO_DIVIDE exception\n" +
" DBMS_OUTPUT.PUT_LINE('Price/earnings ratio = ' || pe_ratio);\n" +
"EXCEPTION\n" +
" WHEN ZERO_DIVIDE THEN\n" +
" DBMS_OUTPUT.PUT_LINE('Company had zero earnings.');\n" +
" pe_ratio := NULL;\n" +
"END;";
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE);
for (SQLStatement statement : statementList) {
statement.accept(visitor);
}
// 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(0, visitor.getTables().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees")));
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("emp_name")));
// assertEquals(7, visitor.getColumns().size());
// assertEquals(3, visitor.getConditions().size());
// assertEquals(1, visitor.getRelationships().size());
// assertTrue(visitor.getColumns().contains(new TableStat.Column("employees", "salary")));
{
String output = SQLUtils.toSQLString(statementList, JdbcConstants.ORACLE);
System.out.println(output);
assertEquals(
"DECLARE\n"
+ "\tstock_price NUMBER := 9.73;\n"
+ "\tnet_earnings NUMBER := 0;\n"
+ "\tpe_ratio NUMBER;\n"
+ "BEGIN\n"
+ "\tpe_ratio := stock_price / net_earnings;\n"
+ "\t-- raises ZERO_DIVIDE exception\n"
+ "\tDBMS_OUTPUT.PUT_LINE('Price/earnings ratio = ' || pe_ratio);\n"
+ "EXCEPTION\n"
+ "\tWHEN ZERO_DIVIDE THEN\n"
+ "\t\tDBMS_OUTPUT.PUT_LINE('Company had zero earnings.');\n"
+ "\t\tpe_ratio := NULL;\n"
+ "END;", //
output);
}
{
String output = SQLUtils.toSQLString(statementList, JdbcConstants.ORACLE, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals(
"declare\n"
+ "\tstock_price NUMBER := 9.73;\n"
+ "\tnet_earnings NUMBER := 0;\n"
+ "\tpe_ratio NUMBER;\n"
+ "begin\n"
+ "\tpe_ratio := stock_price / net_earnings;\n"
+ "\t-- raises ZERO_DIVIDE exception\n"
+ "\tDBMS_OUTPUT.PUT_LINE('Price/earnings ratio = ' || pe_ratio);\n"
+ "exception\n"
+ "\twhen ZERO_DIVIDE then\n"
+ "\t\tDBMS_OUTPUT.PUT_LINE('Company had zero earnings.');\n"
+ "\t\tpe_ratio := null;\n"
+ "end;", //
output);
}
}
}
| Oracle_pl_exception_2 |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/search/RankFeaturePhase.java | {
"start": 2224,
"end": 13507
} | class ____ extends SearchPhase {
static final String NAME = "rank-feature";
private static final Logger logger = LogManager.getLogger(RankFeaturePhase.class);
private final AbstractSearchAsyncAction<?> context;
final SearchPhaseResults<SearchPhaseResult> queryPhaseResults;
final SearchPhaseResults<SearchPhaseResult> rankPhaseResults;
private final AggregatedDfs aggregatedDfs;
private final SearchProgressListener progressListener;
private final RankFeaturePhaseRankCoordinatorContext rankFeaturePhaseRankCoordinatorContext;
RankFeaturePhase(
SearchPhaseResults<SearchPhaseResult> queryPhaseResults,
AggregatedDfs aggregatedDfs,
AbstractSearchAsyncAction<?> context,
RankFeaturePhaseRankCoordinatorContext rankFeaturePhaseRankCoordinatorContext
) {
super(NAME);
assert rankFeaturePhaseRankCoordinatorContext != null;
this.rankFeaturePhaseRankCoordinatorContext = rankFeaturePhaseRankCoordinatorContext;
if (context.getNumShards() != queryPhaseResults.getNumShards()) {
throw new IllegalStateException(
"number of shards must match the length of the query results but doesn't:"
+ context.getNumShards()
+ "!="
+ queryPhaseResults.getNumShards()
);
}
this.context = context;
this.queryPhaseResults = queryPhaseResults;
this.aggregatedDfs = aggregatedDfs;
this.rankPhaseResults = new ArraySearchPhaseResults<>(context.getNumShards());
context.addReleasable(rankPhaseResults);
this.progressListener = context.getTask().getProgressListener();
}
@Override
protected void run() {
context.execute(new AbstractRunnable() {
@Override
protected void doRun() throws Exception {
// we need to reduce the results at this point instead of fetch phase, so we fork this process similarly to how
// was set up at FetchSearchPhase.
// we do the heavy lifting in this inner run method where we reduce aggs etc
innerRun(rankFeaturePhaseRankCoordinatorContext);
}
@Override
public void onFailure(Exception e) {
context.onPhaseFailure(NAME, "", e);
}
});
}
void innerRun(RankFeaturePhaseRankCoordinatorContext rankFeaturePhaseRankCoordinatorContext) throws Exception {
// if the RankBuilder specifies a QueryPhaseCoordinatorContext, it will be called as part of the reduce call
// to operate on the first `rank_window_size * num_shards` results and merge them appropriately.
SearchPhaseController.ReducedQueryPhase reducedQueryPhase = queryPhaseResults.reduce();
ScoreDoc[] queryScoreDocs = reducedQueryPhase.sortedTopDocs().scoreDocs(); // rank_window_size
final List<Integer>[] docIdsToLoad = SearchPhaseController.fillDocIdsToLoad(context.getNumShards(), queryScoreDocs);
final CountedCollector<SearchPhaseResult> rankRequestCounter = new CountedCollector<>(
rankPhaseResults,
context.getNumShards(),
() -> onPhaseDone(rankFeaturePhaseRankCoordinatorContext, reducedQueryPhase),
context
);
// we send out a request to each shard in order to fetch the needed feature info
for (int i = 0; i < docIdsToLoad.length; i++) {
List<Integer> entry = docIdsToLoad[i];
SearchPhaseResult queryResult = queryPhaseResults.getAtomicArray().get(i);
if (entry == null || entry.isEmpty()) {
if (queryResult != null) {
releaseIrrelevantSearchContext(queryResult, context);
progressListener.notifyRankFeatureResult(i);
}
rankRequestCounter.countDown();
} else {
executeRankFeatureShardPhase(queryResult, rankRequestCounter, entry);
}
}
}
static RankFeaturePhaseRankCoordinatorContext coordinatorContext(SearchSourceBuilder source, Client client) {
return source == null || source.rankBuilder() == null
? null
: source.rankBuilder().buildRankFeaturePhaseCoordinatorContext(source.size(), source.from(), client);
}
private void executeRankFeatureShardPhase(
SearchPhaseResult queryResult,
final CountedCollector<SearchPhaseResult> rankRequestCounter,
final List<Integer> entry
) {
final SearchShardTarget shardTarget = queryResult.queryResult().getSearchShardTarget();
final ShardSearchContextId contextId = queryResult.queryResult().getContextId();
final int shardIndex = queryResult.getShardIndex();
var listener = new SearchActionListener<RankFeatureResult>(shardTarget, shardIndex) {
@Override
protected void innerOnResponse(RankFeatureResult response) {
try {
progressListener.notifyRankFeatureResult(shardIndex);
rankRequestCounter.onResult(response);
} catch (Exception e) {
context.onPhaseFailure(NAME, "", e);
}
}
@Override
public void onFailure(Exception e) {
try {
logger.debug(() -> "[" + contextId + "] Failed to execute rank phase", e);
progressListener.notifyRankFeatureFailure(shardIndex, shardTarget, e);
rankRequestCounter.onFailure(shardIndex, shardTarget, e);
} finally {
releaseIrrelevantSearchContext(queryResult, context);
}
}
};
final Transport.Connection connection;
try {
connection = context.getConnection(shardTarget.getClusterAlias(), shardTarget.getNodeId());
} catch (Exception e) {
listener.onFailure(e);
return;
}
context.getSearchTransport()
.sendExecuteRankFeature(
connection,
new RankFeatureShardRequest(
context.getOriginalIndices(queryResult.getShardIndex()),
queryResult.getContextId(),
queryResult.getShardSearchRequest(),
entry
),
context.getTask(),
listener
);
}
private void onPhaseDone(
RankFeaturePhaseRankCoordinatorContext rankFeaturePhaseRankCoordinatorContext,
SearchPhaseController.ReducedQueryPhase reducedQueryPhase
) {
ThreadedActionListener<RankFeatureDoc[]> rankResultListener = new ThreadedActionListener<>(
context::execute,
new ActionListener<>() {
@Override
public void onResponse(RankFeatureDoc[] docsWithUpdatedScores) {
RankDoc[] topResults = rankFeaturePhaseRankCoordinatorContext.rankAndPaginate(docsWithUpdatedScores, true);
SearchPhaseController.ReducedQueryPhase reducedRankFeaturePhase = newReducedQueryPhaseResults(
reducedQueryPhase,
topResults
);
moveToNextPhase(rankPhaseResults, reducedRankFeaturePhase);
}
@Override
public void onFailure(Exception e) {
if (rankFeaturePhaseRankCoordinatorContext.failuresAllowed()) {
// TODO: handle the exception somewhere
// don't want to log the entire stack trace, it's not helpful here
logger.warn("Exception computing updated ranks, continuing with existing ranks: {}", e.toString());
// use the existing score docs as-is
// downstream things expect every doc to have a score, so we need to infer a score here
// if the doc doesn't otherwise have one. We can use the rank to infer a possible score instead (1/rank).
ScoreDoc[] inputDocs = reducedQueryPhase.sortedTopDocs().scoreDocs();
RankFeatureDoc[] rankDocs = new RankFeatureDoc[inputDocs.length];
for (int i = 0; i < inputDocs.length; i++) {
ScoreDoc doc = inputDocs[i];
rankDocs[i] = new RankFeatureDoc(doc.doc, Float.isNaN(doc.score) ? 1f / (i + 1) : doc.score, doc.shardIndex);
}
RankDoc[] topResults = rankFeaturePhaseRankCoordinatorContext.rankAndPaginate(rankDocs, false);
SearchPhaseController.ReducedQueryPhase reducedRankFeaturePhase = newReducedQueryPhaseResults(
reducedQueryPhase,
topResults
);
moveToNextPhase(rankPhaseResults, reducedRankFeaturePhase);
} else {
context.onPhaseFailure(NAME, "Computing updated ranks for results failed", e);
}
}
}
);
rankFeaturePhaseRankCoordinatorContext.computeRankScoresForGlobalResults(
rankPhaseResults.getSuccessfulResults()
.flatMap(r -> Arrays.stream(r.rankFeatureResult().shardResult().rankFeatureDocs))
.filter(rfd -> rfd.featureData != null)
.toArray(RankFeatureDoc[]::new),
rankResultListener
);
}
private SearchPhaseController.ReducedQueryPhase newReducedQueryPhaseResults(
SearchPhaseController.ReducedQueryPhase reducedQueryPhase,
ScoreDoc[] scoreDocs
) {
return new SearchPhaseController.ReducedQueryPhase(
reducedQueryPhase.totalHits(),
reducedQueryPhase.fetchHits(),
maxScore(scoreDocs),
reducedQueryPhase.timedOut(),
reducedQueryPhase.terminatedEarly(),
reducedQueryPhase.suggest(),
reducedQueryPhase.aggregations(),
reducedQueryPhase.profileBuilder(),
new SearchPhaseController.SortedTopDocs(scoreDocs, false, null, null, null, 0),
reducedQueryPhase.sortValueFormats(),
reducedQueryPhase.queryPhaseRankCoordinatorContext(),
reducedQueryPhase.numReducePhases(),
reducedQueryPhase.size(),
reducedQueryPhase.from(),
reducedQueryPhase.isEmptyResult(),
reducedQueryPhase.timeRangeFilterFromMillis()
);
}
private float maxScore(ScoreDoc[] scoreDocs) {
float maxScore = Float.NaN;
for (ScoreDoc scoreDoc : scoreDocs) {
if (Float.isNaN(maxScore) || scoreDoc.score > maxScore) {
maxScore = scoreDoc.score;
}
}
return maxScore;
}
void moveToNextPhase(SearchPhaseResults<SearchPhaseResult> phaseResults, SearchPhaseController.ReducedQueryPhase reducedQueryPhase) {
context.executeNextPhase(NAME, () -> new FetchSearchPhase(phaseResults, aggregatedDfs, context, reducedQueryPhase));
}
}
| RankFeaturePhase |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/DateCheckerTest.java | {
"start": 4155,
"end": 4514
} | class ____ {
private static final int MAY = 4;
Date good = new Date(120, MAY, 31);
}
""")
.doTest();
}
@Test
public void constructor_nonConstants() {
helper
.addSourceLines(
"TestClass.java",
"""
import java.util.Date;
public | TestClass |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/NotInMountpointException.java | {
"start": 1088,
"end": 1310
} | class ____ in cases where the given path is not mounted
* through viewfs.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving /*Evolving for a release,to be changed to Stable */
@SuppressWarnings("serial")
public | used |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java | {
"start": 65872,
"end": 76629
} | class ____ extends
com.google.protobuf.GeneratedMessage
implements OptRequestProtoOrBuilder {
// Use OptRequestProto.newBuilder() to construct.
private OptRequestProto(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private OptRequestProto(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final OptRequestProto defaultInstance;
public static OptRequestProto getDefaultInstance() {
return defaultInstance;
}
public OptRequestProto getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private OptRequestProto(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
message_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_OptRequestProto_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_OptRequestProto_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto.Builder.class);
}
public static com.google.protobuf.Parser<OptRequestProto> PARSER =
new com.google.protobuf.AbstractParser<OptRequestProto>() {
public OptRequestProto parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new OptRequestProto(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<OptRequestProto> getParserForType() {
return PARSER;
}
private int bitField0_;
// optional string message = 1;
public static final int MESSAGE_FIELD_NUMBER = 1;
private java.lang.Object message_;
/**
* <code>optional string message = 1;</code>
*/
public boolean hasMessage() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional string message = 1;</code>
*/
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
message_ = s;
}
return s;
}
}
/**
* <code>optional string message = 1;</code>
*/
public com.google.protobuf.ByteString
getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
message_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getMessageBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getMessageBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto)) {
return super.equals(obj);
}
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto other = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto) obj;
boolean result = true;
result = result && (hasMessage() == other.hasMessage());
if (hasMessage()) {
result = result && getMessage()
.equals(other.getMessage());
}
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
}
private int memoizedHashCode = 0;
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
if (hasMessage()) {
hash = (37 * hash) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code hadoop.common.OptRequestProto}
*/
public static final | OptRequestProto |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/common/TieredStorageInputChannelId.java | {
"start": 985,
"end": 1947
} | class ____ implements TieredStorageDataIdentifier, Serializable {
private static final long serialVersionUID = 1L;
private final int inputChannelId;
public TieredStorageInputChannelId(int inputChannelId) {
this.inputChannelId = inputChannelId;
}
public int getInputChannelId() {
return inputChannelId;
}
@Override
public int hashCode() {
return Objects.hashCode(inputChannelId);
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null || getClass() != that.getClass()) {
return false;
}
TieredStorageInputChannelId thatID = (TieredStorageInputChannelId) that;
return inputChannelId == thatID.inputChannelId;
}
@Override
public String toString() {
return "TieredStorageInputChannelId{" + "Id=" + inputChannelId + '}';
}
}
| TieredStorageInputChannelId |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/wall/Violation.java | {
"start": 656,
"end": 754
} | interface ____ {
int getErrorCode();
String getMessage();
String toString();
}
| Violation |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/util/TestLightWeightHashSet.java | {
"start": 13055,
"end": 13154
} | class ____ is used in
* {@link TestLightWeightHashSet#testGetElement()}
*/
private static | which |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/factory/named/TemplateFactory.java | {
"start": 791,
"end": 1073
} | class ____ {
@Prototype
@Named("csw-test-template")
public Template cswTemplate() {
return new CSWTestTemplate();
}
@Prototype
@Named("ias-test-template")
public Template iasTemplate() {
return new IASTestTemplate();
}
}
| TemplateFactory |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/taobao/SpecialStringTest.java | {
"start": 147,
"end": 1295
} | class ____ extends TestCase {
public void test_for_special() throws Exception {
VO vo = new VO();
vo.value = "{\"aurl\"";
String text = JSON.toJSONString(vo);
VO vo1 = JSON.parseObject(text, VO.class);
Assert.assertEquals(vo1.value, vo.value);
}
public void test_for_special_1() throws Exception {
VO vo = new VO();
vo.value = "{\"aurl\":\"http://a.m.taobao.com/i529666038203.htm\",\"eurl\":\"http://click.mz.simba.taobao.com/ecpm?e=FKzStLpktUcmgME64bmjnBsQmLP5zomMI9WwdvViswDtdMUS1TLPryFiqQmsaUcblU3hrUulblXi4Nf5jVnFI3mESrWAJFi8UK7RDtIZydUyXElRAMLwo3HZWQvTKXBpyitB%2BgALy7j45JkIPnsiapEFjIWbdXJAnae9i5WIlhTnQ%2FthEaQ9IuT5J4gzB5T%2FcKP7YijzmvIZWnX1fL8Wv2yOkjnv1RfOuAwHNITyYhs0036Nbzw1rue9DcuU1VaInAsdAQs%2BcFbs41NPY6%2FbqjqRHfjhCyty&u=http%3A%2F%2Fa.m.taobao.com%2Fi529666038203.htm&k=289\",\"tbgoodslink\":\"http://i.mmcdn.cn/simba/img/TB120WTMpXXXXazXXXXSutbFXXX.jpg\",\"tmpl\":\"\"}";
String text = JSON.toJSONString(vo);
VO vo1 = JSON.parseObject(text, VO.class);
Assert.assertEquals(vo1.value, vo.value);
}
public static | SpecialStringTest |
java | netty__netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java | {
"start": 17945,
"end": 20244
} | class ____ extends AggregatedFullHttpMessage
implements FullHttpResponse {
AggregatedFullHttpResponse(HttpResponse message, ByteBuf content, HttpHeaders trailingHeaders) {
super(message, content, trailingHeaders);
}
@Override
public FullHttpResponse copy() {
return replace(content().copy());
}
@Override
public FullHttpResponse duplicate() {
return replace(content().duplicate());
}
@Override
public FullHttpResponse retainedDuplicate() {
return replace(content().retainedDuplicate());
}
@Override
public FullHttpResponse replace(ByteBuf content) {
DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content,
headers().copy(), trailingHeaders().copy());
dup.setDecoderResult(decoderResult());
return dup;
}
@Override
public FullHttpResponse setStatus(HttpResponseStatus status) {
((HttpResponse) message).setStatus(status);
return this;
}
@Override
public HttpResponseStatus getStatus() {
return ((HttpResponse) message).status();
}
@Override
public HttpResponseStatus status() {
return getStatus();
}
@Override
public FullHttpResponse setProtocolVersion(HttpVersion version) {
super.setProtocolVersion(version);
return this;
}
@Override
public FullHttpResponse retain(int increment) {
super.retain(increment);
return this;
}
@Override
public FullHttpResponse retain() {
super.retain();
return this;
}
@Override
public FullHttpResponse touch(Object hint) {
super.touch(hint);
return this;
}
@Override
public FullHttpResponse touch() {
super.touch();
return this;
}
@Override
public String toString() {
return HttpMessageUtil.appendFullResponse(new StringBuilder(256), this).toString();
}
}
}
| AggregatedFullHttpResponse |
java | alibaba__nacos | client-basic/src/main/java/com/alibaba/nacos/client/env/SearchableProperties.java | {
"start": 1222,
"end": 8341
} | class ____ implements NacosClientProperties {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchableProperties.class);
private static final JvmArgsPropertySource JVM_ARGS_PROPERTY_SOURCE = new JvmArgsPropertySource();
private static final SystemEnvPropertySource SYSTEM_ENV_PROPERTY_SOURCE = new SystemEnvPropertySource();
private static final List<SourceType> SEARCH_ORDER;
private static final CompositeConverter CONVERTER = new CompositeConverter();
static {
SEARCH_ORDER = init();
StringBuilder orderInfo = new StringBuilder("properties search order:");
for (int i = 0; i < SEARCH_ORDER.size(); i++) {
orderInfo.append(SEARCH_ORDER.get(i).toString());
if (i < SEARCH_ORDER.size() - 1) {
orderInfo.append("->");
}
}
LOGGER.debug(orderInfo.toString());
}
private static List<SourceType> init() {
List<SourceType> initOrder = Arrays.asList(SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV);
String firstEnv = JVM_ARGS_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
if (StringUtils.isBlank(firstEnv)) {
firstEnv = SYSTEM_ENV_PROPERTY_SOURCE.getProperty(Constants.SysEnv.NACOS_ENV_FIRST);
}
if (StringUtils.isNotBlank(firstEnv)) {
try {
final SourceType sourceType = SourceType.valueOf(firstEnv.toUpperCase());
if (!sourceType.equals(SourceType.PROPERTIES)) {
final int index = initOrder.indexOf(sourceType);
final SourceType replacedSourceType = initOrder.set(0, sourceType);
initOrder.set(index, replacedSourceType);
}
} catch (Exception e) {
LOGGER.warn("first source type parse error, it will be used default order!", e);
}
}
return initOrder;
}
static final SearchableProperties INSTANCE = new SearchableProperties();
private final List<AbstractPropertySource> propertySources;
private final PropertiesPropertySource propertiesPropertySource;
private SearchableProperties() {
this(new PropertiesPropertySource());
}
private SearchableProperties(PropertiesPropertySource propertiesPropertySource) {
this.propertiesPropertySource = propertiesPropertySource;
this.propertySources = build(propertiesPropertySource, JVM_ARGS_PROPERTY_SOURCE, SYSTEM_ENV_PROPERTY_SOURCE);
}
@Override
public String getProperty(String key) {
return getProperty(key, null);
}
@Override
public String getProperty(String key, String defaultValue) {
return this.search(key, String.class).orElse(defaultValue);
}
@Override
public String getPropertyFrom(SourceType source, String key) {
if (source == null) {
return this.getProperty(key);
}
switch (source) {
case JVM:
return JVM_ARGS_PROPERTY_SOURCE.getProperty(key);
case ENV:
return SYSTEM_ENV_PROPERTY_SOURCE.getProperty(key);
case PROPERTIES:
return this.propertiesPropertySource.getProperty(key);
default:
return this.getProperty(key);
}
}
@Override
public Properties getProperties(SourceType source) {
if (source == null) {
return null;
}
switch (source) {
case JVM:
return JVM_ARGS_PROPERTY_SOURCE.asProperties();
case ENV:
return SYSTEM_ENV_PROPERTY_SOURCE.asProperties();
case PROPERTIES:
return this.propertiesPropertySource.asProperties();
default:
return null;
}
}
@Override
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
@Override
public Boolean getBoolean(String key, Boolean defaultValue) {
return this.search(key, Boolean.class).orElse(defaultValue);
}
@Override
public Integer getInteger(String key) {
return getInteger(key, null);
}
@Override
public Integer getInteger(String key, Integer defaultValue) {
return this.search(key, Integer.class).orElse(defaultValue);
}
@Override
public Long getLong(String key) {
return getLong(key, null);
}
@Override
public Long getLong(String key, Long defaultValue) {
return this.search(key, Long.class).orElse(defaultValue);
}
@Override
public void setProperty(String key, String value) {
propertiesPropertySource.setProperty(key, value);
}
@Override
public void addProperties(Properties properties) {
propertiesPropertySource.addProperties(properties);
}
@Override
public Properties asProperties() {
Properties properties = new Properties();
final ListIterator<AbstractPropertySource> iterator = propertySources.listIterator(propertySources.size());
while (iterator.hasPrevious()) {
final AbstractPropertySource previous = iterator.previous();
properties.putAll(previous.asProperties());
}
return properties;
}
@Override
public boolean containsKey(String key) {
for (AbstractPropertySource propertySource : propertySources) {
final boolean containing = propertySource.containsKey(key);
if (containing) {
return true;
}
}
return false;
}
private <T> Optional<T> search(String key, Class<T> targetType) {
for (AbstractPropertySource propertySource : propertySources) {
final String value = propertySource.getProperty(key);
if (value != null) {
if (targetType.isAssignableFrom(String.class)) {
return (Optional<T>) Optional.of(value);
}
return Optional.ofNullable(CONVERTER.convert(value, targetType));
}
}
return Optional.empty();
}
private List<AbstractPropertySource> build(AbstractPropertySource... propertySources) {
final Map<SourceType, AbstractPropertySource> sourceMap = Arrays.stream(propertySources)
.collect(Collectors.toMap(AbstractPropertySource::getType, propertySource -> propertySource));
return SEARCH_ORDER.stream().map(sourceMap::get).collect(Collectors.toList());
}
@Override
public NacosClientProperties derive() {
return new SearchableProperties(new PropertiesPropertySource(this.propertiesPropertySource));
}
@Override
public NacosClientProperties derive(Properties properties) {
final NacosClientProperties nacosClientProperties = this.derive();
nacosClientProperties.addProperties(properties);
return nacosClientProperties;
}
}
| SearchableProperties |
java | dropwizard__dropwizard | dropwizard-jackson/src/test/java/io/dropwizard/jackson/AnnotationSensitivePropertyNamingStrategyTest.java | {
"start": 614,
"end": 957
} | class ____ {
@JsonProperty
@Nullable
String firstName;
@SuppressWarnings({ "UnusedDeclaration", "unused" }) // Jackson
private RegularExample() {}
public RegularExample(String firstName) {
this.firstName = firstName;
}
}
@JsonSnakeCase
public static | RegularExample |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutput.java | {
"start": 9770,
"end": 16889
} | class ____ overridden to bypass StreamOutput's
// intermediary buffers
@Override
public void writeString(String str) throws IOException {
final int currentPageOffset = this.currentPageOffset;
final int charCount = str.length();
int bytesNeededForVInt = vIntLength(charCount);
// maximum serialized length is 3 bytes per char + n bytes for the vint
if (charCount * 3 + bytesNeededForVInt > (pageSize - currentPageOffset)) {
super.writeString(str);
return;
}
BytesRef currentPage = currentBytesRef;
int offset = currentPage.offset + currentPageOffset;
byte[] buffer = currentPage.bytes;
// mostly duplicated from StreamOutput.writeString to to get more reliable compilation of this very hot loop
putVInt(charCount, bytesNeededForVInt, currentPage.bytes, offset);
offset += bytesNeededForVInt;
for (int i = 0; i < charCount; i++) {
final int c = str.charAt(i);
if (c <= 0x007F) {
buffer[offset++] = ((byte) c);
} else if (c > 0x07FF) {
buffer[offset++] = ((byte) (0xE0 | c >> 12 & 0x0F));
buffer[offset++] = ((byte) (0x80 | c >> 6 & 0x3F));
buffer[offset++] = ((byte) (0x80 | c >> 0 & 0x3F));
} else {
buffer[offset++] = ((byte) (0xC0 | c >> 6 & 0x1F));
buffer[offset++] = ((byte) (0x80 | c >> 0 & 0x3F));
}
}
this.currentPageOffset = offset - currentPage.offset;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void seek(long position) {
ensureCapacityFromPosition(position);
if (position > 0) {
int offsetInPage = (int) (position % pageSize);
int pageIndex = (int) position / pageSize;
// Special handling for seeking to the first index in a new page, which is handled as a seeking to one-after the last index
// in the previous case. This is done so that seeking to the first index of a new page does not cause a page allocation while
// still allowing a fast check via (pageSize - currentPageOffset) on the remaining size in the current page in all other
// methods.
if (offsetInPage == 0) {
this.pageIndex = pageIndex - 1;
this.currentPageOffset = pageSize;
} else {
this.pageIndex = pageIndex;
this.currentPageOffset = offsetInPage;
}
} else {
// We always have an initial page so special handling for seeking to 0.
assert position == 0;
this.pageIndex = 0;
this.currentPageOffset = 0;
}
this.currentBytesRef = pages.get(pageIndex).v();
}
public void skip(int length) {
seek(position() + length);
}
@Override
public void close() {
var pages = this.pages;
if (pages != null) {
closeFields();
Releasables.close(pages);
}
}
/**
* Move the contents written to this stream to a {@link ReleasableBytesReference}. Closing this instance becomes a noop after
* this method returns successfully and its buffers need to be released by releasing the returned bytes reference.
*
* @return a {@link ReleasableBytesReference} that must be released once no longer needed
*/
public ReleasableBytesReference moveToBytesReference() {
var bytes = bytes();
var pages = this.pages;
closeFields();
return new ReleasableBytesReference(bytes, () -> Releasables.close(pages));
}
private void closeFields() {
this.pages = null;
this.currentBytesRef = null;
this.pageIndex = -1;
this.currentPageOffset = pageSize;
this.currentCapacity = 0;
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number of valid
* bytes in this output stream.
* @see ByteArrayOutputStream#size()
*/
public int size() {
return Math.toIntExact(position());
}
@Override
public BytesReference bytes() {
int position = (int) position();
if (position == 0) {
return BytesArray.EMPTY;
} else {
final int adjustment;
final int bytesInLastPage;
final int remainder = position % pageSize;
if (remainder != 0) {
adjustment = 1;
bytesInLastPage = remainder;
} else {
adjustment = 0;
bytesInLastPage = pageSize;
}
final int pageCount = (position / pageSize) + adjustment;
if (pageCount == 1) {
BytesRef page = pages.get(0).v();
return new BytesArray(page.bytes, page.offset, bytesInLastPage);
} else {
BytesReference[] references = new BytesReference[pageCount];
for (int i = 0; i < pageCount - 1; ++i) {
references[i] = new BytesArray(this.pages.get(i).v());
}
BytesRef last = this.pages.get(pageCount - 1).v();
references[pageCount - 1] = new BytesArray(last.bytes, last.offset, bytesInLastPage);
return CompositeBytesReference.of(references);
}
}
}
private void ensureCapacity(int bytesNeeded) {
assert bytesNeeded > pageSize - currentPageOffset;
ensureCapacityFromPosition(position() + bytesNeeded);
}
private void ensureCapacityFromPosition(long newPosition) {
// Integer.MAX_VALUE is not a multiple of the page size so we can only allocate the largest multiple of the pagesize that is less
// than Integer.MAX_VALUE
if (newPosition > Integer.MAX_VALUE - (Integer.MAX_VALUE % pageSize)) {
throw new IllegalArgumentException(getClass().getSimpleName() + " cannot hold more than 2GB of data");
} else if (pages == null) {
throw new IllegalStateException("Cannot use " + getClass().getSimpleName() + " after it has been closed");
}
long additionalCapacityNeeded = newPosition - currentCapacity;
if (additionalCapacityNeeded > 0) {
// Calculate number of additional pages needed
int additionalPagesNeeded = (int) ((additionalCapacityNeeded + pageSize - 1) / pageSize);
pages.ensureCapacity(pages.size() + additionalPagesNeeded);
for (int i = 0; i < additionalPagesNeeded; i++) {
Recycler.V<BytesRef> newPage = recycler.obtain();
assert pageSize == newPage.v().length;
pages.add(newPage);
}
currentCapacity += additionalPagesNeeded * pageSize;
}
}
private void nextPage() {
pageIndex++;
currentPageOffset = 0;
currentBytesRef = pages.get(pageIndex).v();
}
}
| are |
java | quarkusio__quarkus | extensions/kubernetes-config/runtime/src/main/java/io/quarkus/kubernetes/config/runtime/ConfigMapConfigSourceUtil.java | {
"start": 1432,
"end": 1862
} | class ____ extends MapBackedConfigSource {
private static final String NAME_PREFIX = "ConfigMapLiteralDataPropertiesConfigSource[configMap=";
public ConfigMapLiteralDataPropertiesConfigSource(String configMapName, Map<String, String> propertyMap, int ordinal) {
super(NAME_PREFIX + configMapName + "]", propertyMap, ordinal);
}
}
private static | ConfigMapLiteralDataPropertiesConfigSource |
java | google__guice | core/src/com/google/inject/spi/LinkedKeyBinding.java | {
"start": 859,
"end": 1151
} | interface ____<T> extends Binding<T> {
/**
* Returns the linked key used to resolve injections. That binding can be retrieved from an
* injector using {@link com.google.inject.Injector#getBinding(Key) Injector.getBinding(key)}.
*/
Key<? extends T> getLinkedKey();
}
| LinkedKeyBinding |
java | apache__flink | flink-connectors/flink-file-sink-common/src/main/java/org/apache/flink/streaming/api/functions/sink/filesystem/OutputStreamBasedPartFileWriter.java | {
"start": 13236,
"end": 17626
} | class ____
implements SimpleVersionedSerializer<InProgressFileRecoverable> {
private static final int MAGIC_NUMBER = 0xb3a4073d;
private final SimpleVersionedSerializer<RecoverableWriter.ResumeRecoverable>
resumeSerializer;
OutputStreamBasedInProgressFileRecoverableSerializer(
SimpleVersionedSerializer<RecoverableWriter.ResumeRecoverable> resumeSerializer) {
this.resumeSerializer = resumeSerializer;
}
@Override
public int getVersion() {
return 2;
}
@Override
public byte[] serialize(InProgressFileRecoverable inProgressRecoverable)
throws IOException {
OutputStreamBasedInProgressFileRecoverable outputStreamBasedInProgressRecoverable =
(OutputStreamBasedInProgressFileRecoverable) inProgressRecoverable;
DataOutputSerializer dataOutputSerializer = new DataOutputSerializer(256);
dataOutputSerializer.writeInt(MAGIC_NUMBER);
serializeV2(outputStreamBasedInProgressRecoverable, dataOutputSerializer);
return dataOutputSerializer.getCopyOfBuffer();
}
@Override
public InProgressFileRecoverable deserialize(int version, byte[] serialized)
throws IOException {
switch (version) {
case 1:
DataInputView dataInputView = new DataInputDeserializer(serialized);
validateMagicNumber(dataInputView);
return deserializeV1(dataInputView);
case 2:
dataInputView = new DataInputDeserializer(serialized);
validateMagicNumber(dataInputView);
return deserializeV2(dataInputView);
default:
throw new IOException("Unrecognized version or corrupt state: " + version);
}
}
public SimpleVersionedSerializer<RecoverableWriter.ResumeRecoverable>
getResumeSerializer() {
return resumeSerializer;
}
private void serializeV2(
final OutputStreamBasedInProgressFileRecoverable
outputStreamBasedInProgressRecoverable,
final DataOutputView dataOutputView)
throws IOException {
boolean pathAvailable = outputStreamBasedInProgressRecoverable.targetPath != null;
dataOutputView.writeBoolean(pathAvailable);
if (pathAvailable) {
dataOutputView.writeUTF(
outputStreamBasedInProgressRecoverable.targetPath.toUri().toString());
}
SimpleVersionedSerialization.writeVersionAndSerialize(
resumeSerializer,
outputStreamBasedInProgressRecoverable.getResumeRecoverable(),
dataOutputView);
}
private OutputStreamBasedInProgressFileRecoverable deserializeV1(
final DataInputView dataInputView) throws IOException {
return new OutputStreamBasedInProgressFileRecoverable(
SimpleVersionedSerialization.readVersionAndDeSerialize(
resumeSerializer, dataInputView));
}
private OutputStreamBasedInProgressFileRecoverable deserializeV2(
final DataInputView dataInputView) throws IOException {
Path path = null;
if (dataInputView.readBoolean()) {
path = new Path(dataInputView.readUTF());
}
return new OutputStreamBasedInProgressFileRecoverable(
SimpleVersionedSerialization.readVersionAndDeSerialize(
resumeSerializer, dataInputView),
path);
}
private static void validateMagicNumber(final DataInputView dataInputView)
throws IOException {
final int magicNumber = dataInputView.readInt();
if (magicNumber != MAGIC_NUMBER) {
throw new IOException(
String.format("Corrupt data: Unexpected magic number %08X", magicNumber));
}
}
}
/** The serializer for {@link OutputStreamBasedPendingFileRecoverable}. */
public static | OutputStreamBasedInProgressFileRecoverableSerializer |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/MethodVisitor.java | {
"start": 18428,
"end": 21098
} | class ____ parameter (see {@link Type#getInternalName()}).
*
* @param opcode the opcode of the type instruction to be visited. This opcode is either NEW,
* ANEWARRAY, CHECKCAST or INSTANCEOF.
* @param type the operand of the instruction to be visited. This operand must be the internal
* name of an object or array class (see {@link Type#getInternalName()}).
*/
public void visitTypeInsn(final int opcode, final String type) {
if (mv != null) {
mv.visitTypeInsn(opcode, type);
}
}
/**
* Visits a field instruction. A field instruction is an instruction that loads or stores the
* value of a field of an object.
*
* @param opcode the opcode of the type instruction to be visited. This opcode is either
* GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD.
* @param owner the internal name of the field's owner class (see {@link Type#getInternalName()}).
* @param name the field's name.
* @param descriptor the field's descriptor (see {@link Type}).
*/
public void visitFieldInsn(
final int opcode, final String owner, final String name, final String descriptor) {
if (mv != null) {
mv.visitFieldInsn(opcode, owner, name, descriptor);
}
}
/**
* Visits a method instruction. A method instruction is an instruction that invokes a method.
*
* @param opcode the opcode of the type instruction to be visited. This opcode is either
* INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or INVOKEINTERFACE.
* @param owner the internal name of the method's owner class (see {@link
* Type#getInternalName()}).
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type}).
* @deprecated use {@link #visitMethodInsn(int, String, String, String, boolean)} instead.
*/
@Deprecated
public void visitMethodInsn(
final int opcode, final String owner, final String name, final String descriptor) {
int opcodeAndSource = opcode | (api < Opcodes.ASM5 ? Opcodes.SOURCE_DEPRECATED : 0);
visitMethodInsn(opcodeAndSource, owner, name, descriptor, opcode == Opcodes.INVOKEINTERFACE);
}
/**
* Visits a method instruction. A method instruction is an instruction that invokes a method.
*
* @param opcode the opcode of the type instruction to be visited. This opcode is either
* INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or INVOKEINTERFACE.
* @param owner the internal name of the method's owner class (see {@link
* Type#getInternalName()}).
* @param name the method's name.
* @param descriptor the method's descriptor (see {@link Type}).
* @param isInterface if the method's owner | as |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/FragmentRenderingStreamTests.java | {
"start": 5495,
"end": 5667
} | class ____ {
SseEmitter handleWithSseEmitter() {
return null;
}
Flux<ModelAndView> handleWithFlux() {
return null;
}
}
@Configuration
static | TestController |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelFlatMapIterable.java | {
"start": 1109,
"end": 2218
} | class ____<T, R> extends ParallelFlowable<R> {
final ParallelFlowable<T> source;
final Function<? super T, ? extends Iterable<? extends R>> mapper;
final int prefetch;
public ParallelFlatMapIterable(
ParallelFlowable<T> source,
Function<? super T, ? extends Iterable<? extends R>> mapper,
int prefetch) {
this.source = source;
this.mapper = mapper;
this.prefetch = prefetch;
}
@Override
public int parallelism() {
return source.parallelism();
}
@Override
public void subscribe(Subscriber<? super R>[] subscribers) {
subscribers = RxJavaPlugins.onSubscribe(this, subscribers);
if (!validate(subscribers)) {
return;
}
int n = subscribers.length;
@SuppressWarnings("unchecked")
final Subscriber<T>[] parents = new Subscriber[n];
for (int i = 0; i < n; i++) {
parents[i] = FlowableFlattenIterable.subscribe(subscribers[i], mapper, prefetch);
}
source.subscribe(parents);
}
}
| ParallelFlatMapIterable |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/ConvertingDeserializerTest.java | {
"start": 1410,
"end": 1604
} | class ____ extends StdConverter<int[], Point>
{
@Override public Point convert(int[] value) {
return new Point(value[0], value[1]);
}
}
static | PointConverter |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/time/RemainingTimeTests.java | {
"start": 546,
"end": 1838
} | class ____ extends ESTestCase {
public void testRemainingTime() {
var remainingTime = RemainingTime.from(times(Instant.now(), Instant.now().plusSeconds(60)), TimeValue.timeValueSeconds(30));
assertThat(remainingTime.get(), Matchers.greaterThan(TimeValue.ZERO));
assertThat(remainingTime.get(), Matchers.equalTo(TimeValue.ZERO));
}
public void testRemainingTimeMaxValue() {
var remainingTime = RemainingTime.from(
times(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60)),
TimeValue.timeValueSeconds(30)
);
assertThat(remainingTime.get(), Matchers.equalTo(TimeValue.timeValueSeconds(30)));
assertThat(remainingTime.get(), Matchers.equalTo(TimeValue.ZERO));
}
public void testMaxTime() {
var remainingTime = RemainingTime.from(Instant::now, TimeValue.MAX_VALUE);
assertThat(remainingTime.get(), Matchers.equalTo(TimeValue.MAX_VALUE));
}
// always add the first value, which is read when RemainingTime.from is called, then add the test values
private Supplier<Instant> times(Instant... instants) {
var startTime = Stream.of(Instant.now());
return Stream.concat(startTime, Arrays.stream(instants)).iterator()::next;
}
}
| RemainingTimeTests |
java | resilience4j__resilience4j | resilience4j-spring-boot2/src/main/java/io/github/resilience4j/circuitbreaker/monitoring/endpoint/CircuitBreakerServerSideEvent.java | {
"start": 1614,
"end": 2218
} | class ____ used to produce Circuit breaker events as streams.
* <p>
* The following endpoints are automatically generated and events are produced as Server Sent Event(SSE)
* curl -vv http://localhost:8090/actuator/stream-circuitbreaker-events
* curl -vv http://localhost:8090/actuator/stream-circuitbreaker-events/{circuitbreakername}
* curl -vv http://localhost:8090/actuator/stream-circuitbreaker-events/{circuitbreakername}/{errorType}
*
* Note: Please see the example of how to consume SSE event here CircuitBreakerStreamEventsTest.java
*/
@Endpoint(id = "streamcircuitbreakerevents")
public | is |
java | apache__camel | components/camel-http/src/test/java/org/apache/camel/component/http/handler/ProxyAndBasicAuthenticationValidationHandler.java | {
"start": 1140,
"end": 2450
} | class ____ extends AuthenticationValidationHandler {
private final String proxyPassword;
private final String proxyUser;
public ProxyAndBasicAuthenticationValidationHandler(String expectedMethod,
String expectedQuery, Object expectedContent,
String responseContent, String user, String password,
String proxyUser, String proxyPassword) {
super(expectedMethod, expectedQuery, expectedContent, responseContent, user, password);
this.proxyUser = proxyUser;
this.proxyPassword = proxyPassword;
}
@Override
public void handle(
final ClassicHttpRequest request, final ClassicHttpResponse response,
final HttpContext context)
throws HttpException, IOException {
if (!getExpectedProxyCredential().equals(context.getAttribute("proxy-creds"))) {
response.setCode(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
return;
}
super.handle(request, response, context);
}
private Object getExpectedProxyCredential() {
return proxyUser + ":" + proxyPassword;
}
}
| ProxyAndBasicAuthenticationValidationHandler |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AuditInterceptorAsyncDelegateIssueTest.java | {
"start": 1380,
"end": 3193
} | class ____ extends ContextTestSupport {
private MyIntercepStrategy strategy;
@Override
@BeforeEach
public void setUp() throws Exception {
strategy = new MyIntercepStrategy();
super.setUp();
}
@Test
public void testOk() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("mock:handled").expectedMessageCount(0);
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
assertTrue(strategy.isInvoked());
}
@Test
public void testILE() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:handled").expectedMessageCount(1);
getMockEndpoint("mock:error").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(0);
template.sendBody("direct:iae", "Hello World");
assertMockEndpointsSatisfied();
assertTrue(strategy.isInvoked());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
getContext().getCamelContextExtension().addInterceptStrategy(strategy);
onException(IllegalArgumentException.class).handled(true).to("mock:handled");
errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(1));
from("direct:start").to("mock:result");
from("direct:iae").throwException(new IllegalArgumentException("Damn"));
}
};
}
private static final | AuditInterceptorAsyncDelegateIssueTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KeystoneEndpointBuilderFactory.java | {
"start": 1513,
"end": 1650
} | interface ____ {
/**
* Builder for endpoint for the OpenStack Keystone component.
*/
public | KeystoneEndpointBuilderFactory |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/GroupIdNotFoundException.java | {
"start": 847,
"end": 987
} | class ____ extends ApiException {
public GroupIdNotFoundException(String message) {
super(message);
}
}
| GroupIdNotFoundException |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDecommission.java | {
"start": 4437,
"end": 4490
} | class ____ the decommissioning of nodes.
*/
public | tests |
java | quarkusio__quarkus | extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/ClientStubCompressionTest.java | {
"start": 795,
"end": 1634
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(MyConsumer.class,
MutinyGreeterGrpc.class, GreeterGrpc.class,
MutinyGreeterGrpc.MutinyGreeterStub.class,
HelloService.class, HelloRequest.class, HelloReply.class,
HelloReplyOrBuilder.class, HelloRequestOrBuilder.class))
.withConfigurationResource("hello-config-compression.properties");
@Inject
MyConsumer consumer;
@Test
public void testCallOptions() {
assertEquals("gzip", consumer.service.getCallOptions().getCompressor());
}
@Singleton
static | ClientStubCompressionTest |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/SafeTreeSet.java | {
"start": 1239,
"end": 5944
} | class ____<E> implements Serializable, NavigableSet<E> {
@SuppressWarnings("unchecked")
private static final Comparator<Object> NATURAL_ORDER =
new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return ((Comparable<Object>) o1).compareTo(o2);
}
};
private final NavigableSet<E> delegate;
public SafeTreeSet() {
this(new TreeSet<E>());
}
public SafeTreeSet(Collection<? extends E> collection) {
this(new TreeSet<E>(collection));
}
public SafeTreeSet(Comparator<? super E> comparator) {
this(new TreeSet<E>(comparator));
}
public SafeTreeSet(SortedSet<E> set) {
this(new TreeSet<E>(set));
}
private SafeTreeSet(NavigableSet<E> delegate) {
this.delegate = delegate;
for (E e : this) {
checkValid(e);
}
}
@Override
public boolean add(E element) {
return delegate.add(checkValid(element));
}
@Override
public boolean addAll(Collection<? extends E> collection) {
for (E e : collection) {
checkValid(e);
}
return delegate.addAll(collection);
}
@Override
public @Nullable E ceiling(E e) {
return delegate.ceiling(checkValid(e));
}
@Override
public void clear() {
delegate.clear();
}
@Override
public Comparator<? super E> comparator() {
Comparator<? super E> comparator = delegate.comparator();
if (comparator == null) {
comparator = (Comparator<? super E>) NATURAL_ORDER;
}
return comparator;
}
@Override
public boolean contains(Object object) {
return delegate.contains(checkValid(object));
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public Iterator<E> descendingIterator() {
return delegate.descendingIterator();
}
@Override
public NavigableSet<E> descendingSet() {
return new SafeTreeSet<>(delegate.descendingSet());
}
@Override
public E first() {
return delegate.first();
}
@Override
public @Nullable E floor(E e) {
return delegate.floor(checkValid(e));
}
@Override
public SortedSet<E> headSet(E toElement) {
return headSet(toElement, false);
}
@Override
public NavigableSet<E> headSet(E toElement, boolean inclusive) {
return new SafeTreeSet<>(delegate.headSet(checkValid(toElement), inclusive));
}
@Override
public @Nullable E higher(E e) {
return delegate.higher(checkValid(e));
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public Iterator<E> iterator() {
return delegate.iterator();
}
@Override
public E last() {
return delegate.last();
}
@Override
public @Nullable E lower(E e) {
return delegate.lower(checkValid(e));
}
@Override
public @Nullable E pollFirst() {
return delegate.pollFirst();
}
@Override
public @Nullable E pollLast() {
return delegate.pollLast();
}
@Override
public boolean remove(Object object) {
return delegate.remove(checkValid(object));
}
@Override
public boolean removeAll(Collection<?> c) {
return delegate.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return delegate.retainAll(c);
}
@Override
public int size() {
return delegate.size();
}
@Override
public NavigableSet<E> subSet(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return new SafeTreeSet<>(
delegate.subSet(
checkValid(fromElement), fromInclusive, checkValid(toElement), toInclusive));
}
@Override
public SortedSet<E> subSet(E fromElement, E toElement) {
return subSet(fromElement, true, toElement, false);
}
@Override
public SortedSet<E> tailSet(E fromElement) {
return tailSet(fromElement, true);
}
@Override
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
return new SafeTreeSet<>(delegate.tailSet(checkValid(fromElement), inclusive));
}
@Override
public Object[] toArray() {
return delegate.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return delegate.toArray(a);
}
@CanIgnoreReturnValue
private <T> T checkValid(T t) {
// a ClassCastException is what's supposed to happen!
@SuppressWarnings("unchecked")
E e = (E) t;
int unused = comparator().compare(e, e);
return t;
}
@Override
public boolean equals(@Nullable Object obj) {
return delegate.equals(obj);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public String toString() {
return delegate.toString();
}
private static final long serialVersionUID = 0L;
}
| SafeTreeSet |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/columnar/vector/MapColumnVector.java | {
"start": 990,
"end": 1068
} | interface ____ extends ColumnVector {
MapData getMap(int i);
}
| MapColumnVector |
java | apache__dubbo | dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/processor/StopZookeeperUnixProcessor.java | {
"start": 1344,
"end": 2846
} | class ____ extends ZookeeperUnixProcessor {
private static final Logger logger = LoggerFactory.getLogger(StopZookeeperUnixProcessor.class);
/**
* The pattern for checking if the zookeeper instance stopped.
*/
private static final Pattern PATTERN_STOPPED = Pattern.compile(".*STOPPED.*");
@Override
protected Process doProcess(ZookeeperContext context, int clientPort) throws DubboTestException {
logger.info(String.format("The zookeeper-%d is stopping...", clientPort));
List<String> commands = new ArrayList<>();
Path zookeeperBin = Paths.get(
context.getSourceFile().getParent().toString(),
String.valueOf(clientPort),
context.getUnpackedDirectory(),
"bin");
commands.add(Paths.get(zookeeperBin.toString(), "zkServer.sh")
.toAbsolutePath()
.toString());
commands.add("stop");
try {
return new ProcessBuilder()
.directory(zookeeperBin.getParent().toFile())
.command(commands)
.inheritIO()
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start();
} catch (IOException e) {
throw new DubboTestException(String.format("Failed to stop zookeeper-%d", clientPort), e);
}
}
@Override
protected Pattern getPattern() {
return PATTERN_STOPPED;
}
}
| StopZookeeperUnixProcessor |
java | quarkusio__quarkus | integration-tests/reactive-messaging-rabbitmq-dyn/src/main/java/io/quarkus/it/rabbitmq/TestCredentialsProvider.java | {
"start": 336,
"end": 938
} | class ____ implements CredentialsProvider {
@ConfigProperty(name = "test-creds-provider.username")
String username;
@ConfigProperty(name = "test-creds-provider.password")
String password;
@Override
public Map<String, String> getCredentials(String credentialsProviderName) {
return Map.of(
CredentialsProvider.USER_PROPERTY_NAME, username,
CredentialsProvider.PASSWORD_PROPERTY_NAME, password,
CredentialsProvider.EXPIRATION_TIMESTAMP_PROPERTY_NAME, Instant.now().plusSeconds(90).toString());
}
}
| TestCredentialsProvider |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/MonoFlatMap.java | {
"start": 6177,
"end": 7761
} | class ____<R> implements InnerConsumer<R> {
@SuppressWarnings("DataFlowIssue") // dummy instance has null parent
static final FlatMapInner<?> CANCELLED = new FlatMapInner<>(null);
final FlatMapMain<?, R> parent;
@SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe
Subscription s;
boolean done;
FlatMapInner(FlatMapMain<?, R> parent) {
this.parent = parent;
}
@Override
public Context currentContext() {
return parent.currentContext();
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return s;
if (key == Attr.ACTUAL) return parent;
if (key == Attr.TERMINATED) return done;
if (key == Attr.CANCELLED) return s == Operators.cancelledSubscription();
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.validate(this.s, s)) {
this.s = s;
if (this.parent.setSecond(this)) {
s.request(Long.MAX_VALUE);
} else {
s.cancel();
}
}
}
@Override
public void onNext(R t) {
if (done) {
Operators.onNextDropped(t, parent.currentContext());
return;
}
done = true;
this.parent.secondComplete(t);
}
@Override
public void onError(Throwable t) {
if (done) {
Operators.onErrorDropped(t, parent.currentContext());
return;
}
done = true;
this.parent.secondError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
this.parent.secondComplete();
}
}
}
| FlatMapInner |
java | apache__camel | components/camel-ibm/camel-ibm-watson-discovery/src/test/java/org/apache/camel/component/ibm/watson/discovery/integration/WatsonDiscoveryIT.java | {
"start": 2250,
"end": 5415
} | class ____ extends WatsonDiscoveryTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(WatsonDiscoveryIT.class);
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint mockResult;
@BeforeEach
public void resetMocks() {
mockResult.reset();
}
@Test
public void testListCollections() throws Exception {
mockResult.expectedMessageCount(1);
template.sendBody("direct:listCollections", "");
mockResult.assertIsSatisfied();
Exchange exchange = mockResult.getExchanges().get(0);
ListCollectionsResponse result = exchange.getIn().getBody(ListCollectionsResponse.class);
assertNotNull(result);
assertNotNull(result.getCollections());
LOG.info("Found {} collections", result.getCollections().size());
result.getCollections().forEach(collection -> {
LOG.info(" Collection: {} (ID: {})", collection.getName(), collection.getCollectionId());
});
}
@Test
public void testQuery() throws Exception {
mockResult.expectedMessageCount(1);
final String query = "IBM Watson";
template.sendBody("direct:query", query);
mockResult.assertIsSatisfied();
Exchange exchange = mockResult.getExchanges().get(0);
QueryResponse result = exchange.getIn().getBody(QueryResponse.class);
assertNotNull(result);
LOG.info("Query returned {} results", result.getMatchingResults());
if (result.getResults() != null && !result.getResults().isEmpty()) {
LOG.info("First result: {}", result.getResults().get(0));
}
}
@Test
public void testQueryWithFilter() throws Exception {
mockResult.expectedMessageCount(1);
final String query = "cloud computing";
final String filter = "enriched_text.entities.type:Company";
template.send("direct:queryWithFilter", exchange -> {
exchange.getIn().setBody(query);
exchange.getIn().setHeader(WatsonDiscoveryConstants.FILTER, filter);
exchange.getIn().setHeader(WatsonDiscoveryConstants.COUNT, 5);
});
mockResult.assertIsSatisfied();
Exchange exchange = mockResult.getExchanges().get(0);
QueryResponse result = exchange.getIn().getBody(QueryResponse.class);
assertNotNull(result);
LOG.info("Filtered query returned {} results", result.getMatchingResults());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:listCollections")
.to(buildEndpointUri("listCollections"))
.to("mock:result");
from("direct:query")
.to(buildEndpointUri("query"))
.to("mock:result");
from("direct:queryWithFilter")
.to(buildEndpointUri("query"))
.to("mock:result");
}
};
}
}
| WatsonDiscoveryIT |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/declare/state/ListStateWithDeclaredNamespace.java | {
"start": 1290,
"end": 3118
} | class ____<K, N, V> extends StateWithDeclaredNamespace<K, N, V>
implements InternalListState<K, N, V> {
private final InternalListState<K, N, V> state;
public ListStateWithDeclaredNamespace(
InternalListState<K, N, V> state, DeclaredVariable<N> declaredNamespace) {
super(state, declaredNamespace);
this.state = state;
}
@Override
public StateFuture<StateIterator<V>> asyncGet() {
resetNamespace();
return state.asyncGet();
}
@Override
public StateFuture<Void> asyncAdd(V value) {
resetNamespace();
return state.asyncAdd(value);
}
@Override
public StateFuture<Void> asyncUpdate(List<V> values) {
resetNamespace();
return state.asyncUpdate(values);
}
@Override
public StateFuture<Void> asyncAddAll(List<V> values) {
resetNamespace();
return state.asyncAddAll(values);
}
@Override
public StateFuture<Void> asyncClear() {
resetNamespace();
return state.asyncClear();
}
@Override
public StateFuture<Void> asyncMergeNamespaces(N target, Collection<N> sources) {
resetNamespace();
return state.asyncMergeNamespaces(target, sources);
}
@Override
public Iterable<V> get() {
return state.get();
}
@Override
public void add(V value) {
state.add(value);
}
@Override
public void update(List<V> values) {
state.update(values);
}
@Override
public void addAll(List<V> values) {
state.addAll(values);
}
@Override
public void clear() {
state.clear();
}
@Override
public void mergeNamespaces(N target, Collection<N> sources) {
state.mergeNamespaces(target, sources);
}
}
| ListStateWithDeclaredNamespace |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/text/CompositeFormat.java | {
"start": 1472,
"end": 4003
} | class ____ extends Format {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = -4329119827877627683L;
/** The parser to use. */
private final Format parser;
/** The formatter to use. */
private final Format formatter;
/**
* Create a format that points its parseObject method to one implementation
* and its format method to another.
*
* @param parser implementation
* @param formatter implementation
*/
public CompositeFormat(final Format parser, final Format formatter) {
this.parser = parser;
this.formatter = formatter;
}
/**
* Uses the formatter Format instance.
*
* @param obj the object to format
* @param toAppendTo the {@link StringBuffer} to append to
* @param pos the FieldPosition to use (or ignore).
* @return {@code toAppendTo}
* @see Format#format(Object, StringBuffer, FieldPosition)
*/
@Override // Therefore has to use StringBuffer
public StringBuffer format(final Object obj, final StringBuffer toAppendTo,
final FieldPosition pos) {
return formatter.format(obj, toAppendTo, pos);
}
/**
* Provides access to the parser Format implementation.
*
* @return formatter Format implementation
*/
public Format getFormatter() {
return this.formatter;
}
/**
* Provides access to the parser Format implementation.
*
* @return parser Format implementation
*/
public Format getParser() {
return this.parser;
}
/**
* Uses the parser Format instance.
*
* @param source the String source
* @param pos the ParsePosition containing the position to parse from, will
* be updated according to parsing success (index) or failure
* (error index)
* @return the parsed Object
* @see Format#parseObject(String, ParsePosition)
*/
@Override
public Object parseObject(final String source, final ParsePosition pos) {
return parser.parseObject(source, pos);
}
/**
* Utility method to parse and then reformat a String.
*
* @param input String to reformat
* @return A reformatted String
* @throws ParseException thrown by parseObject(String) call
*/
public String reformat(final String input) throws ParseException {
return format(parseObject(input));
}
}
| CompositeFormat |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/SimpleFieldParam.java | {
"start": 61,
"end": 223
} | class ____ {
public final String propertyOne;
public SimpleFieldParam(String propertyOne) {
this.propertyOne = propertyOne;
}
}
| SimpleFieldParam |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jChatEndpointBuilderFactory.java | {
"start": 12400,
"end": 16088
} | interface ____ extends EndpointProducerBuilder {
default LangChain4jChatEndpointProducerBuilder basic() {
return (LangChain4jChatEndpointProducerBuilder) 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 AdvancedLangChain4jChatEndpointProducerBuilder 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 AdvancedLangChain4jChatEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Chat Model of type dev.langchain4j.model.chat.ChatModel.
*
* The option is a: <code>dev.langchain4j.model.chat.ChatModel</code>
* type.
*
* Group: advanced
*
* @param chatModel the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jChatEndpointProducerBuilder chatModel(dev.langchain4j.model.chat.ChatModel chatModel) {
doSetProperty("chatModel", chatModel);
return this;
}
/**
* Chat Model of type dev.langchain4j.model.chat.ChatModel.
*
* The option will be converted to a
* <code>dev.langchain4j.model.chat.ChatModel</code> type.
*
* Group: advanced
*
* @param chatModel the value to set
* @return the dsl builder
*/
default AdvancedLangChain4jChatEndpointProducerBuilder chatModel(String chatModel) {
doSetProperty("chatModel", chatModel);
return this;
}
}
/**
* Builder for endpoint for the LangChain4j Chat component.
*/
public | AdvancedLangChain4jChatEndpointProducerBuilder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/FederationQueueWeightPBImpl.java | {
"start": 1332,
"end": 5110
} | class ____ extends FederationQueueWeight {
private FederationQueueWeightProto proto = FederationQueueWeightProto.getDefaultInstance();
private FederationQueueWeightProto.Builder builder = null;
private boolean viaProto = false;
public FederationQueueWeightPBImpl() {
this.builder = FederationQueueWeightProto.newBuilder();
}
public FederationQueueWeightPBImpl(FederationQueueWeightProto proto) {
this.proto = proto;
this.viaProto = true;
}
private synchronized void maybeInitBuilder() {
if (this.viaProto || this.builder == null) {
this.builder = FederationQueueWeightProto.newBuilder(proto);
}
this.viaProto = false;
}
public FederationQueueWeightProto getProto() {
this.proto = this.viaProto ? this.proto : this.builder.build();
this.viaProto = true;
return this.proto;
}
@Override
public String getRouterWeight() {
FederationQueueWeightProtoOrBuilder p = this.viaProto ? this.proto : this.builder;
boolean hasRouterWeight = p.hasRouterWeight();
if (hasRouterWeight) {
return p.getRouterWeight();
}
return null;
}
@Override
public void setRouterWeight(String routerWeight) {
maybeInitBuilder();
if (routerWeight == null) {
builder.clearRouterWeight();
return;
}
builder.setRouterWeight(routerWeight);
}
@Override
public String getAmrmWeight() {
FederationQueueWeightProtoOrBuilder p = this.viaProto ? this.proto : this.builder;
boolean hasAmrmWeight = p.hasAmrmWeight();
if (hasAmrmWeight) {
return p.getAmrmWeight();
}
return null;
}
@Override
public void setAmrmWeight(String amrmWeight) {
maybeInitBuilder();
if (amrmWeight == null) {
builder.clearAmrmWeight();
return;
}
builder.setAmrmWeight(amrmWeight);
}
@Override
public String getHeadRoomAlpha() {
FederationQueueWeightProtoOrBuilder p = this.viaProto ? this.proto : this.builder;
boolean hasHeadRoomAlpha = p.hasHeadRoomAlpha();
if (hasHeadRoomAlpha) {
return p.getHeadRoomAlpha();
}
return null;
}
@Override
public void setHeadRoomAlpha(String headRoomAlpha) {
maybeInitBuilder();
if (headRoomAlpha == null) {
builder.clearHeadRoomAlpha();
return;
}
builder.setHeadRoomAlpha(headRoomAlpha);
}
@Override
public String getQueue() {
FederationQueueWeightProtoOrBuilder p = this.viaProto ? this.proto : this.builder;
boolean hasQueue = p.hasQueue();
if (hasQueue) {
return p.getQueue();
}
return null;
}
@Override
public void setQueue(String queue) {
maybeInitBuilder();
if (queue == null) {
builder.clearQueue();
return;
}
builder.setQueue(queue);
}
@Override
public String getPolicyManagerClassName() {
FederationQueueWeightProtoOrBuilder p = this.viaProto ? this.proto : this.builder;
boolean hasPolicyManagerClassName = p.hasPolicyManagerClassName();
if (hasPolicyManagerClassName) {
return p.getPolicyManagerClassName();
}
return null;
}
@Override
public void setPolicyManagerClassName(String policyManagerClassName) {
maybeInitBuilder();
if (policyManagerClassName == null) {
builder.clearPolicyManagerClassName();
return;
}
builder.setPolicyManagerClassName(policyManagerClassName);
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (!(other instanceof FederationQueueWeight)) {
return false;
}
FederationQueueWeightPBImpl otherImpl = this.getClass().cast(other);
return new EqualsBuilder()
.append(this.getProto(), otherImpl.getProto())
.isEquals();
}
}
| FederationQueueWeightPBImpl |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/node/capabilities/NodesCapabilitiesResponse.java | {
"start": 1060,
"end": 2404
} | class ____ extends BaseNodesResponse<NodeCapability> implements ToXContentFragment {
protected NodesCapabilitiesResponse(ClusterName clusterName, List<NodeCapability> nodes, List<FailedNodeException> failures) {
super(clusterName, nodes, failures);
}
@Override
protected List<NodeCapability> readNodesFrom(StreamInput in) throws IOException {
return TransportAction.localOnly();
}
@Override
protected void writeNodesTo(StreamOutput out, List<NodeCapability> nodes) throws IOException {
TransportAction.localOnly();
}
public Optional<Boolean> isSupported() {
if (hasFailures() || getNodes().isEmpty()) {
// there's no nodes in the response (uh? what about ourselves?)
// or there's a problem (hopefully transient) talking to one or more nodes.
// We don't have enough information to decide if it's supported or not, so return unknown
return Optional.empty();
}
return Optional.of(getNodes().stream().allMatch(NodeCapability::isSupported));
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Optional<Boolean> supported = isSupported();
return builder.field("supported", supported.orElse(null));
}
}
| NodesCapabilitiesResponse |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobPlanInfo.java | {
"start": 13784,
"end": 17719
} | class ____ implements Serializable {
private static final String FIELD_NAME_NUM = "num";
@JsonProperty(FIELD_NAME_NUM)
private final long num;
private static final String FIELD_NAME_ID = "id";
@JsonProperty(FIELD_NAME_ID)
private final String id;
private static final String FIELD_NAME_SHIP_STRATEGY = "ship_strategy";
@Nullable
@JsonProperty(FIELD_NAME_SHIP_STRATEGY)
private final String shipStrategy;
private static final String FIELD_NAME_LOCAL_STRATEGY = "local_strategy";
@Nullable
@JsonInclude(Include.NON_NULL)
@JsonProperty(FIELD_NAME_LOCAL_STRATEGY)
private final String localStrategy;
private static final String FIELD_NAME_CACHING = "caching";
@Nullable
@JsonInclude(Include.NON_NULL)
@JsonProperty(FIELD_NAME_CACHING)
private final String caching;
private static final String FIELD_NAME_EXCHANGE = "exchange";
@JsonProperty(FIELD_NAME_EXCHANGE)
private final String exchange;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Input that = (Input) o;
return Objects.equals(id, that.id)
&& num == that.num
&& Objects.equals(shipStrategy, that.shipStrategy)
&& Objects.equals(localStrategy, that.localStrategy)
&& Objects.equals(caching, that.caching)
&& Objects.equals(exchange, that.exchange);
}
@Override
public int hashCode() {
return Objects.hash(id, num, shipStrategy, localStrategy, caching, exchange);
}
@JsonCreator
public Input(
@JsonProperty(FIELD_NAME_ID) String id,
@JsonProperty(FIELD_NAME_NUM) long num,
@JsonProperty(FIELD_NAME_EXCHANGE) String exchange,
@Nullable @JsonProperty(FIELD_NAME_SHIP_STRATEGY) String shipStrategy,
@Nullable @JsonProperty(FIELD_NAME_LOCAL_STRATEGY) String localStrategy,
@Nullable @JsonProperty(FIELD_NAME_CACHING) String caching) {
this.id = Preconditions.checkNotNull(id);
this.num = Preconditions.checkNotNull(num);
this.exchange = Preconditions.checkNotNull(exchange);
this.shipStrategy = shipStrategy;
this.localStrategy = localStrategy;
this.caching = caching;
}
@JsonIgnore
public long getNum() {
return num;
}
@JsonIgnore
public String getId() {
return id;
}
@JsonIgnore
public String getShipStrategy() {
return shipStrategy;
}
@JsonIgnore
public String getLocalStrategy() {
return localStrategy;
}
@JsonIgnore
public String getCaching() {
return caching;
}
@JsonIgnore
public String getExchange() {
return exchange;
}
}
}
}
}
| Input |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/SimpleProcessorTraceableTest.java | {
"start": 1104,
"end": 1665
} | class ____ extends ContextTestSupport {
@Test
public void testProcess() {
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.setTracing(true);
from("direct:start").process(new MyProcessor());
}
};
}
private static | SimpleProcessorTraceableTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ondeletecascade/OnDeleteCollectionTest.java | {
"start": 2941,
"end": 3088
} | class ____ {
@Id
long id;
boolean a;
@ElementCollection
@OnDelete(action = OnDeleteAction.CASCADE)
Set<String> bs = new HashSet<>();
}
}
| A |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/resequencer/SequenceBuffer.java | {
"start": 990,
"end": 1547
} | class ____<E> implements SequenceSender<E> {
private final BlockingQueue<E> queue;
public SequenceBuffer() {
this.queue = new LinkedBlockingQueue<>();
}
public int size() {
return queue.size();
}
public E take() throws InterruptedException {
return queue.take();
}
public E poll(long timeout) throws InterruptedException {
return queue.poll(timeout, TimeUnit.MILLISECONDS);
}
@Override
public void sendElement(E o) throws Exception {
queue.put(o);
}
}
| SequenceBuffer |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/memory/MemoryManagerBuilder.java | {
"start": 984,
"end": 1684
} | class ____ {
private static final long DEFAULT_MEMORY_SIZE = 32L * DEFAULT_PAGE_SIZE;
private long memorySize = DEFAULT_MEMORY_SIZE;
private int pageSize = DEFAULT_PAGE_SIZE;
private MemoryManagerBuilder() {}
public MemoryManagerBuilder setMemorySize(long memorySize) {
this.memorySize = memorySize;
return this;
}
public MemoryManagerBuilder setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public MemoryManager build() {
return new MemoryManager(memorySize, pageSize);
}
public static MemoryManagerBuilder newBuilder() {
return new MemoryManagerBuilder();
}
}
| MemoryManagerBuilder |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockToMarkCorrupt.java | {
"start": 1198,
"end": 2721
} | class ____ {
/** The corrupted block in a datanode. */
private final Block corrupted;
/** The corresponding block stored in the BlockManager. */
private final BlockInfo stored;
/** The reason to mark corrupt. */
private final String reason;
/** The reason code to be stored */
private final CorruptReplicasMap.Reason reasonCode;
BlockToMarkCorrupt(Block corrupted, BlockInfo stored, String reason,
CorruptReplicasMap.Reason reasonCode) {
Preconditions.checkNotNull(corrupted, "corrupted is null");
Preconditions.checkNotNull(stored, "stored is null");
this.corrupted = corrupted;
this.stored = stored;
this.reason = reason;
this.reasonCode = reasonCode;
}
BlockToMarkCorrupt(Block corrupted, BlockInfo stored, long gs, String reason,
CorruptReplicasMap.Reason reasonCode) {
this(corrupted, stored, reason, reasonCode);
//the corrupted block in datanode has a different generation stamp
this.corrupted.setGenerationStamp(gs);
}
public boolean isCorruptedDuringWrite() {
return stored.getGenerationStamp() > corrupted.getGenerationStamp();
}
public Block getCorrupted() {
return corrupted;
}
public BlockInfo getStored() {
return stored;
}
public String getReason() {
return reason;
}
public Reason getReasonCode() {
return reasonCode;
}
@Override
public String toString() {
return corrupted + "("
+ (corrupted == stored ? "same as stored": "stored=" + stored) + ")";
}
}
| BlockToMarkCorrupt |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ElasticsearchRestClientEndpointBuilderFactory.java | {
"start": 1487,
"end": 1656
} | interface ____ {
/**
* Builder for endpoint for the Elasticsearch Low level Rest Client component.
*/
public | ElasticsearchRestClientEndpointBuilderFactory |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/util/MBeans.java | {
"start": 1538,
"end": 1774
} | class ____ a method to register an MBean using
* our standard naming convention as described in the doc
* for {link {@link #register(String, String, Object)}.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public final | provides |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/unmarshall/simple/trimfield/BindySimpleFixedLengthUnmarshallTrimFieldTest.java | {
"start": 1682,
"end": 2850
} | class ____ {
private static final String URI_MOCK_RESULT = "mock:result";
private static final String URI_DIRECT_START = "direct:start";
@Produce(URI_DIRECT_START)
private ProducerTemplate template;
@EndpointInject(URI_MOCK_RESULT)
private MockEndpoint result;
private String expected;
@Test
@DirtiesContext
public void testUnMarshallMessage() throws Exception {
expected = "10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009 Hello###";
template.sendBody(expected);
result.expectedMessageCount(1);
result.assertIsSatisfied();
// check the model
BindySimpleFixedLengthUnmarshallTrimFieldTest.Order order = result.getReceivedExchanges().get(0).getIn()
.getBody(BindySimpleFixedLengthUnmarshallTrimFieldTest.Order.class);
assertEquals(10, order.getOrderNr());
// the field is not trimmed
assertEquals("Pauline", order.getFirstName());
assertEquals("M ", order.getLastName()); // no trim
assertEquals(" Hello", order.getComment());
}
public static | BindySimpleFixedLengthUnmarshallTrimFieldTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/CopyableValueComparator.java | {
"start": 1362,
"end": 5575
} | class ____<T extends CopyableValue<T> & Comparable<T>>
extends TypeComparator<T> {
private static final long serialVersionUID = 1L;
private final Class<T> type;
private final boolean ascendingComparison;
private transient T reference;
private transient T tempReference;
private final TypeComparator<?>[] comparators = new TypeComparator[] {this};
public CopyableValueComparator(boolean ascending, Class<T> type) {
this.type = type;
this.ascendingComparison = ascending;
this.reference = InstantiationUtil.instantiate(type, CopyableValue.class);
}
@Override
public int hash(T record) {
return record.hashCode();
}
@Override
public void setReference(T toCompare) {
toCompare.copyTo(reference);
}
@Override
public boolean equalToReference(T candidate) {
return candidate.equals(this.reference);
}
@Override
public int compareToReference(TypeComparator<T> referencedComparator) {
T otherRef = ((CopyableValueComparator<T>) referencedComparator).reference;
int comp = otherRef.compareTo(reference);
return ascendingComparison ? comp : -comp;
}
@Override
public int compare(T first, T second) {
int comp = first.compareTo(second);
return ascendingComparison ? comp : -comp;
}
@Override
public int compareSerialized(DataInputView firstSource, DataInputView secondSource)
throws IOException {
if (tempReference == null) {
tempReference = InstantiationUtil.instantiate(type, CopyableValue.class);
}
reference.read(firstSource);
tempReference.read(secondSource);
int comp = reference.compareTo(tempReference);
return ascendingComparison ? comp : -comp;
}
@Override
public boolean supportsNormalizedKey() {
return NormalizableKey.class.isAssignableFrom(type);
}
@Override
public int getNormalizeKeyLen() {
NormalizableKey<?> key = (NormalizableKey<?>) reference;
return key.getMaxNormalizedKeyLen();
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return keyBytes < getNormalizeKeyLen();
}
@Override
public void putNormalizedKey(T record, MemorySegment target, int offset, int numBytes) {
NormalizableKey<?> key = (NormalizableKey<?>) record;
key.copyNormalizedKey(target, offset, numBytes);
}
@Override
public boolean invertNormalizedKey() {
return !ascendingComparison;
}
@Override
public TypeComparator<T> duplicate() {
return new CopyableValueComparator<T>(ascendingComparison, type);
}
@Override
public int extractKeys(Object record, Object[] target, int index) {
target[index] = record;
return 1;
}
@Override
public TypeComparator<?>[] getFlatComparators() {
return comparators;
}
// --------------------------------------------------------------------------------------------
// unsupported normalization
// --------------------------------------------------------------------------------------------
@Override
public boolean supportsSerializationWithKeyNormalization() {
return false;
}
@Override
public void writeWithKeyNormalization(T record, DataOutputView target) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public T readWithKeyDenormalization(T reuse, DataInputView source) throws IOException {
throw new UnsupportedOperationException();
}
// --------------------------------------------------------------------------------------------
// serialization
// --------------------------------------------------------------------------------------------
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// read basic object and the type
s.defaultReadObject();
this.reference = InstantiationUtil.instantiate(type, CopyableValue.class);
this.tempReference = null;
}
}
| CopyableValueComparator |
java | apache__camel | components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/simplebinding/testbean/CustomerService.java | {
"start": 1278,
"end": 2151
} | interface ____ {
@GET
@Path("/customers/{id}/")
Customer getCustomer(@PathParam("id") String id, @QueryParam("test") String test);
@PUT
@Path("/customers/{id}")
Response updateCustomer(Customer customer, @PathParam("id") String id);
@POST
@Path("/customers/")
Response newCustomer(Customer customer, @PathParam("type") String type, @QueryParam("age") int age);
@Path("/customers/vip/{status}")
VipCustomerResource vipCustomer(@PathParam("status") String status);
@Consumes("image/jpeg")
@POST
@Path("/customers/{id}/image_inputstream")
Response uploadImageInputStream(InputStream is);
@Consumes("image/jpeg")
@POST
@Path("/customers/{id}/image_datahandler")
Response uploadImageDataHandler(DataHandler dh);
@Path("/customers/multipart")
MultipartCustomer multipart();
}
| CustomerService |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/internal/security/trust/XdsX509TrustManager.java | {
"start": 2011,
"end": 15807
} | class ____ extends X509ExtendedTrustManager implements X509TrustManager {
// ref: io.grpc.okhttp.internal.OkHostnameVerifier and
// sun.security.x509.GeneralNameInterface
private static final int ALT_DNS_NAME = 2;
private static final int ALT_URI_NAME = 6;
private static final int ALT_IPA_NAME = 7;
private final X509ExtendedTrustManager delegate;
private final Map<String, X509ExtendedTrustManager> spiffeTrustMapDelegates;
private final CertificateValidationContext certContext;
private final boolean autoSniSanValidation;
XdsX509TrustManager(@Nullable CertificateValidationContext certContext,
X509ExtendedTrustManager delegate,
boolean autoSniSanValidation) {
checkNotNull(delegate, "delegate");
this.certContext = certContext;
this.delegate = delegate;
this.spiffeTrustMapDelegates = null;
this.autoSniSanValidation = autoSniSanValidation;
}
XdsX509TrustManager(@Nullable CertificateValidationContext certContext,
Map<String, X509ExtendedTrustManager> spiffeTrustMapDelegates,
boolean autoSniSanValidation) {
checkNotNull(spiffeTrustMapDelegates, "spiffeTrustMapDelegates");
this.spiffeTrustMapDelegates = ImmutableMap.copyOf(spiffeTrustMapDelegates);
this.certContext = certContext;
this.delegate = null;
this.autoSniSanValidation = autoSniSanValidation;
}
private static boolean verifyDnsNameInPattern(
String altNameFromCert, StringMatcher sanToVerifyMatcher) {
if (Strings.isNullOrEmpty(altNameFromCert)) {
return false;
}
switch (sanToVerifyMatcher.getMatchPatternCase()) {
case EXACT:
return verifyDnsNameExact(
altNameFromCert, sanToVerifyMatcher.getExact(), sanToVerifyMatcher.getIgnoreCase());
case PREFIX:
return verifyDnsNamePrefix(
altNameFromCert, sanToVerifyMatcher.getPrefix(), sanToVerifyMatcher.getIgnoreCase());
case SUFFIX:
return verifyDnsNameSuffix(
altNameFromCert, sanToVerifyMatcher.getSuffix(), sanToVerifyMatcher.getIgnoreCase());
case CONTAINS:
return verifyDnsNameContains(
altNameFromCert, sanToVerifyMatcher.getContains(), sanToVerifyMatcher.getIgnoreCase());
case SAFE_REGEX:
return verifyDnsNameSafeRegex(altNameFromCert, sanToVerifyMatcher.getSafeRegex());
default:
throw new IllegalArgumentException(
"Unknown match-pattern-case " + sanToVerifyMatcher.getMatchPatternCase());
}
}
private static boolean verifyDnsNameSafeRegex(
String altNameFromCert, RegexMatcher sanToVerifySafeRegex) {
Pattern safeRegExMatch = Pattern.compile(sanToVerifySafeRegex.getRegex());
return safeRegExMatch.matches(altNameFromCert);
}
private static boolean verifyDnsNamePrefix(
String altNameFromCert, String sanToVerifyPrefix, boolean ignoreCase) {
if (Strings.isNullOrEmpty(sanToVerifyPrefix)) {
return false;
}
return ignoreCase
? altNameFromCert.toLowerCase(Locale.ROOT).startsWith(
sanToVerifyPrefix.toLowerCase(Locale.ROOT))
: altNameFromCert.startsWith(sanToVerifyPrefix);
}
private static boolean verifyDnsNameSuffix(
String altNameFromCert, String sanToVerifySuffix, boolean ignoreCase) {
if (Strings.isNullOrEmpty(sanToVerifySuffix)) {
return false;
}
return ignoreCase
? altNameFromCert.toLowerCase(Locale.ROOT).endsWith(
sanToVerifySuffix.toLowerCase(Locale.ROOT))
: altNameFromCert.endsWith(sanToVerifySuffix);
}
private static boolean verifyDnsNameContains(
String altNameFromCert, String sanToVerifySubstring, boolean ignoreCase) {
if (Strings.isNullOrEmpty(sanToVerifySubstring)) {
return false;
}
return ignoreCase
? altNameFromCert.toLowerCase(Locale.ROOT).contains(
sanToVerifySubstring.toLowerCase(Locale.ROOT))
: altNameFromCert.contains(sanToVerifySubstring);
}
private static boolean verifyDnsNameExact(
String altNameFromCert, String sanToVerifyExact, boolean ignoreCase) {
if (Strings.isNullOrEmpty(sanToVerifyExact)) {
return false;
}
if (sanToVerifyExact.contains("*")) {
return verifyDnsNameWildcard(altNameFromCert, sanToVerifyExact, ignoreCase);
}
return ignoreCase
? sanToVerifyExact.equalsIgnoreCase(altNameFromCert)
: sanToVerifyExact.equals(altNameFromCert);
}
private static boolean verifyDnsNameInSanList(
String altNameFromCert, List<StringMatcher> verifySanList) {
for (StringMatcher verifySan : verifySanList) {
if (verifyDnsNameInPattern(altNameFromCert, verifySan)) {
return true;
}
}
return false;
}
private static boolean verifyOneSanInList(List<?> entry, List<StringMatcher> verifySanList)
throws CertificateParsingException {
// from OkHostnameVerifier.getSubjectAltNames
if (entry == null || entry.size() < 2) {
throw new CertificateParsingException("Invalid SAN entry");
}
Integer altNameType = (Integer) entry.get(0);
if (altNameType == null) {
throw new CertificateParsingException("Invalid SAN entry: null altNameType");
}
switch (altNameType) {
case ALT_DNS_NAME:
case ALT_URI_NAME:
case ALT_IPA_NAME:
return verifyDnsNameInSanList((String) entry.get(1), verifySanList);
default:
return false;
}
}
// logic from Envoy::Extensions::TransportSockets::Tls::ContextImpl::verifySubjectAltName
private static void verifySubjectAltNameInLeaf(
X509Certificate cert, List<StringMatcher> verifyList) throws CertificateException {
Collection<List<?>> names = cert.getSubjectAlternativeNames();
if (names == null || names.isEmpty()) {
throw new CertificateException("Peer certificate SAN check failed");
}
for (List<?> name : names) {
if (verifyOneSanInList(name, verifyList)) {
return;
}
}
// at this point there's no match
throw new CertificateException("Peer certificate SAN check failed");
}
/**
* Verifies SANs in the peer cert chain against verify_subject_alt_name in the certContext.
* This is called from various check*Trusted methods.
*/
@VisibleForTesting
void verifySubjectAltNameInChain(X509Certificate[] peerCertChain,
List<StringMatcher> verifyList) throws CertificateException {
if (certContext == null) {
return;
}
if (verifyList.isEmpty()) {
return;
}
if (peerCertChain == null || peerCertChain.length < 1) {
throw new CertificateException("Peer certificate(s) missing");
}
// verify SANs only in the top cert (leaf cert)
verifySubjectAltNameInLeaf(peerCertChain[0], verifyList);
}
@Override
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket)
throws CertificateException {
chooseDelegate(chain).checkClientTrusted(chain, authType, socket);
verifySubjectAltNameInChain(chain, certContext != null
? certContext.getMatchSubjectAltNamesList() : new ArrayList<>());
}
@Override
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine)
throws CertificateException {
chooseDelegate(chain).checkClientTrusted(chain, authType, sslEngine);
verifySubjectAltNameInChain(chain, certContext != null
? certContext.getMatchSubjectAltNamesList() : new ArrayList<>());
}
@Override
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
chooseDelegate(chain).checkClientTrusted(chain, authType);
verifySubjectAltNameInChain(chain, certContext != null
? certContext.getMatchSubjectAltNamesList() : new ArrayList<>());
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
throws CertificateException {
List<StringMatcher> sniMatchers = null;
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
SSLParameters sslParams = sslSocket.getSSLParameters();
if (sslParams != null) {
sslParams.setEndpointIdentificationAlgorithm("");
sslSocket.setSSLParameters(sslParams);
}
sniMatchers = getAutoSniSanMatchers(sslParams);
}
if (sniMatchers.isEmpty() && certContext != null) {
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
List<StringMatcher> sniMatchersTmp = certContext.getMatchSubjectAltNamesList();
sniMatchers = sniMatchersTmp;
}
chooseDelegate(chain).checkServerTrusted(chain, authType, socket);
verifySubjectAltNameInChain(chain, sniMatchers);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine sslEngine)
throws CertificateException {
List<StringMatcher> sniMatchers = null;
SSLParameters sslParams = sslEngine.getSSLParameters();
if (sslParams != null) {
sslParams.setEndpointIdentificationAlgorithm("");
sslEngine.setSSLParameters(sslParams);
sniMatchers = getAutoSniSanMatchers(sslParams);
}
if (sniMatchers.isEmpty() && certContext != null) {
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
List<StringMatcher> sniMatchersTmp = certContext.getMatchSubjectAltNamesList();
sniMatchers = sniMatchersTmp;
}
chooseDelegate(chain).checkServerTrusted(chain, authType, sslEngine);
verifySubjectAltNameInChain(chain, sniMatchers);
}
@Override
@SuppressWarnings("deprecation") // gRFC A29 predates match_typed_subject_alt_names
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
chooseDelegate(chain).checkServerTrusted(chain, authType);
verifySubjectAltNameInChain(chain, certContext != null
? certContext.getMatchSubjectAltNamesList() : new ArrayList<>());
}
private List<StringMatcher> getAutoSniSanMatchers(SSLParameters sslParams) {
List<StringMatcher> sniNamesToMatch = new ArrayList<>();
if (CertificateUtils.isXdsSniEnabled && autoSniSanValidation) {
List<SNIServerName> serverNames = sslParams.getServerNames();
if (serverNames != null) {
for (SNIServerName serverName : serverNames) {
if (serverName instanceof SNIHostName) {
SNIHostName sniHostName = (SNIHostName) serverName;
String hostName = sniHostName.getAsciiName();
sniNamesToMatch.add(StringMatcher.newBuilder().setExact(hostName).build());
}
}
}
}
return sniNamesToMatch;
}
private X509ExtendedTrustManager chooseDelegate(X509Certificate[] chain)
throws CertificateException {
if (spiffeTrustMapDelegates != null) {
Optional<SpiffeUtil.SpiffeId> spiffeId = SpiffeUtil.extractSpiffeId(chain);
if (!spiffeId.isPresent()) {
throw new CertificateException("Failed to extract SPIFFE ID from peer leaf certificate");
}
String trustDomain = spiffeId.get().getTrustDomain();
if (!spiffeTrustMapDelegates.containsKey(trustDomain)) {
throw new CertificateException(String.format("Spiffe Trust Map doesn't contain trust"
+ " domain '%s' from peer leaf certificate", trustDomain));
}
return spiffeTrustMapDelegates.get(trustDomain);
} else {
return delegate;
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
if (spiffeTrustMapDelegates != null) {
Set<X509Certificate> result = new HashSet<>();
for (X509ExtendedTrustManager tm: spiffeTrustMapDelegates.values()) {
result.addAll(Arrays.asList(tm.getAcceptedIssuers()));
}
return result.toArray(new X509Certificate[0]);
}
return delegate.getAcceptedIssuers();
}
private static boolean verifyDnsNameWildcard(
String altNameFromCert, String sanToVerify, boolean ignoreCase) {
String[] splitPattern = splitAtFirstDelimiter(ignoreCase
? sanToVerify.toLowerCase(Locale.ROOT) : sanToVerify);
String[] splitDnsName = splitAtFirstDelimiter(ignoreCase
? altNameFromCert.toLowerCase(Locale.ROOT) : altNameFromCert);
if (splitPattern == null || splitDnsName == null) {
return false;
}
if (splitDnsName[0].startsWith("xn--")) {
return false;
}
if (splitPattern[0].contains("*")
&& !splitPattern[1].contains("*")
&& !splitPattern[0].startsWith("xn--")) {
return splitDnsName[1].equals(splitPattern[1])
&& labelWildcardMatch(splitDnsName[0], splitPattern[0]);
}
return false;
}
private static boolean labelWildcardMatch(String dnsLabel, String pattern) {
final char glob = '*';
// Check the special case of a single * pattern, as it's common.
if (pattern.equals("*")) {
return !dnsLabel.isEmpty();
}
int globIndex = pattern.indexOf(glob);
if (pattern.indexOf(glob, globIndex + 1) == -1) {
return dnsLabel.length() >= pattern.length() - 1
&& dnsLabel.startsWith(pattern.substring(0, globIndex))
&& dnsLabel.endsWith(pattern.substring(globIndex + 1));
}
return false;
}
@Nullable
private static String[] splitAtFirstDelimiter(String s) {
int index = s.indexOf('.');
if (index == -1) {
return null;
}
return new String[]{s.substring(0, index), s.substring(index + 1)};
}
}
| XdsX509TrustManager |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/executor/loader/javassist/JavassistProxyFactory.java | {
"start": 1742,
"end": 4220
} | class ____ implements org.apache.ibatis.executor.loader.ProxyFactory {
private static final String FINALIZE_METHOD = "finalize";
private static final String WRITE_REPLACE_METHOD = "writeReplace";
public JavassistProxyFactory() {
try {
Resources.classForName("javassist.util.proxy.ProxyFactory");
} catch (Throwable e) {
throw new IllegalStateException(
"Cannot enable lazy loading because Javassist is not available. Add Javassist to your classpath.", e);
}
}
@Override
public Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration,
ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return EnhancedResultObjectProxyImpl.createProxy(target, lazyLoader, configuration, objectFactory,
constructorArgTypes, constructorArgs);
}
public Object createDeserializationProxy(Object target, Map<String, ResultLoaderMap.LoadPair> unloadedProperties,
ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return EnhancedDeserializationProxyImpl.createProxy(target, unloadedProperties, objectFactory, constructorArgTypes,
constructorArgs);
}
static Object createStaticProxy(Class<?> type, MethodHandler callback, List<Class<?>> constructorArgTypes,
List<Object> constructorArgs) {
ProxyFactory enhancer = new ProxyFactory();
enhancer.setSuperclass(type);
try {
type.getDeclaredMethod(WRITE_REPLACE_METHOD);
// ObjectOutputStream will call writeReplace of objects returned by writeReplace
if (LogHolder.log.isDebugEnabled()) {
LogHolder.log.debug(WRITE_REPLACE_METHOD + " method was found on bean " + type + ", make sure it returns this");
}
} catch (NoSuchMethodException e) {
enhancer.setInterfaces(new Class[] { WriteReplaceInterface.class });
} catch (SecurityException e) {
// nothing to do here
}
Object enhanced;
Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]);
Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]);
try {
enhanced = enhancer.create(typesArray, valuesArray);
} catch (Exception e) {
throw new ExecutorException("Error creating lazy proxy. Cause: " + e, e);
}
((Proxy) enhanced).setHandler(callback);
return enhanced;
}
private static | JavassistProxyFactory |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/exc/DeferredBindingException.java | {
"start": 1768,
"end": 3828
} | class ____ extends DatabindException {
private static final long serialVersionUID = 1L;
private final List<CollectedProblem> problems;
private final boolean limitReached;
public DeferredBindingException(JsonParser p,
List<CollectedProblem> problems,
boolean limitReached) {
super(p, formatMessage(problems, limitReached));
this.problems = Collections.unmodifiableList(problems);
this.limitReached = limitReached;
}
/**
* @return Unmodifiable list of all collected problems
*/
public List<CollectedProblem> getProblems() {
return problems;
}
/**
* @return Number of problems collected
*/
public int getProblemCount() {
return problems.size();
}
/**
* @return true if error collection stopped due to reaching the configured limit
*/
public boolean isLimitReached() {
return limitReached;
}
private static String formatMessage(List<CollectedProblem> problems, boolean limitReached) {
int count = problems.size();
if (count == 1) {
return "1 deserialization problem: " + problems.get(0).getMessage();
}
String limitNote = limitReached ? " (limit reached; more errors may exist)" : "";
return String.format(
"%d deserialization problems%s (showing first 5):%n%s",
count,
limitNote,
formatProblems(problems)
);
}
private static String formatProblems(List<CollectedProblem> problems) {
StringBuilder sb = new StringBuilder();
int limit = Math.min(5, problems.size());
for (int i = 0; i < limit; i++) {
CollectedProblem p = problems.get(i);
sb.append(String.format(" [%d] at %s: %s%n",
i + 1, p.getPath(), p.getMessage()));
}
if (problems.size() > 5) {
sb.append(String.format(" ... and %d more", problems.size() - 5));
}
return sb.toString();
}
}
| DeferredBindingException |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderWhenDoneByIndexTest.java | {
"start": 1226,
"end": 2274
} | class ____ extends ContextTestSupport {
@Test
public void testDoneByIndex() {
final AtomicInteger counter = new AtomicInteger();
getMockEndpoint("mock:split").whenAnyExchangeReceived(new Processor() {
@Override
public void process(Exchange exchange) {
counter.incrementAndGet();
}
});
// notify when the 1st exchange is done (by index)
NotifyBuilder notify = new NotifyBuilder(context).whenDoneByIndex(0).create();
assertFalse(notify.matches());
template.sendBody("seda:foo", "A,B,C");
assertTrue(notify.matchesWaitTime());
assertEquals(3, counter.get());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:foo").routeId("foo").delay(500).split(body().tokenize(",")).to("mock:split").end().to("mock:foo");
}
};
}
}
| NotifyBuilderWhenDoneByIndexTest |
java | google__auto | value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java | {
"start": 23806,
"end": 24132
} | class ____ there is
* one. In that case, it should check if {@link BuilderContext#toBuilderMethods()} is empty. If
* not, the {@code Builder} subclass should include a "copy constructor", like this:
*
* <pre>{@code
* ...
* <finalOrAbstract> class <className> extends <classToExtend> {
* ...
* static | if |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java | {
"start": 2183,
"end": 2252
} | class ____ extends TypeReference<List<Object>> {
}
}
| ListTypeReference |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ApplicationClientProtocol.java | {
"start": 7281,
"end": 9531
} | interface ____ by clients to submit a new application to the
* <code>ResourceManager.</code></p>
*
* <p>The client is required to provide details such as queue,
* {@link Resource} required to run the <code>ApplicationMaster</code>,
* the equivalent of {@link ContainerLaunchContext} for launching
* the <code>ApplicationMaster</code> etc. via the
* {@link SubmitApplicationRequest}.</p>
*
* <p>Currently the <code>ResourceManager</code> sends an immediate (empty)
* {@link SubmitApplicationResponse} on accepting the submission and throws
* an exception if it rejects the submission. However, this call needs to be
* followed by {@link #getApplicationReport(GetApplicationReportRequest)}
* to make sure that the application gets properly submitted - obtaining a
* {@link SubmitApplicationResponse} from ResourceManager doesn't guarantee
* that RM 'remembers' this application beyond failover or restart. If RM
* failover or RM restart happens before ResourceManager saves the
* application's state successfully, the subsequent
* {@link #getApplicationReport(GetApplicationReportRequest)} will throw
* a {@link ApplicationNotFoundException}. The Clients need to re-submit
* the application with the same {@link ApplicationSubmissionContext} when
* it encounters the {@link ApplicationNotFoundException} on the
* {@link #getApplicationReport(GetApplicationReportRequest)} call.</p>
*
* <p>During the submission process, it checks whether the application
* already exists. If the application exists, it will simply return
* SubmitApplicationResponse</p>
*
* <p> In secure mode,the <code>ResourceManager</code> verifies access to
* queues etc. before accepting the application submission.</p>
*
* @param request request to submit a new application
* @return (empty) response on accepting the submission
* @throws YarnException exceptions from yarn servers.
* @throws IOException io error occur.
* @see #getNewApplication(GetNewApplicationRequest)
*/
@Public
@Stable
@Idempotent
public SubmitApplicationResponse submitApplication(
SubmitApplicationRequest request)
throws YarnException, IOException;
/**
* <p>The | used |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/PasswordManagementConfigurerTests.java | {
"start": 4021,
"end": 4378
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
return http
.passwordManagement((passwordManagement) -> passwordManagement
.changePasswordPage("/custom-change-password-page")
)
.build();
// @formatter:on
}
}
}
| PasswordManagementWithCustomChangePasswordPageConfig |
java | spring-projects__spring-boot | documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/scheduling/ScheduledTasksEndpointDocumentationTests.java | {
"start": 6242,
"end": 6424
} | class ____ implements Runnable {
@Override
public void run() {
throw new IllegalStateException("Failed while running custom task");
}
}
static | CustomTriggeredRunnable |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/CleanerUtil.java | {
"start": 7378,
"end": 7546
} | interface ____ cleanup ByteBuffers.
* CleanerUtil implements this to allow unmapping of bytebuffers
* with private Java APIs.
*/
@FunctionalInterface
public | to |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/admin/UserScramCredentialAlteration.java | {
"start": 1108,
"end": 1481
} | class ____ {
protected final String user;
/**
*
* @param user the mandatory user
*/
protected UserScramCredentialAlteration(String user) {
this.user = Objects.requireNonNull(user);
}
/**
*
* @return the always non-null user
*/
public String user() {
return this.user;
}
}
| UserScramCredentialAlteration |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurityExpressionTests.java | {
"start": 8363,
"end": 8424
} | class ____ implements MethodResolver {
static | MyMethodResolver |
java | elastic__elasticsearch | x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/JdbcColumnInfo.java | {
"start": 393,
"end": 3052
} | class ____ {
public final String catalog;
public final String schema;
public final String table;
public final String label;
public final String name;
public final int displaySize;
public final EsType type;
JdbcColumnInfo(String name, EsType type, String table, String catalog, String schema, String label, int displaySize) {
if (name == null) {
throw new IllegalArgumentException("[name] must not be null");
}
if (type == null) {
throw new IllegalArgumentException("[type] must not be null");
}
if (table == null) {
throw new IllegalArgumentException("[table] must not be null");
}
if (catalog == null) {
throw new IllegalArgumentException("[catalog] must not be null");
}
if (schema == null) {
throw new IllegalArgumentException("[schema] must not be null");
}
if (label == null) {
throw new IllegalArgumentException("[label] must not be null");
}
this.name = name;
this.type = type;
this.table = table;
this.catalog = catalog;
this.schema = schema;
this.label = label;
this.displaySize = displaySize;
}
int displaySize() {
// 0 - means unknown
return displaySize;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (false == EMPTY.equals(table)) {
b.append(table).append('.');
}
b.append(name).append("<type=[").append(type).append(']');
if (false == EMPTY.equals(catalog)) {
b.append(" catalog=[").append(catalog).append(']');
}
if (false == EMPTY.equals(schema)) {
b.append(" schema=[").append(schema).append(']');
}
if (false == EMPTY.equals(label)) {
b.append(" label=[").append(label).append(']');
}
return b.append('>').toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
JdbcColumnInfo other = (JdbcColumnInfo) obj;
return name.equals(other.name)
&& type.equals(other.type)
&& table.equals(other.table)
&& catalog.equals(other.catalog)
&& schema.equals(other.schema)
&& label.equals(other.label)
&& displaySize == other.displaySize;
}
@Override
public int hashCode() {
return Objects.hash(name, type, table, catalog, schema, label, displaySize);
}
}
| JdbcColumnInfo |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanForBrokenFactoryBeanIntegrationTests.java | {
"start": 1784,
"end": 1895
} | class ____ {
@Bean
TestFactoryBean testFactoryBean() {
return new TestFactoryBean();
}
}
static | Config |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java | {
"start": 1486,
"end": 2918
} | class ____ {
private Protocol protocol =
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
private ProxyFactory proxy =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
@AfterEach
public void after() {
ProtocolUtils.closeAll();
}
@Test
void testRpcFilter() throws Exception {
DemoService service = new DemoServiceImpl();
int port = NetUtils.getAvailablePort();
URL url = URL.valueOf("dubbo://127.0.0.1:" + port
+ "/org.apache.dubbo.rpc.protocol.dubbo.support.DemoService?service.filter=echo");
ApplicationModel.defaultModel()
.getDefaultModule()
.getServiceRepository()
.registerService(DemoService.class);
url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule());
protocol.export(proxy.getInvoker(service, DemoService.class, url));
service = proxy.getProxy(protocol.refer(DemoService.class, url));
Assertions.assertEquals("123", service.echo("123"));
// cast to EchoService
EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, url));
Assertions.assertEquals(echo.$echo("test"), "test");
Assertions.assertEquals(echo.$echo("abcdefg"), "abcdefg");
Assertions.assertEquals(echo.$echo(1234), 1234);
}
}
| RpcFilterTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/LocalTimeOffset.java | {
"start": 1947,
"end": 5392
} | class ____ {
/**
* Lookup offsets for a provided zone. This <strong>can</strong> fail if
* there are many transitions and the provided lookup would be very large.
*
* @return a {@linkplain Lookup} or {@code null} if none could be built
*/
public static Lookup lookup(ZoneId zone, long minUtcMillis, long maxUtcMillis) {
if (minUtcMillis > maxUtcMillis) {
throw new IllegalArgumentException("[" + minUtcMillis + "] must be <= [" + maxUtcMillis + "]");
}
ZoneRules rules = zone.getRules();
{
LocalTimeOffset fixed = checkForFixedZone(zone, rules);
if (fixed != null) {
return new FixedLookup(zone, fixed);
}
}
List<ZoneOffsetTransition> transitions = collectTransitions(zone, rules, minUtcMillis, maxUtcMillis);
if (transitions == null) {
// The range is too large for us to pre-build all the offsets
return null;
}
if (transitions.size() < 3) {
/*
* Its actually quite common that there are *very* few transitions.
* This case where there are only two transitions covers an entire
* year of data! In any case, it is slightly faster to do the
* "simpler" thing and compare the start times instead of perform
* a binary search when there are so few offsets to look at.
*/
return new LinkedListLookup(zone, minUtcMillis, maxUtcMillis, transitions);
}
return new TransitionArrayLookup(zone, minUtcMillis, maxUtcMillis, transitions);
}
/**
* Lookup offsets without any known min or max time. This will generally
* fail if the provided zone isn't fixed.
*
* @return a lookup function of {@code null} if none could be built
*/
public static LocalTimeOffset fixedOffset(ZoneId zone) {
return checkForFixedZone(zone, zone.getRules());
}
private final long millis;
private LocalTimeOffset(long millis) {
this.millis = millis;
}
/**
* Convert a time in utc into a the local time at this offset.
*/
public final long utcToLocalTime(long utcMillis) {
return utcMillis + millis;
}
/**
* Convert a time in local millis to utc millis using <strong>this</strong> offset.
* <p>
* <strong>Important:</strong> Callers will rarely want to <strong>force</strong>
* using this offset and are instead instead interested in picking an appropriate
* offset for some local time that they have rounded down. In that case use
* {@link #localToUtc(long, Strategy)}.
*/
public final long localToUtcInThisOffset(long localMillis) {
return localMillis - millis;
}
/**
* Convert a local time that occurs during this offset or a previous
* offset to utc, providing a strategy for how to resolve "funny" cases.
* You can use this if you've converted from utc to local, rounded down,
* and then want to convert back to utc and you need fine control over
* how to handle the "funny" edges.
* <p>
* This will not help you if you must convert a local time that you've
* rounded <strong>up</strong>. For that you are on your own. May God
* have mercy on your soul.
*/
public abstract long localToUtc(long localMillis, Strategy strat);
public | LocalTimeOffset |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/typeutils/PythonTypeUtils.java | {
"start": 24158,
"end": 24847
} | class ____ extends DataConverter<Float, Float, Double> {
public static final FloatDataConverter INSTANCE = new FloatDataConverter();
private FloatDataConverter() {
super(DataFormatConverters.FloatConverter.INSTANCE);
}
@Override
Float toInternalImpl(Double value) {
return value.floatValue();
}
@Override
Double toExternalImpl(Float value) {
return value.doubleValue();
}
}
/**
* Python datetime.time will be converted to Time in PemJa, so we need TimeDataConverter to
* convert Java Double to internal Integer.
*/
public static final | FloatDataConverter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/dialect/functional/MariaDBExtractSequenceMetadataTest.java | {
"start": 1000,
"end": 3215
} | class ____ {
private static String primaryDbName;
private static String primarySequenceName = "seq_HHH13373";
private static String secondaryDbName = "secondary_db_HHH13373";
private static String secondarySequenceName = "secondary_seq_HHH13373";
@BeforeAll
public static void setUpDBs() throws Exception {
try (Connection conn = getConnection()) {
try (Statement stmt = conn.createStatement()) {
try (ResultSet resultSet = stmt.executeQuery( "SELECT DATABASE()" )) {
assert resultSet.next();
primaryDbName = resultSet.getString( 1 );
}
stmt.execute( "CREATE DATABASE IF NOT EXISTS " + secondaryDbName );
stmt.execute( "USE " + secondaryDbName );
stmt.execute( "CREATE SEQUENCE IF NOT EXISTS " + secondarySequenceName );
stmt.execute( "USE " + primaryDbName );
stmt.execute( "DROP SEQUENCE IF EXISTS " + secondarySequenceName );
stmt.execute( "CREATE SEQUENCE IF NOT EXISTS " + primarySequenceName );
}
}
}
@Test
@JiraKey(value = "HHH-13373")
public void testHibernateLaunchedSuccessfully() {
JdbcEnvironment jdbcEnvironment = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() )
.getService( JdbcEnvironment.class );
Assertions.assertFalse( jdbcEnvironment.getExtractedDatabaseMetaData().getSequenceInformationList().isEmpty() );
}
@AfterAll
public static void tearDownDBs() throws SQLException {
try (Connection conn = getConnection()) {
try (Statement stmt = conn.createStatement()) {
stmt.execute( "DROP DATABASE IF EXISTS " + secondaryDbName );
}
catch (Exception e) {
// Ignore
}
try (Statement stmt = conn.createStatement()) {
stmt.execute( "DROP SEQUENCE IF EXISTS " + primarySequenceName );
}
catch (Exception e) {
// Ignore
}
}
}
private static Connection getConnection() throws SQLException {
String url = resolveUrl( Environment.getProperties().getProperty( Environment.URL ) );
String user = resolveUsername( Environment.getProperties().getProperty( Environment.USER ) );
String password = Environment.getProperties().getProperty( Environment.PASS );
return DriverManager.getConnection( url, user, password );
}
}
| MariaDBExtractSequenceMetadataTest |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java | {
"start": 59785,
"end": 59923
} | class ____ {
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(NestedProperties.class)
static | BasicConfiguration |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointStatusMessageParameters.java | {
"start": 1350,
"end": 1949
} | class ____ extends MessageParameters {
public final JobIDPathParameter jobIdPathParameter = new JobIDPathParameter();
public final TriggerIdPathParameter triggerIdPathParameter = new TriggerIdPathParameter();
@Override
public Collection<MessagePathParameter<?>> getPathParameters() {
return Collections.unmodifiableCollection(
Arrays.asList(jobIdPathParameter, triggerIdPathParameter));
}
@Override
public Collection<MessageQueryParameter<?>> getQueryParameters() {
return Collections.emptyList();
}
}
| CheckpointStatusMessageParameters |
java | apache__camel | components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/CxfOneWayRouteTest.java | {
"start": 1972,
"end": 4044
} | class ____ extends CamelSpringTestSupport {
private static final QName SERVICE_NAME = new QName("http://apache.org/hello_world_soap_http", "SOAPService");
private static final QName PORT_NAME = new QName("http://apache.org/hello_world_soap_http", "SoapPort");
private static final String ROUTER_ADDRESS = "http://localhost:" + CXFTestSupport.getPort1() + "/CxfOneWayRouteTest/router";
private static Exception bindingException;
private static boolean bindingDone;
private static boolean onCompeletedCalled;
@BeforeEach
public void setup() {
bindingException = null;
bindingDone = false;
onCompeletedCalled = false;
}
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
// we can put the http conduit configuration here
return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/CxfOneWayRouteBeans.xml");
}
protected Greeter getCXFClient() throws Exception {
Service service = Service.create(SERVICE_NAME);
service.addPort(PORT_NAME, "http://schemas.xmlsoap.org/soap/", ROUTER_ADDRESS);
Greeter greeter = service.getPort(PORT_NAME, Greeter.class);
return greeter;
}
@Test
public void testInvokingOneWayServiceFromCXFClient() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedFileExists("target/camel-file/cxf-oneway-route");
Greeter client = getCXFClient();
client.greetMeOneWay("lemac");
// may need to wait until the oneway call completes
long waitUntil = System.nanoTime() + Duration.ofMillis(10000).toMillis();
while (!bindingDone && System.nanoTime() < waitUntil) {
Thread.sleep(1000);
}
MockEndpoint.assertIsSatisfied(context);
assertTrue(onCompeletedCalled, "UnitOfWork done should be called");
assertNull(bindingException, "exception occurred: " + bindingException);
}
public static | CxfOneWayRouteTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/range/RangeAggregator.java | {
"start": 29852,
"end": 33218
} | class ____ extends NumericRangeAggregator {
Overlap(
String name,
AggregatorFactories factories,
Numeric valuesSource,
DocValueFormat format,
Factory<?, ?> rangeFactory,
Range[] ranges,
double averageDocsPerRange,
boolean keyed,
AggregationContext context,
Aggregator parent,
CardinalityUpperBound cardinality,
Map<String, Object> metadata
) throws IOException {
super(
name,
factories,
valuesSource,
format,
rangeFactory,
ranges,
averageDocsPerRange,
keyed,
context,
parent,
cardinality,
metadata
);
maxTo = new double[ranges.length];
maxTo[0] = ranges[0].to;
for (int i = 1; i < ranges.length; ++i) {
maxTo[i] = Math.max(ranges[i].to, maxTo[i - 1]);
}
if (parent == null) {
grow(ranges.length);
this.collector = this::collectExistingBucket;
} else {
this.collector = this::collectBucket;
}
}
private final double[] maxTo;
private final BucketCollector collector;
@Override
protected int collect(LeafBucketCollector sub, int doc, double value, long owningBucketOrdinal, int lowBound) throws IOException {
int lo = lowBound, hi = ranges.length - 1; // all candidates are between these indexes
int mid = (lo + hi) >>> 1;
while (lo <= hi) {
if (value < ranges[mid].from) {
hi = mid - 1;
} else if (value >= maxTo[mid]) {
lo = mid + 1;
} else {
break;
}
mid = (lo + hi) >>> 1;
}
if (lo > hi) return lo; // no potential candidate
// binary search the lower bound
int startLo = lo, startHi = mid;
while (startLo <= startHi) {
final int startMid = (startLo + startHi) >>> 1;
if (value >= maxTo[startMid]) {
startLo = startMid + 1;
} else {
startHi = startMid - 1;
}
}
// binary search the upper bound
int endLo = mid, endHi = hi;
while (endLo <= endHi) {
final int endMid = (endLo + endHi) >>> 1;
if (value < ranges[endMid].from) {
endHi = endMid - 1;
} else {
endLo = endMid + 1;
}
}
assert startLo == lowBound || value >= maxTo[startLo - 1];
assert endHi == ranges.length - 1 || value < ranges[endHi + 1].from;
for (int i = startLo; i <= endHi; ++i) {
if (ranges[i].matches(value)) {
collector.accept(sub, doc, subBucketOrdinal(owningBucketOrdinal, i));
}
}
// The next value must fall in the next bucket to be collected.
return endHi + 1;
}
}
static | Overlap |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/hive/ast/HiveInsertStatement.java | {
"start": 543,
"end": 2252
} | class ____ extends SQLInsertStatement implements SQLStatement {
private boolean ifNotExists;
public HiveInsertStatement() {
dbType = DbType.hive;
partitions = new ArrayList<SQLAssignItem>();
}
public HiveInsertStatement clone() {
HiveInsertStatement x = new HiveInsertStatement();
super.cloneTo(x);
return x;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor instanceof OdpsASTVisitor) {
accept0((OdpsASTVisitor) visitor);
} else if (visitor instanceof HiveASTVisitor) {
accept0((HiveASTVisitor) visitor);
} else {
super.accept0(visitor);
}
}
protected void accept0(HiveASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, with);
acceptChild(visitor, tableSource);
acceptChild(visitor, partitions);
acceptChild(visitor, valuesList);
acceptChild(visitor, query);
}
visitor.endVisit(this);
}
protected void accept0(OdpsASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, with);
acceptChild(visitor, tableSource);
acceptChild(visitor, partitions);
acceptChild(visitor, valuesList);
acceptChild(visitor, query);
}
visitor.endVisit(this);
}
@Override
public List<SQLCommentHint> getHeadHintsDirect() {
return null;
}
public boolean isIfNotExists() {
return ifNotExists;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
}
| HiveInsertStatement |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java | {
"start": 24855,
"end": 26085
} | class ____ extends SortingNumericLongValues implements ScorerAware {
private final SortedNumericLongValues longValues;
private final AggregationScript script;
LongValues(SortedNumericLongValues values, AggregationScript script) {
this.longValues = values;
this.script = script;
}
@Override
public void setScorer(Scorable scorer) {
script.setScorer(scorer);
}
@Override
public boolean advanceExact(int target) throws IOException {
if (longValues.advanceExact(target)) {
resize(longValues.docValueCount());
script.setDocument(target);
for (int i = 0; i < docValueCount(); ++i) {
script.setNextAggregationValue(longValues.nextValue());
values[i] = script.runAsLong();
}
sort();
return true;
}
return false;
}
}
static | LongValues |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/InvocationInfo.java | {
"start": 1413,
"end": 3574
} | class ____) that we are processing.
*
* @author andrewrice@google.com (Andrew Rice)
*/
record InvocationInfo(
Tree tree,
MethodSymbol symbol,
ImmutableList<Tree> actualParameters,
ImmutableList<VarSymbol> formalParameters,
VisitorState state) {
static InvocationInfo createFromMethodInvocation(
MethodInvocationTree tree, MethodSymbol symbol, VisitorState state) {
return new InvocationInfo(
tree,
symbol,
ImmutableList.copyOf(tree.getArguments()),
getFormalParametersWithoutVarArgs(symbol),
state);
}
static InvocationInfo createFromNewClass(
NewClassTree tree, MethodSymbol symbol, VisitorState state) {
return new InvocationInfo(
tree,
symbol,
ImmutableList.copyOf(tree.getArguments()),
getFormalParametersWithoutVarArgs(symbol),
state);
}
static @Nullable InvocationInfo createFromDeconstructionPattern(
DeconstructionPatternTree tree, VisitorState state) {
var symbol = getSymbol(tree.getDeconstructor());
if (!(symbol instanceof ClassSymbol cs)) {
return null;
}
var constructor = canonicalConstructor(cs, state);
ImmutableList.Builder<Tree> actuals = ImmutableList.builder();
ImmutableList.Builder<VarSymbol> formals = ImmutableList.builder();
for (int i = 0; i < constructor.getParameters().size(); ++i) {
// Skip over anything that isn't binding. There might be nested patterns here, or "_"s.
if (tree.getNestedPatterns().get(i) instanceof BindingPatternTree) {
actuals.add(((BindingPatternTree) tree.getNestedPatterns().get(i)).getVariable());
formals.add(constructor.getParameters().get(i));
}
}
return new InvocationInfo(tree, constructor, actuals.build(), formals.build(), state);
}
private static ImmutableList<VarSymbol> getFormalParametersWithoutVarArgs(
MethodSymbol invokedMethodSymbol) {
List<VarSymbol> formalParameters = invokedMethodSymbol.getParameters();
/* javac can get argument names from debugging symbols if they are not available from
other sources. When it does this for an inner | construction |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/valuehandlingmode/inline/ExpressionsTest.java | {
"start": 1893,
"end": 3083
} | enum ____ {LAND_LINE, CELL, FAX, WORK, HOME}
private String id;
private String area;
private String number;
private Address address;
private Set<Phone.Type> types;
public Phone() {
}
public Phone(String v1, String v2, String v3) {
id = v1;
area = v2;
number = v3;
}
public Phone(String v1, String v2, String v3, Address v4) {
id = v1;
area = v2;
number = v3;
address = v4;
}
@Id
@Column(name = "ID")
public String getId() {
return id;
}
public void setId(String v) {
id = v;
}
@Column(name = "AREA")
public String getArea() {
return area;
}
public void setArea(String v) {
area = v;
}
@Column(name = "PHONE_NUMBER")
public String getNumber() {
return number;
}
public void setNumber(String v) {
number = v;
}
@ManyToOne
@JoinColumn(name = "FK_FOR_ADDRESS")
public Address getAddress() {
return address;
}
public void setAddress(Address a) {
address = a;
}
@ElementCollection
public Set<Phone.Type> getTypes() {
return types;
}
public void setTypes(Set<Phone.Type> types) {
this.types = types;
}
}
@Entity
@Table(name = "ADDRESS")
public static | Type |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/sym/CharsToNameCanonicalizer.java | {
"start": 31249,
"end": 32173
} | class ____
{
final int size;
final int longestCollisionList;
final String[] symbols;
final Bucket[] buckets;
public TableInfo(int size, int longestCollisionList,
String[] symbols, Bucket[] buckets)
{
this.size = size;
this.longestCollisionList = longestCollisionList;
this.symbols = symbols;
this.buckets = buckets;
}
public TableInfo(CharsToNameCanonicalizer src)
{
this.size = src._size;
this.longestCollisionList = src._longestCollisionList;
this.symbols = src._symbols;
this.buckets = src._buckets;
}
public static TableInfo createInitial(int sz) {
return new TableInfo(0,
0, // longestCollisionList
new String[sz], new Bucket[sz >> 1]);
}
}
}
| TableInfo |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/SetGlobalVariableTest.java | {
"start": 1246,
"end": 2680
} | class ____ extends ContextTestSupport {
private MockEndpoint end;
private final String variableName = "foo";
private final String expectedVariableValue = "bar";
@Test
public void testSetExchangeVariableMidRoute() throws Exception {
assertNull(context.getVariable(variableName));
end.expectedMessageCount(1);
template.sendBody("direct:start", "<blah/>");
// make sure we got the message
assertMockEndpointsSatisfied();
// lets get the variable value
List<Exchange> exchanges = end.getExchanges();
Exchange exchange = exchanges.get(0);
String actualVariableValue = exchange.getVariable(variableName, String.class);
// should be stored on global so null
assertNull(actualVariableValue);
// should be stored as global variable
assertEquals(expectedVariableValue, context.getVariable(variableName));
}
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
end = getMockEndpoint("mock:end");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// stored as global variable
from("direct:start").setVariable("global:" + variableName).constant(expectedVariableValue).to("mock:end");
}
};
}
}
| SetGlobalVariableTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.