language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/standard/SpelCompilerTests.java | {
"start": 4552,
"end": 4634
} | class ____ {
public Integer getValue() {
return 111;
}
}
public static | Bean2 |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/LogManager.java | {
"start": 8289,
"end": 9464
} | class ____ the container's classpath then a different LoggerContext may
* be returned. If true then only a single LoggerContext will be returned.
* @param configLocation The URI for the configuration to use.
* @return a LoggerContext.
*/
public static LoggerContext getContext(
final ClassLoader loader, final boolean currentContext, final URI configLocation) {
try {
return factory.getContext(FQCN, loader, null, currentContext, configLocation, null);
} catch (final IllegalStateException ex) {
LOGGER.warn("{} Using SimpleLogger", ex.getMessage());
return SimpleLoggerContextFactory.INSTANCE.getContext(
FQCN, loader, null, currentContext, configLocation, null);
}
}
/**
* Returns a LoggerContext.
*
* @param loader The ClassLoader for the context. If null the context will attempt to determine the appropriate
* ClassLoader.
* @param currentContext if false the LoggerContext appropriate for the caller of this method is returned. For
* example, in a web application if the caller is a | in |
java | apache__maven | compat/maven-model/src/test/java/org/apache/maven/model/v4/ModelXmlTest.java | {
"start": 1374,
"end": 4068
} | class ____ {
@Test
void testXmlRoundtripWithProperties() throws Exception {
Map<String, String> props = new LinkedHashMap<>();
props.put("javax.version", "3.1.0");
props.put("mockito.version", "1.10.19");
props.put("hamcret.version", "2.1");
props.put("lombok.version", "1.18.6");
props.put("junit.version", "4.12");
Model model = Model.newBuilder(true).properties(props).build();
String xml = toXml(model);
for (int i = 0; i < 10; i++) {
String newStr = toXml(fromXml(xml));
assertEquals(newStr, xml);
}
}
@Test
void testNamespaceInXmlNode() throws XMLStreamException {
String xml = "<project xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xmlns=\"http://maven.apache.org/POM/4.0.0\"\n"
+ " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/POM/4.0.0\">\n"
+ " <build>\n"
+ " <plugins>\n"
+ " <plugin>\n"
+ " <m:configuration xmlns:m=\"http://maven.apache.org/POM/4.0.0\" xmlns=\"http://fabric8.io/fabric8-maven-plugin\">\n"
+ " <myConfig>foo</myConfig>\n"
+ " </m:configuration>\n"
+ " </plugin>\n"
+ " </plugins>\n"
+ " </build>\n"
+ "</project>";
Model model = fromXml(xml);
Plugin plugin = model.getBuild().getPlugins().get(0);
XmlNode node = plugin.getConfiguration();
assertNotNull(node);
assertEquals("http://maven.apache.org/POM/4.0.0", node.namespaceUri());
assertEquals("m", node.prefix());
assertEquals("configuration", node.name());
assertEquals(1, node.children().size());
XmlNode myConfig = node.children().get(0);
assertEquals("http://fabric8.io/fabric8-maven-plugin", myConfig.namespaceUri());
assertEquals("", myConfig.prefix());
assertEquals("myConfig", myConfig.name());
String config = node.toString();
assertFalse(config.isEmpty(), "Expected collection to not be empty but was empty");
}
String toXml(Model model) throws IOException, XMLStreamException {
StringWriter sw = new StringWriter();
MavenStaxWriter writer = new MavenStaxWriter();
writer.setAddLocationInformation(false);
writer.write(sw, model);
return sw.toString();
}
Model fromXml(String xml) throws XMLStreamException {
return new MavenStaxReader().read(new StringReader(xml));
}
}
| ModelXmlTest |
java | spring-projects__spring-security | itest/web/src/integration-test/java/org/springframework/security/integration/AbstractWebServerIntegrationTests.java | {
"start": 1157,
"end": 1495
} | class ____ allows the application to be started with a particular Spring
* application context. Subclasses override the <tt>getContextConfigLocations</tt> method
* to return a list of context file names which is passed to the
* <tt>ContextLoaderListener</tt> when starting up the webapp.
*
* @author Luke Taylor
*/
public abstract | which |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/testkit/IntArrays.java | {
"start": 694,
"end": 912
} | class ____ {
private static final int[] EMPTY = {};
public static int[] arrayOf(int... values) {
return values;
}
public static int[] emptyArray() {
return EMPTY;
}
private IntArrays() {}
}
| IntArrays |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 15112,
"end": 15497
} | class ____ {
// BUG: Diagnostic contains:
final Holder<Object> h = null;
}
""")
.doTest();
}
@Test
public void instantiationWithMutableType() {
compilationHelper
.addSourceLines(
"Holder.java",
"""
import com.google.errorprone.annotations.Immutable;
public | Test |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestConfigurationHelper.java | {
"start": 1535,
"end": 1705
} | class ____ extends AbstractHadoopTestBase {
/**
* Simple Enums.
* "i" is included for case tests, as it is special in turkey.
*/
private | TestConfigurationHelper |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/fs/RefCountedFileWithStream.java | {
"start": 1146,
"end": 2770
} | class ____ extends RefCountedFile {
private final OffsetAwareOutputStream stream;
private RefCountedFileWithStream(
final File file, final OutputStream currentOut, final long bytesInCurrentPart) {
super(file);
this.stream = new OffsetAwareOutputStream(currentOut, bytesInCurrentPart);
}
public OffsetAwareOutputStream getStream() {
return stream;
}
public long getLength() {
return stream.getLength();
}
public void write(byte[] b, int off, int len) throws IOException {
requireOpened();
if (len > 0) {
stream.write(b, off, len);
}
}
void flush() throws IOException {
requireOpened();
stream.flush();
}
void closeStream() {
if (!closed) {
IOUtils.closeQuietly(stream);
closed = true;
}
}
private void requireOpened() throws IOException {
if (closed) {
throw new IOException("Stream closed.");
}
}
// ------------------------------ Factory methods for initializing a temporary file
// ------------------------------
public static RefCountedFileWithStream newFile(final File file, final OutputStream currentOut)
throws IOException {
return new RefCountedFileWithStream(file, currentOut, 0L);
}
public static RefCountedFileWithStream restoredFile(
final File file, final OutputStream currentOut, final long bytesInCurrentPart) {
return new RefCountedFileWithStream(file, currentOut, bytesInCurrentPart);
}
}
| RefCountedFileWithStream |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/search/SearchActionListener.java | {
"start": 800,
"end": 1629
} | class ____<T extends SearchPhaseResult> implements ActionListener<T> {
final int requestIndex;
private final SearchShardTarget searchShardTarget;
protected SearchActionListener(SearchShardTarget searchShardTarget, int shardIndex) {
assert shardIndex >= 0 : "shard index must be positive";
this.searchShardTarget = searchShardTarget;
this.requestIndex = shardIndex;
}
@Override
public final void onResponse(T response) {
response.setShardIndex(requestIndex);
setSearchShardTarget(response);
innerOnResponse(response);
}
protected void setSearchShardTarget(T response) { // some impls need to override this
response.setSearchShardTarget(searchShardTarget);
}
protected abstract void innerOnResponse(T response);
}
| SearchActionListener |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/ValidateTransformAction.java | {
"start": 1383,
"end": 3187
} | class ____ extends AcknowledgedRequest<Request> {
private final TransformConfig config;
private final boolean deferValidation;
public Request(TransformConfig config, boolean deferValidation, TimeValue timeout) {
super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT, timeout);
this.config = config;
this.deferValidation = deferValidation;
}
public Request(StreamInput in) throws IOException {
super(in);
this.config = new TransformConfig(in);
this.deferValidation = in.readBoolean();
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
validationException = config.validate(validationException);
validationException = SourceDestValidator.validateRequest(
validationException,
config.getDestination() != null ? config.getDestination().getIndex() : null
);
return validationException;
}
public TransformConfig getConfig() {
return config;
}
public boolean isDeferValidation() {
return deferValidation;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
this.config.writeTo(out);
out.writeBoolean(this.deferValidation);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Request that = (Request) obj;
// the base | Request |
java | spring-projects__spring-security | oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponse.java | {
"start": 3414,
"end": 5791
} | class ____ {
private String redirectUri;
private String state;
private String code;
private String errorCode;
private String errorDescription;
private String errorUri;
private Builder() {
}
/**
* Sets the uri where the response was redirected to.
* @param redirectUri the uri where the response was redirected to
* @return the {@link Builder}
*/
public Builder redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* Sets the state.
* @param state the state
* @return the {@link Builder}
*/
public Builder state(String state) {
this.state = state;
return this;
}
/**
* Sets the authorization code.
* @param code the authorization code
* @return the {@link Builder}
*/
public Builder code(String code) {
this.code = code;
return this;
}
/**
* Sets the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
/**
* Sets the error description.
* @param errorDescription the error description
* @return the {@link Builder}
*/
public Builder errorDescription(String errorDescription) {
this.errorDescription = errorDescription;
return this;
}
/**
* Sets the error uri.
* @param errorUri the error uri
* @return the {@link Builder}
*/
public Builder errorUri(String errorUri) {
this.errorUri = errorUri;
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationResponse}.
* @return a {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse build() {
if (StringUtils.hasText(this.code) && StringUtils.hasText(this.errorCode)) {
throw new IllegalArgumentException("code and errorCode cannot both be set");
}
Assert.hasText(this.redirectUri, "redirectUri cannot be empty");
OAuth2AuthorizationResponse authorizationResponse = new OAuth2AuthorizationResponse();
authorizationResponse.redirectUri = this.redirectUri;
authorizationResponse.state = this.state;
if (StringUtils.hasText(this.code)) {
authorizationResponse.code = this.code;
}
else {
authorizationResponse.error = new OAuth2Error(this.errorCode, this.errorDescription, this.errorUri);
}
return authorizationResponse;
}
}
}
| Builder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/test/java/org/apache/hadoop/yarn/server/timelineservice/collector/TestTimelineCollector.java | {
"start": 2655,
"end": 11603
} | class ____ {
private TimelineEntities generateTestEntities(int groups, int entities) {
TimelineEntities te = new TimelineEntities();
for (int j = 0; j < groups; j++) {
for (int i = 0; i < entities; i++) {
TimelineEntity entity = new TimelineEntity();
String containerId = "container_1000178881110_2002_" + i;
entity.setId(containerId);
String entityType = "TEST_" + j;
entity.setType(entityType);
long cTime = 1425016501000L;
entity.setCreatedTime(cTime);
// add metrics
Set<TimelineMetric> metrics = new HashSet<>();
TimelineMetric m1 = new TimelineMetric();
m1.setId("HDFS_BYTES_WRITE");
m1.setRealtimeAggregationOp(TimelineMetricOperation.SUM);
long ts = System.currentTimeMillis();
m1.addValue(ts - 20000, 100L);
metrics.add(m1);
TimelineMetric m2 = new TimelineMetric();
m2.setId("VCORES_USED");
m2.setRealtimeAggregationOp(TimelineMetricOperation.SUM);
m2.addValue(ts - 20000, 3L);
metrics.add(m2);
// m3 should not show up in the aggregation
TimelineMetric m3 = new TimelineMetric();
m3.setId("UNRELATED_VALUES");
m3.addValue(ts - 20000, 3L);
metrics.add(m3);
TimelineMetric m4 = new TimelineMetric();
m4.setId("TXN_FINISH_TIME");
m4.setRealtimeAggregationOp(TimelineMetricOperation.MAX);
m4.addValue(ts - 20000, i);
metrics.add(m4);
entity.addMetrics(metrics);
te.addEntity(entity);
}
}
return te;
}
@Test
void testAggregation() throws Exception {
// Test aggregation with multiple groups.
int groups = 3;
int n = 50;
TimelineEntities testEntities = generateTestEntities(groups, n);
TimelineEntity resultEntity = TimelineCollector.aggregateEntities(
testEntities, "test_result", "TEST_AGGR", true);
assertThat(resultEntity.getMetrics()).hasSize(groups * 3);
for (int i = 0; i < groups; i++) {
Set<TimelineMetric> metrics = resultEntity.getMetrics();
for (TimelineMetric m : metrics) {
if (m.getId().startsWith("HDFS_BYTES_WRITE")) {
assertEquals(100 * n, m.getSingleDataValue().intValue());
} else if (m.getId().startsWith("VCORES_USED")) {
assertEquals(3 * n, m.getSingleDataValue().intValue());
} else if (m.getId().startsWith("TXN_FINISH_TIME")) {
assertEquals(n - 1, m.getSingleDataValue());
} else {
fail("Unrecognized metric! " + m.getId());
}
}
}
// Test aggregation with a single group.
TimelineEntities testEntities1 = generateTestEntities(1, n);
TimelineEntity resultEntity1 = TimelineCollector.aggregateEntities(
testEntities1, "test_result", "TEST_AGGR", false);
assertThat(resultEntity1.getMetrics()).hasSize(3);
Set<TimelineMetric> metrics = resultEntity1.getMetrics();
for (TimelineMetric m : metrics) {
if (m.getId().equals("HDFS_BYTES_WRITE")) {
assertEquals(100 * n, m.getSingleDataValue().intValue());
} else if (m.getId().equals("VCORES_USED")) {
assertEquals(3 * n, m.getSingleDataValue().intValue());
} else if (m.getId().equals("TXN_FINISH_TIME")) {
assertEquals(n - 1, m.getSingleDataValue());
} else {
fail("Unrecognized metric! " + m.getId());
}
}
}
/**
* Test TimelineCollector's interaction with TimelineWriter upon
* putEntity() calls.
*/
@Test
void testPutEntity() throws IOException {
TimelineWriter writer = mock(TimelineWriter.class);
TimelineHealth timelineHealth = new TimelineHealth(TimelineHealth.
TimelineHealthStatus.RUNNING, "");
when(writer.getHealthStatus()).thenReturn(timelineHealth);
Configuration conf = new Configuration();
conf.setInt(YarnConfiguration.TIMELINE_SERVICE_CLIENT_MAX_RETRIES, 5);
conf.setLong(YarnConfiguration.TIMELINE_SERVICE_CLIENT_RETRY_INTERVAL_MS,
500L);
TimelineCollector collector = new TimelineCollectorForTest(writer);
collector.init(conf);
TimelineEntities entities = generateTestEntities(1, 1);
collector.putEntities(
entities, UserGroupInformation.createRemoteUser("test-user"));
verify(writer, times(1)).write(any(TimelineCollectorContext.class),
any(TimelineEntities.class), any(UserGroupInformation.class));
verify(writer, times(1)).flush();
}
@Test
void testPutEntityWithStorageDown() throws IOException {
TimelineWriter writer = mock(TimelineWriter.class);
TimelineHealth timelineHealth = new TimelineHealth(TimelineHealth.
TimelineHealthStatus.CONNECTION_FAILURE, "");
when(writer.getHealthStatus()).thenReturn(timelineHealth);
Configuration conf = new Configuration();
conf.setInt(YarnConfiguration.TIMELINE_SERVICE_CLIENT_MAX_RETRIES, 5);
conf.setLong(YarnConfiguration.TIMELINE_SERVICE_CLIENT_RETRY_INTERVAL_MS,
500L);
TimelineCollector collector = new TimelineCollectorForTest(writer);
collector.init(conf);
TimelineEntities entities = generateTestEntities(1, 1);
boolean exceptionCaught = false;
try {
collector.putEntities(entities, UserGroupInformation.
createRemoteUser("test-user"));
} catch (Exception e) {
if (e.getMessage().contains("Failed to putEntities")) {
exceptionCaught = true;
}
}
assertTrue(exceptionCaught, "TimelineCollector putEntity failed to " +
"handle storage down");
}
/**
* Test TimelineCollector's interaction with TimelineWriter upon
* putEntityAsync() calls.
*/
@Test
void testPutEntityAsync() throws Exception {
TimelineWriter writer = mock(TimelineWriter.class);
TimelineCollector collector = new TimelineCollectorForTest(writer);
collector.init(new Configuration());
collector.start();
TimelineEntities entities = generateTestEntities(1, 1);
collector.putEntitiesAsync(
entities, UserGroupInformation.createRemoteUser("test-user"));
Thread.sleep(1000);
verify(writer, times(1)).write(any(TimelineCollectorContext.class),
any(TimelineEntities.class), any(UserGroupInformation.class));
verify(writer, never()).flush();
collector.stop();
}
/**
* Test TimelineCollector's discarding entities in case of async writes if
* write is taking too much time.
*/
@Test
void testAsyncEntityDiscard() throws Exception {
TimelineWriter writer = mock(TimelineWriter.class);
when(writer.write(any(), any(), any())).thenAnswer(
new AnswersWithDelay(500, new Returns(new TimelineWriteResponse())));
TimelineCollector collector = new TimelineCollectorForTest(writer);
Configuration config = new Configuration();
config
.setInt(YarnConfiguration.TIMELINE_SERVICE_WRITER_ASYNC_QUEUE_CAPACITY,
3);
collector.init(config);
collector.start();
for (int i = 0; i < 10; ++i) {
TimelineEntities entities = generateTestEntities(i + 1, 1);
collector.putEntitiesAsync(entities,
UserGroupInformation.createRemoteUser("test-user"));
}
Thread.sleep(3000);
verify(writer, times(4))
.write(any(TimelineCollectorContext.class), any(TimelineEntities.class),
any(UserGroupInformation.class));
verify(writer, never()).flush();
collector.stop();
}
/**
* Test TimelineCollector's interaction with TimelineWriter upon
* putDomain() calls.
*/
@Test
void testPutDomain() throws IOException {
TimelineWriter writer = mock(TimelineWriter.class);
TimelineHealth timelineHealth = new TimelineHealth(TimelineHealth.
TimelineHealthStatus.RUNNING, "");
when(writer.getHealthStatus()).thenReturn(timelineHealth);
Configuration conf = new Configuration();
conf.setInt(YarnConfiguration.TIMELINE_SERVICE_CLIENT_MAX_RETRIES, 5);
conf.setLong(YarnConfiguration.TIMELINE_SERVICE_CLIENT_RETRY_INTERVAL_MS,
500L);
TimelineCollector collector = new TimelineCollectorForTest(writer);
collector.init(conf);
TimelineDomain domain =
generateDomain("id", "desc", "owner", "reader1,reader2", "writer", 0L,
1L);
collector.putDomain(domain, UserGroupInformation.createRemoteUser("owner"));
verify(writer, times(1))
.write(any(TimelineCollectorContext.class), any(TimelineDomain.class));
verify(writer, times(1)).flush();
}
private static TimelineDomain generateDomain(String id, String desc,
String owner, String reader, String writer, Long cTime, Long mTime) {
TimelineDomain domain = new TimelineDomain();
domain.setId(id);
domain.setDescription(desc);
domain.setOwner(owner);
domain.setReaders(reader);
domain.setWriters(writer);
domain.setCreatedTime(cTime);
domain.setModifiedTime(mTime);
return domain;
}
private static | TestTimelineCollector |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/collector/TimelineCollectorWebService.java | {
"start": 3892,
"end": 12355
} | class ____ {
private String about;
public AboutInfo() {
}
public AboutInfo(String abt) {
this.about = abt;
}
@XmlElement(name = "About")
public String getAbout() {
return about;
}
public void setAbout(String abt) {
this.about = abt;
}
}
/**
* Return the description of the timeline web services.
*
* @param req Servlet request.
* @param res Servlet response.
* @return description of timeline web service.
*/
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8
/* , MediaType.APPLICATION_XML */})
public AboutInfo about(
@Context HttpServletRequest req,
@Context HttpServletResponse res) {
init(res);
return new AboutInfo("Timeline Collector API");
}
/**
* Accepts writes to the collector, and returns a response. It simply routes
* the request to the app level collector. It expects an application as a
* context.
*
* @param req Servlet request.
* @param res Servlet response.
* @param async flag indicating whether its an async put or not. "true"
* indicates, its an async call. If null, its considered false.
* @param isSubAppEntities subappwrite.
* @param appId Application Id to which the entities to be put belong to. If
* appId is not there or it cannot be parsed, HTTP 400 will be sent back.
* @param entities timeline entities to be put.
* @return a Response with appropriate HTTP status.
*/
@PUT
@Path("/entities")
@Consumes({ MediaType.APPLICATION_JSON /* , MediaType.APPLICATION_XML */})
public Response putEntities(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@QueryParam("async") String async,
@QueryParam("subappwrite") String isSubAppEntities,
@QueryParam("appid") String appId,
TimelineEntities entities) {
init(res);
UserGroupInformation callerUgi = getUser(req);
boolean isAsync = async != null && async.trim().equalsIgnoreCase("true");
if (callerUgi == null) {
String msg = "The owner of the posted timeline entities is not set";
LOG.error(msg);
throw new ForbiddenException(msg);
}
long startTime = Time.monotonicNow();
boolean succeeded = false;
try {
ApplicationId appID = parseApplicationId(appId);
if (appID == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
NodeTimelineCollectorManager collectorManager =
(NodeTimelineCollectorManager) context.getAttribute(
NodeTimelineCollectorManager.COLLECTOR_MANAGER_ATTR_KEY);
TimelineCollector collector = collectorManager.get(appID);
if (collector == null) {
LOG.error("Application: {} is not found", appId);
throw new NotFoundException("Application: "+ appId + " is not found");
}
if (isAsync) {
collector.putEntitiesAsync(processTimelineEntities(entities, appId,
Boolean.valueOf(isSubAppEntities)), callerUgi);
} else {
collector.putEntities(processTimelineEntities(entities, appId,
Boolean.valueOf(isSubAppEntities)), callerUgi);
}
succeeded = true;
return Response.ok().build();
} catch (NotFoundException | ForbiddenException e) {
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
LOG.error("Error putting entities", e);
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
LOG.error("Unexpected error while putting entities", e);
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
} finally {
long latency = Time.monotonicNow() - startTime;
if (isAsync) {
METRICS.addAsyncPutEntitiesLatency(latency, succeeded);
} else {
METRICS.addPutEntitiesLatency(latency, succeeded);
}
}
}
/**
* @param req Servlet request.
* @param res Servlet response.
* @param domain timeline domain to be put.
* @param appId Application Id to which the domain to be put belong to. If
* appId is not there or it cannot be parsed, HTTP 400 will be sent back.
* @return a Response with appropriate HTTP status.
*/
@PUT
@Path("/domain")
@Consumes({ MediaType.APPLICATION_JSON /* , MediaType.APPLICATION_XML */ })
public Response putDomain(
@Context HttpServletRequest req,
@Context HttpServletResponse res,
@QueryParam("appid") String appId,
TimelineDomain domain) {
init(res);
UserGroupInformation callerUgi = getUser(req);
if (callerUgi == null) {
String msg = "The owner of the posted timeline entities is not set";
LOG.error(msg);
throw new ForbiddenException(msg);
}
try {
ApplicationId appID = parseApplicationId(appId);
if (appID == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
NodeTimelineCollectorManager collectorManager =
(NodeTimelineCollectorManager) context.getAttribute(
NodeTimelineCollectorManager.COLLECTOR_MANAGER_ATTR_KEY);
TimelineCollector collector = collectorManager.get(appID);
if (collector == null) {
LOG.error("Application: {} is not found", appId);
throw new NotFoundException("Application: " + appId + " is not found");
}
domain.setOwner(callerUgi.getShortUserName());
collector.putDomain(domain, callerUgi);
return Response.ok().build();
} catch (NotFoundException e) {
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
LOG.error("Error putting entities", e);
throw new WebApplicationException(e,
Response.Status.INTERNAL_SERVER_ERROR);
}
}
private static ApplicationId parseApplicationId(String appId) {
try {
if (appId != null) {
return ApplicationId.fromString(appId.trim());
} else {
return null;
}
} catch (IllegalFormatException e) {
LOG.error("Invalid application ID: {}", appId);
return null;
}
}
private static void init(HttpServletResponse response) {
response.setContentType(null);
}
private static UserGroupInformation getUser(HttpServletRequest req) {
String remoteUser = req.getRemoteUser();
UserGroupInformation callerUgi = null;
if (remoteUser != null) {
callerUgi = UserGroupInformation.createRemoteUser(remoteUser);
}
return callerUgi;
}
// The process may not be necessary according to the way we write the backend,
// but let's keep it for now in case we need to use sub-classes APIs in the
// future (e.g., aggregation).
private static TimelineEntities processTimelineEntities(
TimelineEntities entities, String appId, boolean isSubAppWrite) {
TimelineEntities entitiesToReturn = new TimelineEntities();
for (TimelineEntity entity : entities.getEntities()) {
TimelineEntityType type = null;
try {
type = TimelineEntityType.valueOf(entity.getType());
} catch (IllegalArgumentException e) {
type = null;
}
if (type != null) {
switch (type) {
case YARN_CLUSTER:
entitiesToReturn.addEntity(new ClusterEntity(entity));
break;
case YARN_FLOW_RUN:
entitiesToReturn.addEntity(new FlowRunEntity(entity));
break;
case YARN_APPLICATION:
entitiesToReturn.addEntity(new ApplicationEntity(entity));
break;
case YARN_APPLICATION_ATTEMPT:
entitiesToReturn.addEntity(new ApplicationAttemptEntity(entity));
break;
case YARN_CONTAINER:
entitiesToReturn.addEntity(new ContainerEntity(entity));
break;
case YARN_QUEUE:
entitiesToReturn.addEntity(new QueueEntity(entity));
break;
case YARN_USER:
entitiesToReturn.addEntity(new UserEntity(entity));
break;
default:
break;
}
} else {
if (isSubAppWrite) {
SubApplicationEntity se = new SubApplicationEntity(entity);
se.setApplicationId(appId);
entitiesToReturn.addEntity(se);
} else {
entitiesToReturn.addEntity(entity);
}
}
}
return entitiesToReturn;
}
}
| AboutInfo |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendLoader.java | {
"start": 4726,
"end": 5528
} | class ____ not found or the factory could not be instantiated
* @throws IllegalConfigurationException May be thrown by the StateBackendFactory when creating
* / configuring the state backend in the factory
* @throws IOException May be thrown by the StateBackendFactory when instantiating the state
* backend
*/
@Nonnull
public static StateBackend loadStateBackendFromConfig(
ReadableConfig config, ClassLoader classLoader, @Nullable Logger logger)
throws IllegalConfigurationException, DynamicCodeLoadingException, IOException {
checkNotNull(config, "config");
checkNotNull(classLoader, "classLoader");
final String backendName = config.get(StateBackendOptions.STATE_BACKEND);
// by default the factory | was |
java | spring-projects__spring-boot | test-support/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/resources/OnClassWithResourceTests.java | {
"start": 1104,
"end": 1334
} | class ____ {
@Test
void whenWithResourceIsUsedOnAClassThenResourceIsAvailable() throws IOException {
assertThat(new ClassPathResource("on-class").getContentAsString(StandardCharsets.UTF_8))
.isEqualTo(" | OnClassWithResourceTests |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java | {
"start": 226586,
"end": 229823
} | class ____ extends ParserRuleContext {
public CastTemplateContext castTemplate() {
return getRuleContext(CastTemplateContext.class, 0);
}
public TerminalNode FUNCTION_ESC() {
return getToken(SqlBaseParser.FUNCTION_ESC, 0);
}
public TerminalNode ESC_END() {
return getToken(SqlBaseParser.ESC_END, 0);
}
public ConvertTemplateContext convertTemplate() {
return getRuleContext(ConvertTemplateContext.class, 0);
}
public CastExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override
public int getRuleIndex() {
return RULE_castExpression;
}
@Override
public void enterRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterCastExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitCastExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitCastExpression(this);
else return visitor.visitChildren(this);
}
}
public final CastExpressionContext castExpression() throws RecognitionException {
CastExpressionContext _localctx = new CastExpressionContext(_ctx, getState());
enterRule(_localctx, 74, RULE_castExpression);
try {
setState(710);
_errHandler.sync(this);
switch (getInterpreter().adaptivePredict(_input, 98, _ctx)) {
case 1:
enterOuterAlt(_localctx, 1); {
setState(700);
castTemplate();
}
break;
case 2:
enterOuterAlt(_localctx, 2); {
setState(701);
match(FUNCTION_ESC);
setState(702);
castTemplate();
setState(703);
match(ESC_END);
}
break;
case 3:
enterOuterAlt(_localctx, 3); {
setState(705);
convertTemplate();
}
break;
case 4:
enterOuterAlt(_localctx, 4); {
setState(706);
match(FUNCTION_ESC);
setState(707);
convertTemplate();
setState(708);
match(ESC_END);
}
break;
}
} catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
} finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | CastExpressionContext |
java | apache__camel | components/camel-base64/src/test/java/org/apache/camel/dataformat/base64/Base64DataFormatLineEndingsTest.java | {
"start": 891,
"end": 3582
} | class ____ extends Base64DataFormatTestBase {
private static final String ENCODED = "IrRWhNZNjFxQ6WXJEIsehbnFdurtgacAq+t6Zh3uYlyclF3HAx995mbIydQlymM8V3yA+Yb1p3Ij\n"
+ "7AS1VQaUNHAljNpHUqrWR6EmASZV/EQvR5Gk8XDvRrrtkoDm+jdZ/XKfest2OIzhixZF1mcqyi1P\n"
+ "Hep/rFnVPclO9WOWtCCRhz+U2soBzNBtvTc6x1pz1gOZcoOEFKHSf2kmkq1/7hHFl5Cb9nbSBgyp\n"
+ "lFzsInVBfCkRxXAFixwbC3B+LB8e15zSMvoG6okyDs7C8QShIZCXGHlsuUiH96izUbfB8qpTQK80\n"
+ "PPAisxYhF/gb678wvO5e/03AmFmYbBqzwoNQ6PoZKFI8a4PUrLoCLrUnKQgwOXueb1y8d4bsVGrX\n"
+ "H5QUFgAE3yZEn2ZQtVv6bZnm3lvBe/LLRD4xIU2Pcm5e+DJUZhHcl/8MaioDWFgYPLftDKvEUwLB\n"
+ "3IFWLSKMKFoeXn2nkwxsCHrzhajhbkKl1+H9I7Gkd19DyAoPIriWOJScog+mcP0iqG9iMqYFko2n\n"
+ "rh2rr+jcyKFBhrRUuNw3W8+h+FOwZDLcBmuTv2lEOvUdaPgD+1e6fXpuxhiih4wf/zlakeVa031T\n"
+ "9c0/HN02z0cAhLT1vtEA0zDn6OzzhY//Mh332ZmC+xro+e9o2a6+dnwamDtLuRgDDd+EcoUQpfEL\n"
+ "XobX3ZSX7OQw1ZXxWiJLtSOc5yLRkdbxdLK/C6fkcY4cqc/RwBGYtXN7Z1ENG/s/LnrZnRU/ErMW\n"
+ "RtbRwehA/0a2KSbNOMwK8BpzDruXufLXZcGaDKRUektQfdX4XhhYESt1drewlQLVaEWrZBR8JOd5\n"
+ "mckulPhwHp2Q00YyoScEj6Rs/9siyv49/FSaRCbnfzl3CRnNvCOD1cvF4OneYbVJCMOY49ucFmN/\n"
+ "mBCyxLOtJ4Zz8EG1FC81QTg3Scw+FdFDsCgr7DqVrmPOLikqq6wJdLBjyHXuMiVP9Fq/aAxvXEgj\n"
+ "RuVnN20wn2tUOXeaN4XqziQ66M229HsY0BX5riJ00yXArDxd+I9mFDpw/UDnGBAE2P//1fU1ns1A\n"
+ "6zQ6hTv7axdlw3/FnOAdymEKqED9CPfbiDvJygcAcxv2fyORHQ+TiprMGxckAlnLZ2pGl+gOzbtZ\n"
+ "zJgecyFJHBbhtkubGD4zzQhuJJw8ypqppSxqDs8SAW2frj42UT9qRMeCBGXLa1wyISt4GI6iOnfw\n"
+ "TCRJ/SE7CVrEfmdmROlJpAJHfUlQIJq1aW3mTE5zTmAygypxRUDCmA+eY9wdCicFp6YptdCEK3P2\n"
+ "7QzZsSASAByd5jxHMiIBkdwGzj1501xZ7hFLJDXDTQ==\n";
public Base64DataFormatLineEndingsTest() {
format = new Base64DataFormat();
byte[] separator = { '\n' };
format.setLineSeparator(separator);
}
@Test
void testEncode() throws Exception {
runEncoderTest(DECODED, ENCODED.getBytes());
}
@Test
void testDecode() throws Exception {
runDecoderTest(ENCODED.getBytes(), DECODED);
}
}
| Base64DataFormatLineEndingsTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/interceptor/InterceptorStrategyOrderedTest.java | {
"start": 2187,
"end": 2985
} | class ____ implements InterceptStrategy, Ordered {
@Override
public Processor wrapProcessorInInterceptors(
CamelContext context, NamedNode definition, final Processor target, Processor nextTarget) {
Processor answer = new Processor() {
public void process(Exchange exchange) throws Exception {
String order = exchange.getIn().getHeader("order", "", String.class);
order = order + getOrder();
exchange.getIn().setHeader("order", order);
target.process(exchange);
}
};
return answer;
}
@Override
public int getOrder() {
return 1;
}
}
public static | FooInterceptStrategy |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/TestConfig.java | {
"start": 1149,
"end": 1476
} | class ____ {
@Bean
Person dilbert() {
return new Person("Dilbert");
}
@Bean
Person wally() {
return new Person("Wally");
}
@Bean
Dog dogbert() {
return new Dog("Dogbert");
}
@Primary
@Bean
Cat catbert() {
return new Cat("Catbert");
}
@Bean
Cat garfield() {
return new Cat("Garfield");
}
}
| TestConfig |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/support/RootBeanDefinitionTests.java | {
"start": 4649,
"end": 4719
} | class ____ {
public void close() {
}
}
static | BeanWithCloseMethod |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/matchers/UnusedReturnValueMatcher.java | {
"start": 7364,
"end": 12319
} | interface ____ it's implementing.
// - The Symbol is the declared method symbol, i.e. V get().
// So we resolve the symbol (V get()) as a member of the qualifier type (Future<Void>) to get
// the method type (Void get()) and then look at the return type of that.
Type type =
state.getTypes().memberType(getType(tree.getQualifierExpression()), getSymbol(tree));
// TODO(cgdecker): There are probably other types than MethodType that we could resolve here
return type instanceof MethodType && isVoidType(type.getReturnType(), state);
}
private static boolean exceptionTesting(ExpressionTree tree, VisitorState state) {
return tree instanceof MemberReferenceTree
? isThrowingFunctionalInterface(getType(tree), state)
: expectedExceptionTest(state);
}
private static final Matcher<ExpressionTree> FAIL_METHOD =
anyOf(
instanceMethod().onDescendantOf("com.google.common.truth.AbstractVerb").named("fail"),
instanceMethod()
.onDescendantOf("com.google.common.truth.StandardSubjectBuilder")
.named("fail"),
staticMethod().onClass("org.junit.Assert").named("fail"),
staticMethod().onClass("junit.framework.Assert").named("fail"),
staticMethod().onClass("junit.framework.TestCase").named("fail"));
private static final Matcher<StatementTree> EXPECTED_EXCEPTION_MATCHER =
anyOf(
// expectedException.expect(Foo.class); me();
allOf(
isLastStatementInBlock(),
previousStatement(
expressionStatement(
anyOf(instanceMethod().onExactClass("org.junit.rules.ExpectedException"))))),
// try { me(); fail(); } catch (Throwable t) {}
allOf(enclosingNode(kindIs(Kind.TRY)), nextStatement(expressionStatement(FAIL_METHOD))),
// assertThrows(Throwable.class, () => { me(); })
allOf(
anyOf(isLastStatementInBlock(), parentNode(kindIs(Kind.LAMBDA_EXPRESSION))),
// Within the context of a ThrowingRunnable/Executable:
(t, s) -> methodCallInDeclarationOfThrowingRunnable(s)),
// @Test(expected = FooException.class) void bah() { me(); }
allOf(
UnusedReturnValueMatcher::isOnlyStatementInBlock,
enclosingMethod(UnusedReturnValueMatcher::isTestExpectedExceptionMethod)));
private static boolean isTestExpectedExceptionMethod(MethodTree tree, VisitorState state) {
if (!JUnitMatchers.wouldRunInJUnit4.matches(tree, state)) {
return false;
}
return getSymbol(tree).getAnnotationMirrors().stream()
.filter(am -> am.type.tsym.getQualifiedName().contentEquals("org.junit.Test"))
.findFirst()
.flatMap(testAm -> MoreAnnotations.getAnnotationValue(testAm, "expected"))
.flatMap(MoreAnnotations::asTypeValue)
.filter(tv -> !tv.toString().equals("org.junit.Test.None"))
.isPresent();
}
private static boolean isOnlyStatementInBlock(StatementTree t, VisitorState s) {
BlockTree parentBlock = ASTHelpers.findEnclosingNode(s.getPath(), BlockTree.class);
return parentBlock != null
&& parentBlock.getStatements().size() == 1
&& getOnlyElement(parentBlock.getStatements()) == t;
}
/** Allow return values to be ignored in tests that expect an exception to be thrown. */
public static boolean expectedExceptionTest(VisitorState state) {
// Allow unused return values in tests that check for thrown exceptions, e.g.:
//
// try {
// Foo.newFoo(-1);
// fail();
// } catch (IllegalArgumentException expected) {
// }
//
StatementTree statement = findEnclosingNode(state.getPath(), StatementTree.class);
return statement != null && EXPECTED_EXCEPTION_MATCHER.matches(statement, state);
}
private static final Matcher<ExpressionTree> MOCKITO_MATCHER =
anyOf(
staticMethod().onClass("org.mockito.Mockito").named("verify"),
instanceMethod().onDescendantOf("org.mockito.stubbing.Stubber").named("when"),
instanceMethod().onDescendantOf("org.mockito.InOrder").named("verify"));
/**
* Don't match the method that is invoked through {@code Mockito.verify(t)} or {@code
* doReturn(val).when(t)}.
*/
public static boolean mockitoInvocation(Tree tree, VisitorState state) {
if (!(tree instanceof JCMethodInvocation invocation)) {
return false;
}
if (!(invocation.getMethodSelect() instanceof JCFieldAccess)) {
return false;
}
ExpressionTree receiver = getReceiver(invocation);
return MOCKITO_MATCHER.matches(receiver, state);
}
/**
* Enumeration of known reasons that an unused return value may be allowed because of the context
* in which the method is used. Suppression is not considered here; these are reasons that don't
* have anything to do with specific checkers.
*/
public | type |
java | quarkusio__quarkus | extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/TransactionalStringCommandsTest.java | {
"start": 669,
"end": 2873
} | class ____ extends DatasourceTestBase {
private RedisDataSource blocking;
private ReactiveRedisDataSource reactive;
@BeforeEach
void initialize() {
blocking = new BlockingRedisDataSourceImpl(vertx, redis, api, Duration.ofSeconds(60));
reactive = new ReactiveRedisDataSourceImpl(vertx, redis, api);
}
@AfterEach
public void clear() {
blocking.flushall();
}
@Test
public void setBlocking() {
TransactionResult result = blocking.withTransaction(tx -> {
TransactionalStringCommands<String, String> string = tx.string(String.class);
assertThat(string.getDataSource()).isEqualTo(tx);
string.set(key, "hello");
string.setnx("k2", "bonjour");
string.append(key, "-1");
string.get(key);
string.strlen("k2");
});
assertThat(result.size()).isEqualTo(5);
assertThat(result.discarded()).isFalse();
assertThat(result.<Void> get(0)).isNull();
assertThat((boolean) result.get(1)).isTrue();
assertThat((long) result.get(2)).isEqualTo(7L);
assertThat((String) result.get(3)).isEqualTo("hello-1");
assertThat((long) result.get(4)).isEqualTo(7L);
}
@Test
public void setReactive() {
TransactionResult result = reactive.withTransaction(tx -> {
ReactiveTransactionalStringCommands<String, String> string = tx.string(String.class);
return string.set(key, "hello")
.chain(() -> string.setnx("k2", "bonjour"))
.chain(() -> string.append(key, "-1"))
.chain(() -> string.get(key))
.chain(() -> string.strlen("k2"));
}).await().atMost(Duration.ofSeconds(5));
assertThat(result.size()).isEqualTo(5);
assertThat(result.discarded()).isFalse();
assertThat(result.<Void> get(0)).isNull();
assertThat((boolean) result.get(1)).isTrue();
assertThat((long) result.get(2)).isEqualTo(7L);
assertThat((String) result.get(3)).isEqualTo("hello-1");
assertThat((long) result.get(4)).isEqualTo(7L);
}
}
| TransactionalStringCommandsTest |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/SecureRandomProcessor.java | {
"start": 226,
"end": 686
} | class ____ {
@BuildStep
void registerReflectiveMethods(BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods) {
// Called reflectively through java.security.SecureRandom.SecureRandom()
reflectiveMethods.produce(new ReflectiveMethodBuildItem(
getClass().getName(),
"sun.security.provider.NativePRNG", "<init>",
java.security.SecureRandomParameters.class));
}
}
| SecureRandomProcessor |
java | quarkusio__quarkus | test-framework/junit5-component/src/test/java/io/quarkus/test/component/MockNotSharedForClassHierarchyTest.java | {
"start": 1691,
"end": 1780
} | interface ____ {
default int ping() {
return 5;
}
}
}
| Alpha |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/stat/MemoryTest.java | {
"start": 914,
"end": 965
} | class ____ {
private volatile long v;
}
}
| A |
java | junit-team__junit5 | junit-platform-reporting/src/main/java/org/junit/platform/reporting/legacy/LegacyReportingUtils.java | {
"start": 1791,
"end": 3083
} | class ____ for;
* never {@code null}
* @see TestIdentifier#getLegacyReportingName
*/
public static String getClassName(TestPlan testPlan, TestIdentifier testIdentifier) {
Preconditions.notNull(testPlan, "testPlan must not be null");
Preconditions.notNull(testIdentifier, "testIdentifier must not be null");
for (TestIdentifier current = testIdentifier; current != null; current = getParent(testPlan, current)) {
ClassSource source = getClassSource(current);
if (source != null) {
return source.getClassName();
}
}
return getParentLegacyReportingName(testPlan, testIdentifier);
}
private static @Nullable TestIdentifier getParent(TestPlan testPlan, TestIdentifier testIdentifier) {
return testPlan.getParent(testIdentifier).orElse(null);
}
private static @Nullable ClassSource getClassSource(TestIdentifier current) {
// @formatter:off
return current.getSource()
.filter(ClassSource.class::isInstance)
.map(ClassSource.class::cast)
.orElse(null);
// @formatter:on
}
private static String getParentLegacyReportingName(TestPlan testPlan, TestIdentifier testIdentifier) {
// @formatter:off
return testPlan.getParent(testIdentifier)
.map(TestIdentifier::getLegacyReportingName)
.orElse("<unrooted>");
// @formatter:on
}
}
| name |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RoutingSlipPropagateVariableAsResultTestTest.java | {
"start": 973,
"end": 2385
} | class ____ extends ContextTestSupport {
@Test
public void testRoutingSlip() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("ABCD");
getMockEndpoint("mock:result").expectedVariableReceived("foo1", "AB");
getMockEndpoint("mock:result").expectedVariableReceived("foo2", "ABC");
getMockEndpoint("mock:result").expectedVariableReceived("foo3", "ABCD");
template.sendBodyAndHeader("direct:start", "A", "slip", "direct:slip1,direct:slip2,direct:slip3");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.routingSlip(header("slip"))
.to("mock:result");
from("direct:slip1")
.transform(body().append("B"))
.setVariable("foo1", simple("${body}"));
from("direct:slip2")
.transform(body().append("C"))
.setVariable("foo2", simple("${body}"));
from("direct:slip3")
.transform(body().append("D"))
.setVariable("foo3", simple("${body}"));
}
};
}
}
| RoutingSlipPropagateVariableAsResultTestTest |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/std/SimpleBeanPropertyFilter.java | {
"start": 424,
"end": 699
} | class ____ the base implementation for any custom
* {@link PropertyFilter} implementations is strongly encouraged,
* because it can provide default implementation for any methods that may
* be added in {@link PropertyFilter} (as unfortunate as additions may be).
*/
public | as |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxSkipLastTest.java | {
"start": 1149,
"end": 5348
} | class ____ extends FluxOperatorTest<String, String> {
@Override
protected Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) {
return defaultOptions.shouldAssertPostTerminateState(false)
.shouldHitDropErrorHookAfterTerminate(false)
.shouldHitDropNextHookAfterTerminate(false);
}
@Override
protected List<Scenario<String, String>> scenarios_operatorSuccess() {
return Arrays.asList(
scenario(f -> f.skipLast(1))
.receiveValues(item(0) ,item(1))
);
}
@Override
protected List<Scenario<String, String>> scenarios_errorFromUpstreamFailure() {
return Arrays.asList(scenario(f -> f.skipLast(1)));
}
@Test
public void sourceNull() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> {
new FluxSkipLast<>(null, 1);
});
}
@Test
public void negativeNumber() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
Flux.never()
.skipLast(-1);
});
}
@Test
public void skipNone() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 10)
.skipLast(0)
.subscribe(ts);
ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.assertNoError()
.assertComplete();
}
@Test
public void skipNoneBackpressured() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
Flux.range(1, 10)
.skipLast(0)
.subscribe(ts);
ts.assertNoValues()
.assertNotComplete()
.assertNoError();
ts.request(2);
ts.assertValues(1, 2)
.assertNotComplete()
.assertNoError();
ts.request(5);
ts.assertValues(1, 2, 3, 4, 5, 6, 7)
.assertNotComplete()
.assertNoError();
ts.request(10);
ts.assertValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.assertNoError()
.assertComplete();
}
@Test
public void skipSome() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 10)
.skipLast(3)
.subscribe(ts);
ts.assertValues(1, 2, 3, 4, 5, 6, 7)
.assertNoError()
.assertComplete();
}
@Test
public void skipSomeBackpressured() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
Flux.range(1, 10)
.skipLast(3)
.subscribe(ts);
ts.assertNoValues()
.assertNotComplete()
.assertNoError();
ts.request(2);
ts.assertValues(1, 2)
.assertNotComplete()
.assertNoError();
ts.request(4);
ts.assertValues(1, 2, 3, 4, 5, 6)
.assertNotComplete()
.assertNoError();
ts.request(10);
ts.assertValues(1, 2, 3, 4, 5, 6, 7)
.assertNoError()
.assertComplete();
}
@Test
public void skipAll() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 10)
.skipLast(20)
.subscribe(ts);
ts.assertNoValues()
.assertNoError()
.assertComplete();
}
@Test
public void skipAllBackpressured() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
Flux.range(1, 10)
.skipLast(20)
.subscribe(ts);
ts.assertNoValues()
.assertNoError()
.assertComplete();
}
@Test
public void scanOperator(){
Flux<Integer> parent = Flux.just(1);
FluxSkipLast<Integer> test = new FluxSkipLast<>(parent, 3);
Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
Assertions.assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanSubscriber() {
CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
FluxSkipLast.SkipLastSubscriber<Integer> test = new FluxSkipLast.SkipLastSubscriber<>(actual, 7);
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
Assertions.assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
Assertions.assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(7);
test.offer(1);
Assertions.assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);
}
}
| FluxSkipLastTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParserTest_6.java | {
"start": 957,
"end": 1177
} | class ____ {
private V1 value;
public V1 getValue() {
return value;
}
public void setValue(V1 value) {
this.value = value;
}
}
public static | Entity |
java | apache__camel | components/camel-mllp/src/test/java/org/apache/camel/component/mllp/MllpTcpServerConsumerAutoAcknowledgementWithBridgeErrorHandlerTest.java | {
"start": 1274,
"end": 5516
} | class ____
extends TcpServerConsumerAcknowledgementTestSupport {
@Override
protected boolean isBridgeErrorHandler() {
return true;
}
@Override
protected boolean isAutoAck() {
return true;
}
@Test
public void testReceiveSingleMessage() throws Exception {
result.expectedBodiesReceived(TEST_MESSAGE);
complete.expectedBodiesReceived(TEST_MESSAGE);
complete.expectedHeaderReceived(MllpConstants.MLLP_ACKNOWLEDGEMENT_TYPE, "AA");
receiveSingleMessage();
Exchange completeExchange = complete.getReceivedExchanges().get(0);
assertNotNull(completeExchange.getIn().getHeader(MllpConstants.MLLP_ACKNOWLEDGEMENT));
assertNotNull(completeExchange.getIn().getHeader(MllpConstants.MLLP_ACKNOWLEDGEMENT_STRING));
String acknowledgement = completeExchange.getIn().getHeader(MllpConstants.MLLP_ACKNOWLEDGEMENT_STRING, String.class);
assertThat(acknowledgement, startsWith("MSH|^~\\&|^org^sys||APP_A|FAC_A|"));
assertThat(acknowledgement, endsWith("||ACK^A04^ACK|||2.6\rMSA|AA|\r"));
}
public void testAcknowledgementDeliveryFailure() throws Exception {
result.expectedBodiesReceived(TEST_MESSAGE);
failure.expectedBodiesReceived(TEST_MESSAGE);
failure.expectedHeaderReceived(MllpConstants.MLLP_ACKNOWLEDGEMENT_TYPE, "AA");
failure.expectedHeaderReceived(MllpConstants.MLLP_ACKNOWLEDGEMENT, EXPECTED_ACKNOWLEDGEMENT);
failure.expectedHeaderReceived(MllpConstants.MLLP_ACKNOWLEDGEMENT_STRING, EXPECTED_ACKNOWLEDGEMENT);
acknowledgementDeliveryFailure();
Exchange failureExchange = failure.getExchanges().get(0);
Object failureException = failureExchange.getProperty(MllpConstants.MLLP_ACKNOWLEDGEMENT_EXCEPTION);
assertNotNull(failureException,
"OnFailureOnly exchange should have a " + MllpConstants.MLLP_ACKNOWLEDGEMENT_EXCEPTION + " property");
assertIsInstanceOf(Exception.class, failureException);
}
@Test
public void testUnparsableMessage() throws Exception {
final String testMessage = "MSH" + TEST_MESSAGE;
result.expectedBodiesReceived(testMessage);
complete.expectedMessageCount(1);
ackGenerationEx.expectedMessageCount(1);
unparsableMessage(testMessage);
assertNull(result.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
assertNull(complete.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
assertNotNull(ackGenerationEx.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should have the exception in the exchange property");
}
@Test
public void testMessageWithEmptySegment() throws Exception {
final String testMessage = TEST_MESSAGE.replace("\rPID|", "\r\rPID|");
result.expectedBodiesReceived(testMessage);
complete.expectedMessageCount(1);
unparsableMessage(testMessage);
assertNull(result.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
assertNull(complete.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
}
@Test
public void testMessageWithEmbeddedNewlines() throws Exception {
final String testMessage = TEST_MESSAGE.replace("\rPID|", "\r\n\rPID|\n");
result.expectedBodiesReceived(testMessage);
complete.expectedMessageCount(1);
unparsableMessage(testMessage);
assertNull(result.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
assertNull(complete.getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT),
"Should not have the exception in the exchange property");
}
}
| MllpTcpServerConsumerAutoAcknowledgementWithBridgeErrorHandlerTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/deser/FieldDeserializerTest7.java | {
"start": 683,
"end": 750
} | class ____ {
public double id;
}
private static | VO |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java | {
"start": 3371,
"end": 6370
} | class ____ implements InitializingBean, DisposableBean {
private static final String SECURITY_REACTOR_CONTEXT_OPERATOR_KEY = "org.springframework.security.SECURITY_REACTOR_CONTEXT_OPERATOR";
private final Map<Object, Supplier<Object>> CONTEXT_ATTRIBUTE_VALUE_LOADERS = new HashMap<>();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
SecurityReactorContextSubscriberRegistrar() {
this.CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletRequest.class,
SecurityReactorContextSubscriberRegistrar::getRequest);
this.CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(HttpServletResponse.class,
SecurityReactorContextSubscriberRegistrar::getResponse);
this.CONTEXT_ATTRIBUTE_VALUE_LOADERS.put(Authentication.class, this::getAuthentication);
}
@Override
public void afterPropertiesSet() throws Exception {
Function<? super Publisher<Object>, ? extends Publisher<Object>> lifter = Operators
.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, lifter::apply);
}
@Override
public void destroy() throws Exception {
Hooks.resetOnLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY);
}
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
<T> CoreSubscriber<T> createSubscriberIfNecessary(CoreSubscriber<T> delegate) {
if (delegate.currentContext().hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)) {
// Already enriched. No need to create Subscriber so return original
return delegate;
}
return new SecurityReactorContextSubscriber<>(delegate, getContextAttributes());
}
private Map<Object, Object> getContextAttributes() {
return new LoadingMap<>(this.CONTEXT_ATTRIBUTE_VALUE_LOADERS);
}
private static HttpServletRequest getRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
return servletRequestAttributes.getRequest();
}
return null;
}
private static HttpServletResponse getResponse() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
return servletRequestAttributes.getResponse(); // possible null
}
return null;
}
private Authentication getAuthentication() {
return this.securityContextHolderStrategy.getContext().getAuthentication();
}
}
static | SecurityReactorContextSubscriberRegistrar |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/ReflectiveClassBuildItem.java | {
"start": 304,
"end": 7936
} | class ____ extends MultiBuildItem {
// The names of the classes that should be registered for reflection
private final List<String> className;
private final boolean methods;
private final boolean queryMethods;
private final boolean fields;
private final boolean classes;
private final boolean constructors;
private final boolean publicConstructors;
private final boolean queryConstructors;
private final boolean weak;
private final boolean serialization;
private final boolean unsafeAllocated;
private final String reason;
private static final Logger log = Logger.getLogger(ReflectiveClassBuildItem.class);
public static Builder builder(Class<?>... classes) {
String[] classNames = stream(classes)
.map(aClass -> {
if (aClass == null) {
throw new NullPointerException();
}
return aClass.getName();
})
.toArray(String[]::new);
return new Builder().className(classNames);
}
public static Builder builder(String... classNames) {
return new Builder().className(classNames);
}
private ReflectiveClassBuildItem(boolean constructors, boolean queryConstructors, boolean methods, boolean queryMethods,
boolean fields, boolean getClasses, boolean weak, boolean serialization, boolean unsafeAllocated, String reason,
Class<?>... classes) {
this(constructors, false, queryConstructors, methods, queryMethods, fields, getClasses, weak, serialization,
unsafeAllocated, reason, stream(classes).map(Class::getName).toArray(String[]::new));
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
@Deprecated(since = "3.0", forRemoval = true)
public ReflectiveClassBuildItem(boolean methods, boolean fields, Class<?>... classes) {
this(true, methods, fields, classes);
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
@Deprecated(since = "3.0", forRemoval = true)
public ReflectiveClassBuildItem(boolean constructors, boolean methods, boolean fields, Class<?>... classes) {
this(constructors, false, methods, false, fields, false, false, false, false, null, classes);
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
@Deprecated(since = "3.0", forRemoval = true)
public ReflectiveClassBuildItem(boolean methods, boolean fields, String... classNames) {
this(true, methods, fields, classNames);
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
@Deprecated(since = "3.0", forRemoval = true)
public ReflectiveClassBuildItem(boolean constructors, boolean methods, boolean fields, String... classNames) {
this(constructors, false, methods, false, fields, false, false, false, classNames);
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
@Deprecated(since = "3.0", forRemoval = true)
public ReflectiveClassBuildItem(boolean constructors, boolean methods, boolean fields, boolean serialization,
String... classNames) {
this(constructors, false, methods, false, fields, false, serialization, false, classNames);
}
public static ReflectiveClassBuildItem weakClass(String... classNames) {
return ReflectiveClassBuildItem.builder(classNames).constructors().methods().fields().weak().build();
}
/**
* @deprecated Use {@link ReflectiveClassBuildItem#builder(Class...)} or {@link ReflectiveClassBuildItem#builder(String...)}
* instead.
*/
public static ReflectiveClassBuildItem weakClass(boolean constructors, boolean methods, boolean fields,
String... classNames) {
return ReflectiveClassBuildItem.builder(classNames).constructors(constructors).methods(methods).fields(fields).weak()
.build();
}
public static ReflectiveClassBuildItem serializationClass(String... classNames) {
return ReflectiveClassBuildItem.builder(classNames).serialization().build();
}
@Deprecated(since = "3.14", forRemoval = true)
ReflectiveClassBuildItem(boolean constructors, boolean queryConstructors, boolean methods, boolean queryMethods,
boolean fields, boolean weak, boolean serialization,
boolean unsafeAllocated, String... className) {
this(constructors, false, queryConstructors, methods, queryMethods, fields, false, weak, serialization, unsafeAllocated,
null, className);
}
ReflectiveClassBuildItem(boolean constructors, boolean publicConstructors, boolean queryConstructors, boolean methods,
boolean queryMethods,
boolean fields, boolean classes, boolean weak, boolean serialization,
boolean unsafeAllocated, String reason, String... className) {
for (String i : className) {
if (i == null) {
throw new NullPointerException();
}
}
this.className = Arrays.asList(className);
this.methods = methods;
if (methods && queryMethods) {
log.warnf(
"Both methods and queryMethods are set to true for classes: %s. queryMethods is redundant and will be ignored",
String.join(", ", className));
this.queryMethods = false;
} else {
this.queryMethods = queryMethods;
}
this.fields = fields;
this.classes = classes;
this.constructors = constructors;
this.publicConstructors = publicConstructors;
if (constructors && queryConstructors) {
log.warnf(
"Both constructors and queryConstructors are set to true for classes: %s. queryConstructors is redundant and will be ignored",
String.join(", ", className));
this.queryConstructors = false;
} else {
this.queryConstructors = queryConstructors;
}
this.weak = weak;
this.serialization = serialization;
this.unsafeAllocated = unsafeAllocated;
this.reason = reason;
}
public List<String> getClassNames() {
return className;
}
public boolean isMethods() {
return methods;
}
public boolean isQueryMethods() {
return queryMethods;
}
public boolean isFields() {
return fields;
}
public boolean isClasses() {
return classes;
}
public boolean isConstructors() {
return constructors;
}
public boolean isPublicConstructors() {
return publicConstructors;
}
public boolean isQueryConstructors() {
return queryConstructors;
}
public boolean isWeak() {
return weak;
}
public boolean isSerialization() {
return serialization;
}
public boolean isUnsafeAllocated() {
return unsafeAllocated;
}
public String getReason() {
return reason;
}
public static | ReflectiveClassBuildItem |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/file/tfile/TestCompression.java | {
"start": 1109,
"end": 2405
} | class ____ {
@BeforeAll
public static void resetConfigBeforeAll() {
Compression.Algorithm.LZO.conf.setBoolean("test.reload.lzo.codec", true);
}
@AfterAll
public static void resetConfigAfterAll() {
Compression.Algorithm.LZO.conf.setBoolean("test.reload.lzo.codec", false);
}
/**
* Regression test for HADOOP-11418.
* Verify we can set a LZO codec different from default LZO codec.
*/
@Test
public void testConfigureLZOCodec() throws IOException {
// Dummy codec
String defaultCodec = "org.apache.hadoop.io.compress.DefaultCodec";
Compression.Algorithm.conf.set(
Compression.Algorithm.CONF_LZO_CLASS, defaultCodec);
assertEquals(defaultCodec,
Compression.Algorithm.LZO.getCodec().getClass().getName());
}
@Test
public void testMisconfiguredLZOCodec() throws Exception {
// Dummy codec
String defaultCodec = "org.apache.hadoop.io.compress.InvalidLzoCodec";
Compression.Algorithm.conf.set(
Compression.Algorithm.CONF_LZO_CLASS, defaultCodec);
IOException ioEx = LambdaTestUtils.intercept(
IOException.class,
defaultCodec,
() -> Compression.Algorithm.LZO.getCodec());
if (!(ioEx.getCause() instanceof ClassNotFoundException)) {
throw ioEx;
}
}
}
| TestCompression |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/NestedObjectMapper.java | {
"start": 5812,
"end": 7441
} | class ____ extends ObjectMapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, MappingParserContext parserContext)
throws MapperParsingException {
if (parseSubobjects(node).explicit()) {
throw new MapperParsingException("Nested type [" + name + "] does not support [subobjects] parameter");
}
NestedObjectMapper.Builder builder = new NestedObjectMapper.Builder(
name,
parserContext.indexVersionCreated(),
parserContext::bitSetProducer,
parserContext.getIndexSettings()
);
parseNested(name, node, builder);
parseObjectFields(node, parserContext, builder);
return builder;
}
protected static void parseNested(String name, Map<String, Object> node, NestedObjectMapper.Builder builder) {
Object fieldNode = node.get("include_in_parent");
if (fieldNode != null) {
boolean includeInParent = XContentMapValues.nodeBooleanValue(fieldNode, name + ".include_in_parent");
builder.includeInParent(includeInParent);
node.remove("include_in_parent");
}
fieldNode = node.get("include_in_root");
if (fieldNode != null) {
boolean includeInRoot = XContentMapValues.nodeBooleanValue(fieldNode, name + ".include_in_root");
builder.includeInRoot(includeInRoot);
node.remove("include_in_root");
}
}
}
static | TypeParser |
java | elastic__elasticsearch | libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/StoreTrustConfig.java | {
"start": 965,
"end": 6757
} | class ____ implements SslTrustConfig {
private final String truststorePath;
private final char[] password;
private final String type;
private final String algorithm;
private final boolean requireTrustAnchors;
private final Path configBasePath;
/**
* @param path The path to the keystore file
* @param password The password for the keystore
* @param type The {@link KeyStore#getType() type} of the keystore (typically "PKCS12" or "jks").
* See {@link KeyStoreUtil#inferKeyStoreType}.
* @param algorithm The algorithm to use for the Trust Manager (see {@link javax.net.ssl.TrustManagerFactory#getAlgorithm()}).
* @param requireTrustAnchors If true, the truststore will be checked to ensure that it contains at least one valid trust anchor.
* @param configBasePath The base path for the configuration directory
*/
public StoreTrustConfig(String path, char[] password, String type, String algorithm, boolean requireTrustAnchors, Path configBasePath) {
this.truststorePath = Objects.requireNonNull(path, "Truststore path cannot be null");
this.type = Objects.requireNonNull(type, "Truststore type cannot be null");
this.algorithm = Objects.requireNonNull(algorithm, "Truststore algorithm cannot be null");
this.password = Objects.requireNonNull(password, "Truststore password cannot be null (but may be empty)");
this.requireTrustAnchors = requireTrustAnchors;
this.configBasePath = configBasePath;
}
@Override
public Collection<Path> getDependentFiles() {
return List.of(resolvePath());
}
private Path resolvePath() {
return configBasePath.resolve(this.truststorePath);
}
@Override
public Collection<? extends StoredCertificate> getConfiguredCertificates() {
final Path path = resolvePath();
final KeyStore trustStore = readKeyStore(path);
return KeyStoreUtil.stream(trustStore, ex -> keystoreException(path, ex)).map(entry -> {
final X509Certificate certificate = entry.getX509Certificate();
if (certificate != null) {
final boolean hasKey = entry.isKeyEntry();
return new StoredCertificate(certificate, this.truststorePath, this.type, entry.getAlias(), hasKey);
} else {
return null;
}
}).filter(Objects::nonNull).toList();
}
@Override
public X509ExtendedTrustManager createTrustManager() {
final Path path = resolvePath();
try {
final KeyStore store = readKeyStore(path);
if (requireTrustAnchors) {
checkTrustStore(store, path);
}
return KeyStoreUtil.createTrustManager(store, algorithm);
} catch (GeneralSecurityException e) {
throw keystoreException(path, e);
}
}
private KeyStore readKeyStore(Path path) {
try {
return KeyStoreUtil.readKeyStore(path, type, password);
} catch (SecurityException e) {
throw SslFileUtil.accessControlFailure(fileTypeForException(), List.of(path), e, configBasePath);
} catch (IOException e) {
throw SslFileUtil.ioException(fileTypeForException(), List.of(path), e, getAdditionalErrorDetails());
} catch (GeneralSecurityException e) {
throw keystoreException(path, e);
}
}
private SslConfigException keystoreException(Path path, GeneralSecurityException e) {
final String extra = getAdditionalErrorDetails();
return SslFileUtil.securityException(fileTypeForException(), List.of(path), e, extra);
}
private String getAdditionalErrorDetails() {
final String extra;
if (password.length == 0) {
extra = "(no password was provided)";
} else {
extra = "(a keystore password was provided)";
}
return extra;
}
private String fileTypeForException() {
return "[" + type + "] keystore (as a truststore)";
}
/**
* Verifies that the keystore contains at least 1 trusted certificate entry.
*/
private static void checkTrustStore(KeyStore store, Path path) throws GeneralSecurityException {
Enumeration<String> aliases = store.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (store.isCertificateEntry(alias)) {
return;
}
}
throw new SslConfigException("the truststore [" + path + "] does not contain any trusted certificate entries");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StoreTrustConfig that = (StoreTrustConfig) o;
return truststorePath.equals(that.truststorePath)
&& Arrays.equals(password, that.password)
&& type.equals(that.type)
&& algorithm.equals(that.algorithm);
}
@Override
public int hashCode() {
int result = Objects.hash(truststorePath, type, algorithm);
result = 31 * result + Arrays.hashCode(password);
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("StoreTrustConfig{");
sb.append("path=").append(truststorePath);
sb.append(", password=").append(password.length == 0 ? "<empty>" : "<non-empty>");
sb.append(", type=").append(type);
sb.append(", algorithm=").append(algorithm);
sb.append('}');
return sb.toString();
}
@Override
public boolean hasExplicitConfig() {
return true;
}
}
| StoreTrustConfig |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/spi/EntityInstantiator.java | {
"start": 192,
"end": 425
} | interface ____ extends Instantiator {
/**
* Create an instance of managed entity
*/
Object instantiate();
/**
* Can this entity be instantiated?
*/
default boolean canBeInstantiated() {
return true;
}
}
| EntityInstantiator |
java | quarkusio__quarkus | extensions/vertx/runtime/src/main/java/io/quarkus/vertx/core/runtime/BufferOutputStream.java | {
"start": 262,
"end": 663
} | class ____ extends OutputStream {
private final Buffer buffer;
public BufferOutputStream(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
buffer.appendBytes(b, off, len);
}
@Override
public void write(int b) throws IOException {
buffer.appendInt(b);
}
}
| BufferOutputStream |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/serializer/WriteClassNameTest.java | {
"start": 716,
"end": 1289
} | class ____ {
private int id;
private String name;
private float average;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getAverage() {
return average;
}
public void setAverage(float average) {
this.average = average;
}
}
}
| Entity |
java | apache__camel | components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/template/ast/Template.java | {
"start": 988,
"end": 1468
} | class ____ {
private final List<Object> parameterList = new ArrayList<>();
private String procedureName;
public void addParameter(Object parameter) {
parameterList.add(parameter);
}
public String getProcedureName() {
return procedureName;
}
public void setProcedureName(String procedureName) {
this.procedureName = procedureName;
}
public List<Object> getParameterList() {
return parameterList;
}
}
| Template |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/plugins/PluginIntrospectorTests.java | {
"start": 13936,
"end": 14170
} | class ____ extends Plugin implements NetworkPlugin {}
assertThat(pluginIntrospector.deprecatedInterfaces(DeprecatedPlugin.class), contains("NetworkPlugin"));
}
public void testDeprecatedMethod() {
| DeprecatedPlugin |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/rule/RuleExecutor.java | {
"start": 4197,
"end": 7835
} | class ____ {
private final TreeType before, after;
private final Map<Batch<TreeType>, List<Transformation>> transformations;
ExecutionInfo(TreeType before, TreeType after, Map<Batch<TreeType>, List<Transformation>> transformations) {
this.before = before;
this.after = after;
this.transformations = transformations;
}
public TreeType before() {
return before;
}
public TreeType after() {
return after;
}
public Map<Batch<TreeType>, List<Transformation>> transformations() {
return transformations;
}
}
protected final TreeType execute(TreeType plan) {
return executeWithInfo(plan).after;
}
protected final ExecutionInfo executeWithInfo(TreeType plan) {
TreeType currentPlan = plan;
long totalDuration = 0;
Map<Batch<TreeType>, List<Transformation>> transformations = new LinkedHashMap<>();
if (batches == null) {
batches = batches();
}
for (Batch<TreeType> batch : batches) {
int batchRuns = 0;
List<Transformation> tfs = new ArrayList<>();
transformations.put(batch, tfs);
boolean hasChanged = false;
long batchStart = System.currentTimeMillis();
long batchDuration = 0;
// run each batch until no change occurs or the limit is reached
do {
hasChanged = false;
batchRuns++;
for (Rule<?, TreeType> rule : batch.rules) {
if (log.isTraceEnabled()) {
log.trace("About to apply rule {}", rule);
}
Transformation tf = new Transformation(rule.name(), currentPlan, transform(rule));
tfs.add(tf);
currentPlan = tf.after;
if (tf.hasChanged()) {
hasChanged = true;
if (changeLog.isTraceEnabled()) {
changeLog.trace("Rule {} applied with change\n{}", rule, NodeUtils.diffString(tf.before, tf.after));
}
} else {
if (log.isTraceEnabled()) {
log.trace("Rule {} applied w/o changes", rule);
}
}
}
batchDuration = System.currentTimeMillis() - batchStart;
} while (hasChanged && batch.limit.reached(batchRuns) == false);
totalDuration += batchDuration;
if (log.isTraceEnabled()) {
TreeType before = plan;
TreeType after = plan;
if (tfs.isEmpty() == false) {
before = tfs.get(0).before;
after = tfs.get(tfs.size() - 1).after;
}
log.trace(
"Batch {} applied took {}\n{}",
batch.name,
TimeValue.timeValueMillis(batchDuration),
NodeUtils.diffString(before, after)
);
}
}
if (false == currentPlan.equals(plan) && log.isDebugEnabled()) {
log.debug("Tree transformation took {}\n{}", TimeValue.timeValueMillis(totalDuration), NodeUtils.diffString(plan, currentPlan));
}
return new ExecutionInfo(plan, currentPlan, transformations);
}
protected Function<TreeType, TreeType> transform(Rule<?, TreeType> rule) {
return rule::apply;
}
}
| ExecutionInfo |
java | quarkusio__quarkus | extensions/devui/deployment/src/main/java/io/quarkus/devui/deployment/DevUIConfig.java | {
"start": 1732,
"end": 2018
} | interface ____ {
/**
* Folders to ignore in the workspace
*/
Optional<List<String>> ignoreFolders();
/**
* Files to ignore in the workspace
*/
Optional<List<Pattern>> ignoreFiles();
}
@ConfigGroup
| Workspace |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/jdbc/JdbcMocks.java | {
"start": 6985,
"end": 10072
} | class ____ implements InvocationHandler {
private final Options options;
private final Connection connectionProxy;
public DatabaseMetaDataHandler(Options options, Connection connectionProxy) {
this.options = options;
this.connectionProxy = connectionProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final String methodName = method.getName();
if ( "getDatabaseProductName".equals( methodName ) ) {
return options.databaseProductName;
}
if ( "getDatabaseMajorVersion".equals( methodName ) ) {
return Integer.valueOf( options.databaseMajorVersion );
}
if ( "getDatabaseMinorVersion".equals( methodName ) ) {
return Integer.valueOf( options.databaseMinorVersion );
}
if ( "getConnection".equals( methodName ) ) {
return connectionProxy;
}
if ( "toString".equals( methodName ) ) {
return "DatabaseMetaData proxy [db-name=" + options.databaseProductName + ", version=" + options.databaseMajorVersion + "]";
}
if ( "hashCode".equals( methodName ) ) {
return Integer.valueOf( this.hashCode() );
}
if ( "supportsNamedParameters".equals( methodName ) ) {
return options.supportsNamedParameters;
}
if ( "supportsResultSetType".equals( methodName ) ) {
return options.supportsResultSetType;
}
if ( "supportsGetGeneratedKeys".equals( methodName ) ) {
return options.supportsGetGeneratedKeys;
}
if ( "supportsBatchUpdates".equals( methodName ) ) {
return options.supportsBatchUpdates;
}
if ( "dataDefinitionIgnoredInTransactions".equals( methodName ) ) {
return options.dataDefinitionIgnoredInTransactions;
}
if ( "dataDefinitionCausesTransactionCommit".equals( methodName ) ) {
return options.dataDefinitionCausesTransactionCommit;
}
if ( "getSQLKeywords".equals( methodName ) ) {
return options.sqlKeywords;
}
if ( "getSQLStateType".equals( methodName ) ) {
return options.sqlStateType;
}
if ( "locatorsUpdateCopy".equals( methodName ) ) {
return options.locatorsUpdateCopy;
}
if ( "getTypeInfo".equals( methodName ) ) {
return EmptyResultSetHandler.makeProxy();
}
if ( "storesLowerCaseIdentifiers".equals( methodName ) ) {
return options.storesLowerCaseIdentifiers;
}
if ( "storesUpperCaseIdentifiers".equals( methodName ) ) {
return options.storesUpperCaseIdentifiers;
}
if ( "getCatalogSeparator".equals( methodName ) ) {
return options.catalogSeparator;
}
if ( "isCatalogAtStart".equals( methodName ) ) {
return options.isCatalogAtStart;
}
if ( canThrowSQLException( method ) ) {
throw new SQLException();
}
else {
throw new UnsupportedOperationException();
}
}
}
private static boolean canThrowSQLException(Method method) {
final Class[] exceptions = method.getExceptionTypes();
for ( Class exceptionType : exceptions ) {
if ( SQLException.class.isAssignableFrom( exceptionType ) ) {
return true;
}
}
return false;
}
public static | DatabaseMetaDataHandler |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/format/EnumFormatShapeTest.java | {
"start": 2047,
"end": 4783
} | enum ____ {
DEFAULT("default"),
ATTRIBUTES("attributes") {
@Override
public String toString() {
return name();
}
};
private final String key;
private Enum2576(String key) {
this.key = key;
}
public String getKey() { return this.key; }
}
/*
/**********************************************************
/* Tests
/**********************************************************
*/
private final ObjectMapper MAPPER = newJsonMapper();
// Tests for JsonFormat.shape
@Test
public void testEnumAsObjectValid() throws Exception {
assertEquals("{\"value\":\"a1\"}", MAPPER.writeValueAsString(PoNUM.A));
}
@Test
public void testEnumAsIndexViaAnnotations() throws Exception {
assertEquals("{\"text\":0}", MAPPER.writeValueAsString(new PoNUMContainer()));
}
// As of 2.5, use of Shape.ARRAY is legal alias for "write as number"
@Test
public void testEnumAsObjectBroken() throws Exception
{
assertEquals("0", MAPPER.writeValueAsString(PoAsArray.A));
}
// [databind#572]
@Test
public void testOverrideEnumAsString() throws Exception {
assertEquals("{\"value\":\"B\"}", MAPPER.writeValueAsString(new PoOverrideAsString()));
}
@Test
public void testOverrideEnumAsNumber() throws Exception {
assertEquals("{\"value\":1}", MAPPER.writeValueAsString(new PoOverrideAsNumber()));
}
// for [databind#1543]
@Test
public void testEnumValueAsNumber() throws Exception {
assertEquals(String.valueOf(Color.GREEN.ordinal()),
MAPPER.writeValueAsString(Color.GREEN));
}
@Test
public void testEnumPropertyAsNumber() throws Exception {
assertEquals(String.format(a2q("{'color':%s}"), Color.GREEN.ordinal()),
MAPPER.writeValueAsString(new ColorWrapper(Color.GREEN)));
}
// [databind#2365]
@Test
public void testEnumWithNamingStrategy() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
.build();
String json = mapper.writeValueAsString(Enum2365.B);
assertEquals(a2q("{'main_value':'B-x'}"), json);
}
// [databind#2576]
@Test
public void testEnumWithMethodOverride() throws Exception {
String stringResult = MAPPER.writeValueAsString(Enum2576.ATTRIBUTES);
Map<?,?> result = MAPPER.readValue(stringResult, Map.class);
Map<String,String> exp = Collections.singletonMap("key", "attributes");
assertEquals(exp, result);
}
}
| Enum2576 |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/server/header/CrossOriginOpenerPolicyServerHttpHeadersWriter.java | {
"start": 2161,
"end": 2481
} | enum ____ {
UNSAFE_NONE("unsafe-none"),
SAME_ORIGIN_ALLOW_POPUPS("same-origin-allow-popups"),
SAME_ORIGIN("same-origin");
private final String policy;
CrossOriginOpenerPolicy(String policy) {
this.policy = policy;
}
public String getPolicy() {
return this.policy;
}
}
}
| CrossOriginOpenerPolicy |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubsConcurrentTest.java | {
"start": 755,
"end": 819
} | interface ____ {
List<String> doSomething();
}
}
| Service |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/spr16756/Spr16756Tests.java | {
"start": 838,
"end": 1191
} | class ____ {
@Test
void shouldNotFailOnNestedScopedComponent() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(ScanningConfiguration.class);
context.refresh();
context.getBean(ScannedComponent.class);
context.getBean(ScannedComponent.State.class);
context.close();
}
}
| Spr16756Tests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/JournalSet.java | {
"start": 12255,
"end": 14767
} | interface ____ {
/**
* The operation on JournalAndStream.
* @param jas Object on which operations are performed.
* @throws IOException
*/
public void apply(JournalAndStream jas) throws IOException;
}
/**
* Apply the given operation across all of the journal managers, disabling
* any for which the closure throws an IOException.
* @param closure {@link JournalClosure} object encapsulating the operation.
* @param status message used for logging errors (e.g. "opening journal")
* @throws IOException If the operation fails on all the journals.
*/
private void mapJournalsAndReportErrors(
JournalClosure closure, String status) throws IOException{
List<JournalAndStream> badJAS = Lists.newLinkedList();
for (JournalAndStream jas : journals) {
try {
closure.apply(jas);
} catch (Throwable t) {
if (jas.isRequired()) {
final String msg = "Error: " + status + " failed for required journal ("
+ jas + ")";
LOG.error(msg, t);
// If we fail on *any* of the required journals, then we must not
// continue on any of the other journals. Abort them to ensure that
// retry behavior doesn't allow them to keep going in any way.
abortAllJournals();
// the current policy is to shutdown the NN on errors to shared edits
// dir. There are many code paths to shared edits failures - syncs,
// roll of edits etc. All of them go through this common function
// where the isRequired() check is made. Applying exit policy here
// to catch all code paths.
terminate(1, msg);
} else {
LOG.error("Error: " + status + " failed for (journal " + jas + ")", t);
badJAS.add(jas);
}
}
}
disableAndReportErrorOnJournals(badJAS);
if (!NameNodeResourcePolicy.areResourcesAvailable(journals,
minimumRedundantJournals)) {
String message = status + " failed for too many journals";
LOG.error("Error: " + message);
throw new IOException(message);
}
}
/**
* Abort all of the underlying streams.
*/
private void abortAllJournals() {
for (JournalAndStream jas : journals) {
if (jas.isActive()) {
jas.abort();
}
}
}
/**
* An implementation of EditLogOutputStream that applies a requested method on
* all the journals that are currently active.
*/
private | JournalClosure |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java | {
"start": 1023,
"end": 4096
} | class ____ {
private Method method;
private SynthesizingMethodParameter stringParameter;
private SynthesizingMethodParameter longParameter;
private SynthesizingMethodParameter intReturnType;
@BeforeEach
void setUp() throws NoSuchMethodException {
method = getClass().getMethod("method", String.class, long.class);
stringParameter = new SynthesizingMethodParameter(method, 0);
longParameter = new SynthesizingMethodParameter(method, 1);
intReturnType = new SynthesizingMethodParameter(method, -1);
}
@Test
void equals() throws NoSuchMethodException {
assertThat(stringParameter).isEqualTo(stringParameter);
assertThat(longParameter).isEqualTo(longParameter);
assertThat(intReturnType).isEqualTo(intReturnType);
assertThat(stringParameter).isNotEqualTo(longParameter);
assertThat(stringParameter).isNotEqualTo(intReturnType);
assertThat(longParameter).isNotEqualTo(stringParameter);
assertThat(longParameter).isNotEqualTo(intReturnType);
assertThat(intReturnType).isNotEqualTo(stringParameter);
assertThat(intReturnType).isNotEqualTo(longParameter);
Method method = getClass().getMethod("method", String.class, long.class);
MethodParameter methodParameter = new SynthesizingMethodParameter(method, 0);
assertThat(methodParameter).isEqualTo(stringParameter);
assertThat(stringParameter).isEqualTo(methodParameter);
assertThat(methodParameter).isNotEqualTo(longParameter);
assertThat(longParameter).isNotEqualTo(methodParameter);
methodParameter = new MethodParameter(method, 0);
assertThat(methodParameter).isEqualTo(stringParameter);
assertThat(stringParameter).isEqualTo(methodParameter);
assertThat(methodParameter).isNotEqualTo(longParameter);
assertThat(longParameter).isNotEqualTo(methodParameter);
}
@Test
void testHashCode() throws NoSuchMethodException {
assertThat(stringParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(longParameter.hashCode()).isEqualTo(longParameter.hashCode());
assertThat(intReturnType.hashCode()).isEqualTo(intReturnType.hashCode());
Method method = getClass().getMethod("method", String.class, long.class);
SynthesizingMethodParameter methodParameter = new SynthesizingMethodParameter(method, 0);
assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode());
assertThat(methodParameter.hashCode()).isNotEqualTo(longParameter.hashCode());
}
@Test
void factoryMethods() {
assertThat(SynthesizingMethodParameter.forExecutable(method, 0)).isEqualTo(stringParameter);
assertThat(SynthesizingMethodParameter.forExecutable(method, 1)).isEqualTo(longParameter);
assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[0])).isEqualTo(stringParameter);
assertThat(SynthesizingMethodParameter.forParameter(method.getParameters()[1])).isEqualTo(longParameter);
}
@Test
void indexValidation() {
assertThatIllegalArgumentException().isThrownBy(() ->
new SynthesizingMethodParameter(method, 2));
}
public int method(String p1, long p2) {
return 42;
}
}
| SynthesizingMethodParameterTests |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/yearmonth/YearMonthAssert_isNotIn_Test.java | {
"start": 1229,
"end": 2638
} | class ____ extends YearMonthAssertBaseTest {
@Test
void should_pass_if_actual_is_not_in_dates_as_string_array_parameter() {
assertThat(REFERENCE).isNotIn(AFTER.toString(), BEFORE.toString());
}
@Test
void should_fail_if_actual_is_in_dates_as_string_array_parameter() {
// WHEN
ThrowingCallable code = () -> assertThat(REFERENCE).isNotIn(REFERENCE.toString(), AFTER.toString());
// THEN
assertThatAssertionErrorIsThrownBy(code).withMessage(shouldNotBeIn(REFERENCE, asList(REFERENCE, AFTER)).create());
}
@Test
void should_fail_if_dates_as_string_array_parameter_is_null() {
// GIVEN
String[] otherYearMonthsAsString = null;
// WHEN
ThrowingCallable code = () -> assertThat(YearMonth.now()).isNotIn(otherYearMonthsAsString);
// THEN
assertThatIllegalArgumentException().isThrownBy(code)
.withMessage("The given YearMonth array should not be null");
}
@Test
void should_fail_if_dates_as_string_array_parameter_is_empty() {
// GIVEN
String[] otherYearMonthsAsString = new String[0];
// WHEN
ThrowingCallable code = () -> assertThat(YearMonth.now()).isNotIn(otherYearMonthsAsString);
// THEN
assertThatIllegalArgumentException().isThrownBy(code)
.withMessage("The given YearMonth array should not be empty");
}
}
| YearMonthAssert_isNotIn_Test |
java | junit-team__junit5 | junit-vintage-engine/src/testFixtures/java/org/junit/vintage/engine/samples/junit4/NotFilterableRunner.java | {
"start": 394,
"end": 526
} | class ____ extends ConfigurableRunner {
public NotFilterableRunner(Class<?> testClass) {
super(testClass);
}
}
| NotFilterableRunner |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/TestInstanceLifecycleConfigurationTests.java | {
"start": 1812,
"end": 5364
} | class ____ extends AbstractJupiterTestEngineTests {
private static final String KEY = Constants.DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME;
private static final List<String> methodsInvoked = new ArrayList<>();
@BeforeEach
@AfterEach
void reset() {
methodsInvoked.clear();
System.clearProperty(KEY);
}
@Test
void instancePerMethodUsingStandardDefaultConfiguration() {
performAssertions(AssumedInstancePerTestMethodTestCase.class, 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerClassConfiguredViaExplicitAnnotationDeclaration() {
performAssertions(ExplicitInstancePerClassTestCase.class, 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerClassConfiguredViaSystemProperty() {
Class<?> testClass = AssumedInstancePerClassTestCase.class;
// Should fail by default...
performAssertions(testClass, 1, 1, 0);
// Should pass with the system property set
System.setProperty(KEY, PER_CLASS.name());
performAssertions(testClass, 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerClassConfiguredViaConfigParam() {
Class<?> testClass = AssumedInstancePerClassTestCase.class;
// Should fail by default...
performAssertions(testClass, 1, 1, 0);
// Should pass with the config param
performAssertions(testClass, Map.of(KEY, PER_CLASS.name()), 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerClassConfiguredViaConfigParamThatOverridesSystemProperty() {
Class<?> testClass = AssumedInstancePerClassTestCase.class;
// Should fail with system property
System.setProperty(KEY, PER_METHOD.name());
performAssertions(testClass, 1, 1, 0);
// Should pass with the config param
performAssertions(testClass, Map.of(KEY, PER_CLASS.name()), 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerMethodConfiguredViaExplicitAnnotationDeclarationThatOverridesSystemProperty() {
System.setProperty(KEY, PER_CLASS.name());
performAssertions(ExplicitInstancePerTestMethodTestCase.class, 2, 0, 1, "beforeAll", "test", "afterAll");
}
@Test
void instancePerMethodConfiguredViaExplicitAnnotationDeclarationThatOverridesConfigParam() {
Class<?> testClass = ExplicitInstancePerTestMethodTestCase.class;
performAssertions(testClass, Map.of(KEY, PER_CLASS.name()), 2, 0, 1, "beforeAll", "test", "afterAll");
}
private void performAssertions(Class<?> testClass, int containers, int containersFailed, int tests,
String... methods) {
performAssertions(testClass, Map.of(), containers, containersFailed, tests, methods);
}
private void performAssertions(Class<?> testClass, Map<String, String> configParams, int numContainers,
int numFailedContainers, int numTests, String... methods) {
// @formatter:off
EngineExecutionResults executionResults = executeTests(
request()
.selectors(selectClass(testClass))
.configurationParameters(configParams)
.configurationParameter(DISCOVERY_ISSUE_FAILURE_PHASE_PROPERTY_NAME, "execution")
.build()
);
// @formatter:on
executionResults.containerEvents().assertStatistics(//
stats -> stats.started(numContainers).finished(numContainers).failed(numFailedContainers));
executionResults.testEvents().assertStatistics(//
stats -> stats.started(numTests).finished(numTests));
assertEquals(Arrays.asList(methods), methodsInvoked);
}
// -------------------------------------------------------------------------
@SuppressWarnings("JUnitMalformedDeclaration")
@TestInstance(PER_METHOD)
static | TestInstanceLifecycleConfigurationTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/spi/EntityIdentifierNavigablePath.java | {
"start": 395,
"end": 2686
} | class ____ extends NavigablePath {
private final String identifierAttributeName;
public EntityIdentifierNavigablePath(NavigablePath parent, String identifierAttributeName) {
super( parent, EntityIdentifierMapping.ID_ROLE_NAME );
this.identifierAttributeName = identifierAttributeName;
}
public EntityIdentifierNavigablePath(NavigablePath parent, String alias, String identifierAttributeName) {
super( parent, EntityIdentifierMapping.ID_ROLE_NAME, alias );
this.identifierAttributeName = identifierAttributeName;
}
public String getIdentifierAttributeName() {
return identifierAttributeName;
}
@Override
public String getLocalName() {
return EntityIdentifierMapping.ID_ROLE_NAME;
}
@Override
protected boolean localNamesMatch(DotIdentifierSequence otherPath) {
final String otherLocalName = otherPath.getLocalName();
return otherLocalName.equals( getLocalName() )
|| otherLocalName.equals( identifierAttributeName );
}
@Override
protected boolean localNamesMatch(EntityIdentifierNavigablePath otherPath) {
return super.localNamesMatch( otherPath );
}
// @Override
// public int hashCode() {
// return getParent().getFullPath().hashCode();
// }
//
// @Override
// public boolean equals(Object other) {
// if ( other == null ) {
// return false;
// }
//
// if ( other == this ) {
// return true;
// }
//
// if ( ! ( other instanceof NavigablePath ) ) {
// return false;
// }
//
// final NavigablePath otherPath = (NavigablePath) other;
//
// if ( getFullPath().equals( ( (NavigablePath) other ).getFullPath() ) ) {
// return true;
// }
//
// if ( getParent() == null ) {
// if ( otherPath.getParent() != null ) {
// return false;
// }
//
// //noinspection RedundantIfStatement
// if ( localNamesMatch( otherPath) ) {
// return true;
//
// }
//
// return false;
// }
//
// if ( otherPath.getParent() == null ) {
// return false;
// }
//
// return getParent().equals( otherPath.getParent() )
// && localNamesMatch( otherPath );
// }
//
// private boolean localNamesMatch(NavigablePath otherPath) {
// final String otherLocalName = otherPath.getLocalName();
//
// return otherLocalName.equals( getLocalName() )
// || otherLocalName.equals( identifierAttributeName );
// }
}
| EntityIdentifierNavigablePath |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/http/impl/http2/multiplex/Http2MultiplexClientChannelInitializer.java | {
"start": 1681,
"end": 4781
} | class ____ implements Http2ClientChannelInitializer {
private final HttpClientMetrics<?, ?, ?> tcpMetrics;
private Http2Settings initialSettings;
private long keepAliveTimeoutMillis; // TimeUnit.SECONDS.toMillis(client.options.getHttp2KeepAliveTimeout())
private int multiplexingLimit; // client.options.getHttp2MultiplexingLimit()
private final boolean decompressionSupported;
private final boolean logEnabled;
public Http2MultiplexClientChannelInitializer(Http2Settings initialSettings,
HttpClientMetrics<?, ?, ?> tcpMetrics,
long keepAliveTimeoutMillis,
int multiplexingLimit,
boolean decompressionSupported,
boolean logEnabled) {
this.initialSettings = initialSettings;
this.keepAliveTimeoutMillis = keepAliveTimeoutMillis;
this.multiplexingLimit = multiplexingLimit;
this.decompressionSupported = decompressionSupported;
this.tcpMetrics = tcpMetrics;
this.logEnabled = logEnabled;
}
@Override
public void http2Connected(ContextInternal context, HostAndPort authority, Object connectionMetric, long maxLifetimeMillis, Channel channel, ClientMetrics<?, ?, ?> metrics, PromiseInternal<HttpClientConnection> promise) {
Http2MultiplexConnectionFactory connectionFactory = connectionFactory(context, authority, connectionMetric, maxLifetimeMillis, metrics, promise);
io.vertx.core.http.impl.http2.multiplex.Http2MultiplexHandler handler = new io.vertx.core.http.impl.http2.multiplex.Http2MultiplexHandler(channel, context, connectionFactory, initialSettings);
Http2FrameCodec http2FrameCodec = new Http2CustomFrameCodecBuilder(null, decompressionSupported).server(false)
.initialSettings(initialSettings)
.logEnabled(logEnabled)
.build();
channel.pipeline().addLast(http2FrameCodec);
channel.pipeline().addLast(new io.netty.handler.codec.http2.Http2MultiplexHandler(handler));
channel.pipeline().addLast(handler);
http2FrameCodec.connection().addListener(handler);
}
@Override
public Http2UpgradeClientConnection.Http2ChannelUpgrade channelUpgrade(Http1xClientConnection conn, long maxLifetimeMillis, ClientMetrics<?, ?, ?> clientMetrics) {
return new MultiplexChannelUpgrade(conn.metric());
}
Http2MultiplexConnectionFactory connectionFactory(ContextInternal context, HostAndPort authority, Object connectionMetric, long maxLifetimeMillis, ClientMetrics<?, ?, ?> clientMetrics, Promise<HttpClientConnection> promise) {
return (handler, chctx) -> {
Http2MultiplexClientConnection connection = new Http2MultiplexClientConnection(handler, chctx, context, clientMetrics, tcpMetrics, authority, multiplexingLimit,
keepAliveTimeoutMillis,
maxLifetimeMillis,
decompressionSupported,
promise);
connection.metric(connectionMetric);
return connection;
};
}
public | Http2MultiplexClientChannelInitializer |
java | apache__camel | components/camel-reactive-streams/src/test/java/org/apache/camel/component/reactive/streams/DelayedMonoPublisherTest.java | {
"start": 1752,
"end": 9277
} | class ____ {
private ExecutorService service;
@BeforeEach
public void init() {
service = new ScheduledThreadPoolExecutor(3);
}
@AfterEach
public void tearDown() throws Exception {
service.shutdown();
service.awaitTermination(1, TimeUnit.SECONDS);
}
@Test
public void testAlreadyAvailable() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
pub.setData(5);
LinkedList<Integer> data = new LinkedList<>();
CountDownLatch latch = new CountDownLatch(1);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(1, data.size());
assertEquals(5, data.get(0).intValue());
}
@Test
public void testExceptionAlreadyAvailable() throws Exception {
Exception ex = new RuntimeCamelException("An exception");
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
pub.setException(ex);
LinkedList<Throwable> exceptions = new LinkedList<>();
CountDownLatch latch = new CountDownLatch(1);
Flowable.fromPublisher(pub)
.subscribe(item -> {
}, e -> {
exceptions.add(e);
latch.countDown();
});
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(1, exceptions.size());
assertEquals(ex, exceptions.get(0));
}
@Test
public void testAvailableSoon() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
LinkedList<Integer> data = new LinkedList<>();
CountDownLatch latch = new CountDownLatch(1);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
Thread.yield();
pub.setData(5);
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(1, data.size());
assertEquals(5, data.get(0).intValue());
}
@Test
public void testAvailableLater() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
LinkedList<Integer> data = new LinkedList<>();
CountDownLatch latch = new CountDownLatch(1);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
Thread.sleep(200);
pub.setData(5);
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(1, data.size());
assertEquals(5, data.get(0).intValue());
}
@Test
public void testMultipleSubscribers() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
ConcurrentLinkedDeque<Integer> data = new ConcurrentLinkedDeque<>();
CountDownLatch latch = new CountDownLatch(2);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
Thread.sleep(200);
pub.setData(5);
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(2, data.size());
for (Integer n : data) {
assertEquals(5, n.intValue());
}
}
@Test
public void testMultipleSubscribersMixedArrival() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
ConcurrentLinkedDeque<Integer> data = new ConcurrentLinkedDeque<>();
CountDownLatch latch = new CountDownLatch(2);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
Thread.sleep(200);
pub.setData(5);
Flowable.fromPublisher(pub)
.doOnNext(data::add)
.doOnComplete(latch::countDown)
.subscribe();
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(2, data.size());
for (Integer n : data) {
assertEquals(5, n.intValue());
}
}
@Test
public void testMultipleSubscribersMixedArrivalException() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
Exception ex = new RuntimeCamelException("An exception");
ConcurrentLinkedDeque<Throwable> exceptions = new ConcurrentLinkedDeque<>();
CountDownLatch latch = new CountDownLatch(2);
Flowable.fromPublisher(pub)
.subscribe(item -> {
}, e -> {
exceptions.add(e);
latch.countDown();
});
Thread.sleep(200);
pub.setException(ex);
Flowable.fromPublisher(pub)
.subscribe(item -> {
}, e -> {
exceptions.add(e);
latch.countDown();
});
assertTrue(latch.await(1, TimeUnit.SECONDS));
assertEquals(2, exceptions.size());
for (Throwable t : exceptions) {
assertEquals(ex, t);
}
}
@Test
public void testDelayedRequest() throws Exception {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
pub.setData(2);
BlockingQueue<Integer> queue = new LinkedBlockingDeque<>();
TestSubscriber<Integer> sub = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer o) {
queue.add(o);
}
};
sub.setInitiallyRequested(0);
pub.subscribe(sub);
Thread.sleep(100);
sub.request(1);
Integer res = queue.poll(1, TimeUnit.SECONDS);
assertEquals(Integer.valueOf(2), res);
}
@Test
public void testDataOrExceptionAllowed() {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
Exception ex = new RuntimeCamelException("An exception");
pub.setException(ex);
assertThrows(IllegalStateException.class,
() -> pub.setData(1));
}
@Test
public void testDataOrExceptionAllowed2() {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
pub.setData(1);
Exception ex = new RuntimeCamelException("An exception");
assertThrows(IllegalStateException.class,
() -> pub.setException(ex));
}
@Test
public void testOnlyOneDataAllowed() {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
pub.setData(1);
assertThrows(IllegalStateException.class,
() -> pub.setData(2));
}
@Test
public void testOnlyOneExceptionAllowed() {
DelayedMonoPublisher<Integer> pub = new DelayedMonoPublisher<>(service);
final RuntimeCamelException runtimeException = new RuntimeCamelException("An exception");
pub.setException(runtimeException);
assertThrows(IllegalStateException.class,
() -> pub.setException(runtimeException));
}
}
| DelayedMonoPublisherTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/web/GenericXmlWebContextLoaderTests.java | {
"start": 888,
"end": 1579
} | class ____ {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
@Test
void configMustNotContainAnnotatedClasses() {
GenericXmlWebContextLoader loader = new GenericXmlWebContextLoader();
@SuppressWarnings("deprecation")
WebMergedContextConfiguration mergedConfig = new WebMergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
new Class<?>[] { getClass() }, null, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY, EMPTY_STRING_ARRAY,
"resource/path", loader, null, null);
assertThatIllegalStateException()
.isThrownBy(() -> loader.loadContext(mergedConfig))
.withMessageContaining("does not support annotated classes");
}
}
| GenericXmlWebContextLoaderTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/selection/primitives/Source.java | {
"start": 244,
"end": 668
} | class ____ {
private int primitiveInt;
private Integer wrappedInt;
public int getPrimitiveInt() {
return primitiveInt;
}
public void setPrimitiveInt( int primitiveInt ) {
this.primitiveInt = primitiveInt;
}
public Integer getWrappedInt() {
return wrappedInt;
}
public void setWrappedInt( Integer wrappedInt ) {
this.wrappedInt = wrappedInt;
}
}
| Source |
java | quarkusio__quarkus | integration-tests/hibernate-reactive-panache/src/test/java/io/quarkus/it/panache/reactive/NamedPersistenceUnitsTest.java | {
"start": 362,
"end": 582
} | class ____ {
@Test
public void testPanacheFunctionality() throws Exception {
RestAssured.when().get("/secondaryPersistenceUnit").then().body(is("mainFruit secondaryFruit"));
}
} | NamedPersistenceUnitsTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/FilterContainer.java | {
"start": 882,
"end": 926
} | class ____ javax.servlet.Filter.
*/
public | for |
java | hibernate__hibernate-orm | tooling/hibernate-maven-plugin/src/main/java/org/hibernate/orm/tooling/maven/EnhancementContext.java | {
"start": 407,
"end": 2169
} | class ____ extends DefaultEnhancementContext {
private ClassLoader classLoader = null;
private boolean enableAssociationManagement = false;
private boolean enableDirtyTracking = false;
private boolean enableLazyInitialization = false;
private boolean enableExtendedEnhancement = false;
public EnhancementContext(
ClassLoader classLoader,
boolean enableAssociationManagement,
boolean enableDirtyTracking,
boolean enableLazyInitialization,
boolean enableExtendedEnhancement) {
this.classLoader = classLoader;
this.enableAssociationManagement = enableAssociationManagement;
this.enableDirtyTracking = enableDirtyTracking;
this.enableLazyInitialization = enableLazyInitialization;
this.enableExtendedEnhancement = enableExtendedEnhancement;
}
@Override
public ClassLoader getLoadingClassLoader() {
return classLoader;
}
@Override
public boolean doBiDirectionalAssociationManagement(UnloadedField field) {
if ( enableAssociationManagement ) {
DEPRECATION_LOGGER.deprecatedSettingForRemoval( "management of bidirectional persistent association attributes", "false" );
}
return enableAssociationManagement;
}
@Override
public boolean doDirtyCheckingInline(UnloadedClass classDescriptor) {
return enableDirtyTracking;
}
@Override
public boolean hasLazyLoadableAttributes(UnloadedClass classDescriptor) {
return enableLazyInitialization;
}
@Override
public boolean isLazyLoadable(UnloadedField field) {
return enableLazyInitialization;
}
@Override
public boolean doExtendedEnhancement(UnloadedClass classDescriptor) {
if (enableExtendedEnhancement) {
DEPRECATION_LOGGER.deprecatedSettingForRemoval("extended enhancement", "false");
}
return enableExtendedEnhancement;
}
}
| EnhancementContext |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpointStats.java | {
"start": 1347,
"end": 1385
} | class ____
* been created.
*/
public | has |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/PartialConsumePipelinedResultTest.java | {
"start": 5464,
"end": 6215
} | class ____ extends AbstractInvokable {
public SingleBufferReceiver(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
InputGate gate = getEnvironment().getInputGate(0);
gate.finishReadRecoveredState();
while (!gate.getStateConsumedFuture().isDone()) {
gate.pollNext();
}
gate.setChannelStateWriter(ChannelStateWriter.NO_OP);
gate.requestPartitions();
Buffer buffer = gate.getNext().orElseThrow(IllegalStateException::new).getBuffer();
if (buffer != null) {
buffer.recycleBuffer();
}
}
}
}
| SingleBufferReceiver |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedClassIntegrationTests.java | {
"start": 64564,
"end": 67651
} | class ____ {
@BeforeParameterizedClassInvocation
static void before0() {
}
@BeforeParameterizedClassInvocation
static void before1(AtomicInteger value) {
value.incrementAndGet();
}
@BeforeParameterizedClassInvocation
static void before2(ArgumentsAccessor accessor) {
assertEquals(1, accessor.getInteger(0));
}
@BeforeParameterizedClassInvocation
static void before3(AtomicInteger value, TestInfo testInfo) {
assertEquals("[1] value = 1", testInfo.getDisplayName());
value.incrementAndGet();
}
@BeforeParameterizedClassInvocation
static void before4(ArgumentsAccessor accessor, TestInfo testInfo) {
assertEquals(1, accessor.getInteger(0));
assertEquals("[1] value = 1", testInfo.getDisplayName());
}
@BeforeParameterizedClassInvocation
static void before4(AtomicInteger value, ArgumentsAccessor accessor) {
assertEquals(1, accessor.getInteger(0));
value.incrementAndGet();
}
@BeforeParameterizedClassInvocation
static void before5(AtomicInteger value, ArgumentsAccessor accessor, TestInfo testInfo) {
assertEquals(1, accessor.getInteger(0));
assertEquals("[1] value = 1", testInfo.getDisplayName());
value.incrementAndGet();
}
@BeforeParameterizedClassInvocation
static void before6(@TimesTwo int valueTimesTwo) {
assertEquals(2, valueTimesTwo);
}
@AfterParameterizedClassInvocation
static void after(AtomicInteger value, ArgumentsAccessor accessor, TestInfo testInfo) {
assertEquals(6, value.get());
assertEquals(1, accessor.getInteger(0));
assertEquals("[1] value = 1", testInfo.getDisplayName());
}
}
@ParameterizedClass
@CsvSource("1, 2")
record LifecycleMethodWithInvalidParametersTestCase(int value, int anotherValue) {
@BeforeParameterizedClassInvocation
static void before(long value, @ConvertWith(CustomIntegerToStringConverter.class) int anotherValue) {
fail("should not be called");
}
@Test
void test() {
fail("should not be called");
}
}
@ParameterizedClass
@ValueSource(ints = 1)
record LifecycleMethodWithInvalidParameterOrderTestCase(int value) {
@BeforeParameterizedClassInvocation
static void before(ArgumentsAccessor accessor1, int value, ArgumentsAccessor accessor2) {
fail("should not be called");
}
@Test
void test() {
fail("should not be called");
}
}
@ParameterizedClass
@ValueSource(ints = 1)
record LifecycleMethodWithParameterAfterAggregatorTestCase(int value) {
@BeforeParameterizedClassInvocation
static void before(@TimesTwo int valueTimesTwo, int value) {
fail("should not be called");
}
@Test
void test() {
fail("should not be called");
}
}
@ParameterizedClass // argument sets: 13 = 2 + 4 + 1 + 1 + 1 + 1 + 1 + 1 + 1
@ArgumentsSource(CustomArgumentsProvider.class) // 2
@CsvFileSource(resources = "two-column.csv") // 4
@CsvSource("csv") // 1
@EmptySource // 1
@EnumSource(EnumOne.class) // 1
@FieldSource("field") // 1
@MethodSource("method") // 1
@NullSource // 1
@ValueSource(strings = "value") // 1
abstract static | AbstractValidLifecycleMethodInjectionTestCase |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SystemExitOutsideMainTest.java | {
"start": 2315,
"end": 2704
} | class ____ {
public void main(String[] args) {
// BUG: Diagnostic contains: SystemExitOutsideMain
System.exit(0);
}
}
""")
.doTest();
}
@Test
public void systemExitMainLookalikeDifferentReturnType() {
helper
.addSourceLines(
"Test.java",
"""
| Test |
java | apache__flink | flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/AbstractAvroBulkFormat.java | {
"start": 3451,
"end": 6707
} | class ____ implements BulkFormat.Reader<T> {
private final DataFileReader<A> reader;
private final Function<A, T> converter;
private final long end;
private final Pool<A> pool;
private long currentBlockStart;
private long currentRecordsToSkip;
private AvroReader(
Path path,
long offset,
long end,
long blockStart,
long recordsToSkip,
A reuse,
Function<A, T> converter)
throws IOException {
this.reader = createReaderFromPath(path);
if (blockStart >= 0) {
reader.seek(blockStart);
} else {
reader.sync(offset);
}
for (int i = 0; i < recordsToSkip; i++) {
reader.next(reuse);
}
this.converter = converter;
this.end = end;
this.pool = new Pool<>(1);
this.pool.add(reuse);
this.currentBlockStart = reader.previousSync();
this.currentRecordsToSkip = recordsToSkip;
}
private DataFileReader<A> createReaderFromPath(Path path) throws IOException {
FileSystem fileSystem = path.getFileSystem();
DatumReader<A> datumReader = new GenericDatumReader<>(null, readerSchema);
SeekableInput in =
new FSDataInputStreamWrapper(
fileSystem.open(path), fileSystem.getFileStatus(path).getLen());
return (DataFileReader<A>) DataFileReader.openReader(in, datumReader);
}
@Nullable
@Override
public RecordIterator<T> readBatch() throws IOException {
A reuse;
try {
reuse = pool.pollEntry();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(
"Interrupted while waiting for the previous batch to be consumed", e);
}
if (!readNextBlock()) {
pool.recycler().recycle(reuse);
return null;
}
currentBlockStart = reader.previousSync();
Iterator<T> iterator =
new AvroBlockIterator(
reader.getBlockCount() - currentRecordsToSkip,
reader,
reuse,
converter);
long recordsToSkip = currentRecordsToSkip;
currentRecordsToSkip = 0;
return new IteratorResultIterator<>(
iterator,
currentBlockStart,
recordsToSkip,
() -> pool.recycler().recycle(reuse));
}
private boolean readNextBlock() throws IOException {
// read the next block with reader,
// returns true if a block is read and false if we reach the end of this split
return reader.hasNext() && !reader.pastSync(end);
}
@Override
public void close() throws IOException {
reader.close();
}
}
private | AvroReader |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/SSLHandlerFactory.java | {
"start": 1223,
"end": 3126
} | class ____ {
private final SslContext sslContext;
private final int handshakeTimeoutMs;
private final int closeNotifyFlushTimeoutMs;
/**
* Create a new {@link SslHandler} factory.
*
* @param handshakeTimeoutMs SSL session timeout during handshakes (-1 = use system default)
* @param closeNotifyFlushTimeoutMs SSL session timeout after flushing the <tt>close_notify</tt>
* message (-1 = use system default)
*/
public SSLHandlerFactory(
final SslContext sslContext,
final int handshakeTimeoutMs,
final int closeNotifyFlushTimeoutMs) {
this.sslContext = requireNonNull(sslContext, "sslContext must not be null");
this.handshakeTimeoutMs = handshakeTimeoutMs;
this.closeNotifyFlushTimeoutMs = closeNotifyFlushTimeoutMs;
}
public SslHandler createNettySSLHandler(ByteBufAllocator allocator) {
return createNettySSLHandler(createSSLEngine(allocator));
}
public SslHandler createNettySSLHandler(ByteBufAllocator allocator, String hostname, int port) {
return createNettySSLHandler(createSSLEngine(allocator, hostname, port));
}
private SslHandler createNettySSLHandler(SSLEngine sslEngine) {
SslHandler sslHandler = new SslHandler(sslEngine);
if (handshakeTimeoutMs >= 0) {
sslHandler.setHandshakeTimeoutMillis(handshakeTimeoutMs);
}
if (closeNotifyFlushTimeoutMs >= 0) {
sslHandler.setCloseNotifyFlushTimeoutMillis(closeNotifyFlushTimeoutMs);
}
return sslHandler;
}
private SSLEngine createSSLEngine(ByteBufAllocator allocator) {
return sslContext.newEngine(allocator);
}
private SSLEngine createSSLEngine(ByteBufAllocator allocator, String hostname, int port) {
return sslContext.newEngine(allocator, hostname, port);
}
}
| SSLHandlerFactory |
java | playframework__playframework | core/play/src/main/java/play/server/SSLEngineProvider.java | {
"start": 544,
"end": 687
} | class ____ ApplicationProvider in the constructor, then the applicationProvider is
* passed into it, if available.
*
* <p>The path to this | takes |
java | google__gson | gson/src/test/java/com/google/gson/functional/TypeVariableTest.java | {
"start": 2805,
"end": 3044
} | class ____<S> {
protected S redField;
public Red() {}
public Red(S redField) {
this.redField = redField;
}
}
@SuppressWarnings({"overrides", "EqualsHashCode"}) // for missing hashCode() override
public static | Red |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LumberjackEndpointBuilderFactory.java | {
"start": 1575,
"end": 3008
} | interface ____
extends
EndpointConsumerBuilder {
default AdvancedLumberjackEndpointBuilder advanced() {
return (AdvancedLumberjackEndpointBuilder) this;
}
/**
* SSL configuration.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: consumer
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default LumberjackEndpointBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* SSL configuration.
*
* The option will be converted to a
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: consumer
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default LumberjackEndpointBuilder sslContextParameters(String sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
}
/**
* Advanced builder for endpoint for the Lumberjack component.
*/
public | LumberjackEndpointBuilder |
java | micronaut-projects__micronaut-core | jackson-databind/src/test/groovy/io/micronaut/jackson/modules/testclasses/HTTPCheck.java | {
"start": 488,
"end": 1359
} | class ____ {
private ConvertibleMultiValues<String> headers = ConvertibleMultiValues.empty();
public ConvertibleMultiValues<String> getHeader() {
return headers;
}
/**
* @param headers The headers
*/
@JsonProperty("Header")
public void setHeaders(Map<CharSequence, List<String>> headers) {
if (headers == null) {
this.headers = ConvertibleMultiValues.empty();
} else {
this.headers = ConvertibleMultiValues.of(headers);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HTTPCheck httpCheck = (HTTPCheck) o;
return headers.equals(httpCheck.headers);
}
@Override
public int hashCode() {
return Objects.hash(headers);
}
}
| HTTPCheck |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/MapInterfaceTest.java | {
"start": 3173,
"end": 44933
} | class ____ test.
*/
protected abstract Map<K, V> makePopulatedMap() throws UnsupportedOperationException;
/**
* Creates a new key that is not expected to be found in {@link #makePopulatedMap()}.
*
* @return a key.
* @throws UnsupportedOperationException if it's not possible to make a key that will not be found
* in the map.
*/
protected abstract K getKeyNotInPopulatedMap() throws UnsupportedOperationException;
/**
* Creates a new value that is not expected to be found in {@link #makePopulatedMap()}.
*
* @return a value.
* @throws UnsupportedOperationException if it's not possible to make a value that will not be
* found in the map.
*/
protected abstract V getValueNotInPopulatedMap() throws UnsupportedOperationException;
/**
* Constructor that assigns {@code supportsIteratorRemove} the same value as {@code
* supportsRemove}.
*/
protected MapInterfaceTest(
boolean allowsNullKeys,
boolean allowsNullValues,
boolean supportsPut,
boolean supportsRemove,
boolean supportsClear) {
this(
allowsNullKeys,
allowsNullValues,
supportsPut,
supportsRemove,
supportsClear,
supportsRemove);
}
/** Constructor with an explicit {@code supportsIteratorRemove} parameter. */
protected MapInterfaceTest(
boolean allowsNullKeys,
boolean allowsNullValues,
boolean supportsPut,
boolean supportsRemove,
boolean supportsClear,
boolean supportsIteratorRemove) {
this.supportsPut = supportsPut;
this.supportsRemove = supportsRemove;
this.supportsClear = supportsClear;
this.allowsNullKeys = allowsNullKeys;
this.allowsNullValues = allowsNullValues;
this.supportsIteratorRemove = supportsIteratorRemove;
}
/**
* Used by tests that require a map, but don't care whether it's populated or not.
*
* @return a new map instance.
*/
protected Map<K, V> makeEitherMap() {
try {
return makePopulatedMap();
} catch (UnsupportedOperationException e) {
return makeEmptyMap();
}
}
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
protected final boolean supportsValuesHashCode(Map<K, V> map) {
// get the first non-null value
Collection<V> values = map.values();
for (V value : values) {
if (value != null) {
try {
int unused = value.hashCode();
} catch (Exception e) { // sneaky checked exception
return false;
}
return true;
}
}
return true;
}
/**
* Checks all the properties that should always hold of a map. Also calls {@link
* #assertMoreInvariants} to check invariants that are peculiar to specific implementations.
*
* @see #assertMoreInvariants
* @param map the map to check.
*/
protected final void assertInvariants(Map<K, V> map) {
Set<K> keySet = map.keySet();
Collection<V> valueCollection = map.values();
Set<Entry<K, V>> entrySet = map.entrySet();
assertEquals(map.size() == 0, map.isEmpty());
assertEquals(map.size(), keySet.size());
assertEquals(keySet.size() == 0, keySet.isEmpty());
assertEquals(!keySet.isEmpty(), keySet.iterator().hasNext());
int expectedKeySetHash = 0;
for (K key : keySet) {
V value = map.get(key);
expectedKeySetHash += key != null ? key.hashCode() : 0;
assertTrue(map.containsKey(key));
assertTrue(map.containsValue(value));
assertTrue(valueCollection.contains(value));
assertTrue(valueCollection.containsAll(singleton(value)));
assertTrue(entrySet.contains(mapEntry(key, value)));
assertTrue(allowsNullKeys || (key != null));
}
assertEquals(expectedKeySetHash, keySet.hashCode());
assertEquals(map.size(), valueCollection.size());
assertEquals(valueCollection.size() == 0, valueCollection.isEmpty());
assertEquals(!valueCollection.isEmpty(), valueCollection.iterator().hasNext());
for (V value : valueCollection) {
assertTrue(map.containsValue(value));
assertTrue(allowsNullValues || (value != null));
}
assertEquals(map.size(), entrySet.size());
assertEquals(entrySet.size() == 0, entrySet.isEmpty());
assertEquals(!entrySet.isEmpty(), entrySet.iterator().hasNext());
assertEntrySetNotContainsString(entrySet);
boolean supportsValuesHashCode = supportsValuesHashCode(map);
if (supportsValuesHashCode) {
int expectedEntrySetHash = 0;
for (Entry<K, V> entry : entrySet) {
assertTrue(map.containsKey(entry.getKey()));
assertTrue(map.containsValue(entry.getValue()));
int expectedHash =
(entry.getKey() == null ? 0 : entry.getKey().hashCode())
^ (entry.getValue() == null ? 0 : entry.getValue().hashCode());
assertEquals(expectedHash, entry.hashCode());
expectedEntrySetHash += expectedHash;
}
assertEquals(expectedEntrySetHash, entrySet.hashCode());
assertTrue(entrySet.containsAll(new HashSet<Entry<K, V>>(entrySet)));
assertTrue(entrySet.equals(new HashSet<Entry<K, V>>(entrySet)));
}
Object[] entrySetToArray1 = entrySet.toArray();
assertEquals(map.size(), entrySetToArray1.length);
assertTrue(asList(entrySetToArray1).containsAll(entrySet));
Entry<?, ?>[] entrySetToArray2 = new Entry<?, ?>[map.size() + 2];
entrySetToArray2[map.size()] = mapEntry("foo", 1);
assertSame(entrySetToArray2, entrySet.toArray(entrySetToArray2));
assertNull(entrySetToArray2[map.size()]);
assertTrue(asList(entrySetToArray2).containsAll(entrySet));
Object[] valuesToArray1 = valueCollection.toArray();
assertEquals(map.size(), valuesToArray1.length);
assertTrue(asList(valuesToArray1).containsAll(valueCollection));
Object[] valuesToArray2 = new Object[map.size() + 2];
valuesToArray2[map.size()] = "foo";
assertSame(valuesToArray2, valueCollection.toArray(valuesToArray2));
assertNull(valuesToArray2[map.size()]);
assertTrue(asList(valuesToArray2).containsAll(valueCollection));
if (supportsValuesHashCode) {
int expectedHash = 0;
for (Entry<K, V> entry : entrySet) {
expectedHash += entry.hashCode();
}
assertEquals(expectedHash, map.hashCode());
}
assertMoreInvariants(map);
}
@SuppressWarnings("CollectionIncompatibleType")
private void assertEntrySetNotContainsString(Set<Entry<K, V>> entrySet) {
// Very unlikely that a buggy collection would ever return true. It might accidentally throw.
assertFalse(entrySet.contains("foo"));
}
/**
* Override this to check invariants which should hold true for a particular implementation, but
* which are not generally applicable to every instance of Map.
*
* @param map the map whose additional invariants to check.
*/
protected void assertMoreInvariants(Map<K, V> map) {}
public void testClear() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsClear) {
map.clear();
assertTrue(map.isEmpty());
} else {
assertThrows(UnsupportedOperationException.class, map::clear);
}
assertInvariants(map);
}
@J2ktIncompatible // https://youtrack.jetbrains.com/issue/KT-58242/ undefined behavior (crash)
public void testContainsKey() {
Map<K, V> map;
K unmappedKey;
try {
map = makePopulatedMap();
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.containsKey(unmappedKey));
try {
assertFalse(map.containsKey(new IncompatibleKeyType()));
} catch (ClassCastException tolerated) {
}
assertTrue(map.containsKey(map.keySet().iterator().next()));
if (allowsNullKeys) {
boolean unused = map.containsKey(null);
} else {
try {
boolean unused2 = map.containsKey(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testContainsValue() {
Map<K, V> map;
V unmappedValue;
try {
map = makePopulatedMap();
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.containsValue(unmappedValue));
assertTrue(map.containsValue(map.values().iterator().next()));
if (allowsNullValues) {
boolean unused = map.containsValue(null);
} else {
try {
boolean unused2 = map.containsKey(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testEntrySet() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Set<Entry<K, V>> entrySet = map.entrySet();
K unmappedKey;
V unmappedValue;
try {
unmappedKey = getKeyNotInPopulatedMap();
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (Entry<K, V> entry : entrySet) {
assertFalse(unmappedKey.equals(entry.getKey()));
assertFalse(unmappedValue.equals(entry.getValue()));
}
}
public void testEntrySetForEmptyMap() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
@J2ktIncompatible // https://youtrack.jetbrains.com/issue/KT-58242/ undefined behavior (crash)
public void testEntrySetContainsEntryIncompatibleKey() {
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Set<Entry<K, V>> entrySet = map.entrySet();
V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Entry<IncompatibleKeyType, V> entry = mapEntry(new IncompatibleKeyType(), unmappedValue);
try {
assertFalse(entrySet.contains(entry));
} catch (ClassCastException tolerated) {
}
}
public void testEntrySetContainsEntryNullKeyPresent() {
if (!allowsNullKeys || !supportsPut) {
return;
}
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Set<Entry<K, V>> entrySet = map.entrySet();
V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
map.put(null, unmappedValue);
Entry<@Nullable K, V> entry = mapEntry(null, unmappedValue);
assertTrue(entrySet.contains(entry));
Entry<@Nullable K, @Nullable V> nonEntry = mapEntry(null, null);
assertFalse(entrySet.contains(nonEntry));
}
public void testEntrySetContainsEntryNullKeyMissing() {
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Set<Entry<K, V>> entrySet = map.entrySet();
V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Entry<@Nullable K, V> nullKeyEntry = mapEntry(null, unmappedValue);
try {
assertFalse(entrySet.contains(nullKeyEntry));
} catch (NullPointerException e) {
assertFalse(allowsNullKeys);
}
Entry<@Nullable K, @Nullable V> nullKeyValueEntry = mapEntry(null, null);
try {
assertFalse(entrySet.contains(nullKeyValueEntry));
} catch (NullPointerException e) {
assertFalse(allowsNullKeys && allowsNullValues);
}
}
public void testEntrySetIteratorRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Iterator<Entry<K, V>> iterator = entrySet.iterator();
if (supportsIteratorRemove) {
int initialSize = map.size();
Entry<K, V> entry = iterator.next();
Entry<K, V> entryCopy = mapEntry(entry.getKey(), entry.getValue());
iterator.remove();
assertEquals(initialSize - 1, map.size());
// Use "entryCopy" instead of "entry" because "entry" might be invalidated after
// iterator.remove().
assertFalse(entrySet.contains(entryCopy));
assertInvariants(map);
assertThrows(IllegalStateException.class, iterator::remove);
} else {
iterator.next();
assertThrows(UnsupportedOperationException.class, iterator::remove);
}
assertInvariants(map);
}
public void testEntrySetRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
int initialSize = map.size();
boolean didRemove = entrySet.remove(entrySet.iterator().next());
assertTrue(didRemove);
assertEquals(initialSize - 1, map.size());
} else {
assertThrows(
UnsupportedOperationException.class, () -> entrySet.remove(entrySet.iterator().next()));
}
assertInvariants(map);
}
public void testEntrySetRemoveMissingKey() {
Map<K, V> map;
K key;
try {
map = makeEitherMap();
key = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry = mapEntry(key, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {
}
}
assertEquals(initialSize, map.size());
assertFalse(map.containsKey(key));
assertInvariants(map);
}
public void testEntrySetRemoveDifferentValue() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
K key = map.keySet().iterator().next();
Entry<K, V> entry = mapEntry(key, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {
}
}
assertEquals(initialSize, map.size());
assertTrue(map.containsKey(key));
assertInvariants(map);
}
public void testEntrySetRemoveNullKeyPresent() {
if (!allowsNullKeys || !supportsPut || !supportsRemove) {
return;
}
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Set<Entry<K, V>> entrySet = map.entrySet();
V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
map.put(null, unmappedValue);
assertEquals(unmappedValue, map.get(null));
assertTrue(map.containsKey(null));
Entry<@Nullable K, V> entry = mapEntry(null, unmappedValue);
assertTrue(entrySet.remove(entry));
assertNull(map.get(null));
assertFalse(map.containsKey(null));
}
public void testEntrySetRemoveNullKeyMissing() {
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<@Nullable K, V> entry = mapEntry(null, getValueNotInPopulatedMap());
int initialSize = map.size();
if (supportsRemove) {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (NullPointerException e) {
assertFalse(allowsNullKeys);
}
} else {
try {
boolean didRemove = entrySet.remove(entry);
assertFalse(didRemove);
} catch (UnsupportedOperationException optional) {
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testEntrySetRemoveAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entryToRemove = entrySet.iterator().next();
Set<Entry<K, V>> entriesToRemove = singleton(entryToRemove);
if (supportsRemove) {
// We use a copy of "entryToRemove" in the assertion because "entryToRemove" might be
// invalidated and have undefined behavior after entrySet.removeAll(entriesToRemove),
// for example entryToRemove.getValue() might be null.
Entry<K, V> entryToRemoveCopy = mapEntry(entryToRemove.getKey(), entryToRemove.getValue());
int initialSize = map.size();
boolean didRemove = entrySet.removeAll(entriesToRemove);
assertTrue(didRemove);
assertEquals(initialSize - entriesToRemove.size(), map.size());
// Use "entryToRemoveCopy" instead of "entryToRemove" because it might be invalidated and
// have undefined behavior after entrySet.removeAll(entriesToRemove),
assertFalse(entrySet.contains(entryToRemoveCopy));
} else {
assertThrows(UnsupportedOperationException.class, () -> entrySet.removeAll(entriesToRemove));
}
assertInvariants(map);
}
public void testEntrySetRemoveAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
assertThrows(NullPointerException.class, () -> entrySet.removeAll(null));
} else {
try {
entrySet.removeAll(null);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetRetainAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> originalEntry = entrySet.iterator().next();
// Copy the Entry, as discussed in testEntrySetRemoveAll.
Set<Entry<K, V>> entriesToRetain =
singleton(mapEntry(originalEntry.getKey(), originalEntry.getValue()));
if (supportsRemove) {
boolean shouldRemove = entrySet.size() > entriesToRetain.size();
boolean didRemove = entrySet.retainAll(entriesToRetain);
assertEquals(shouldRemove, didRemove);
assertEquals(entriesToRetain.size(), map.size());
for (Entry<K, V> entry : entriesToRetain) {
assertTrue(entrySet.contains(entry));
}
} else {
assertThrows(UnsupportedOperationException.class, () -> entrySet.retainAll(entriesToRetain));
}
assertInvariants(map);
}
public void testEntrySetRetainAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsRemove) {
try {
entrySet.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException tolerated) {
}
} else {
try {
entrySet.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testEntrySetClear() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
if (supportsClear) {
entrySet.clear();
assertTrue(entrySet.isEmpty());
} else {
assertThrows(UnsupportedOperationException.class, entrySet::clear);
}
assertInvariants(map);
}
public void testEntrySetAddAndAddAll() {
Map<K, V> map = makeEitherMap();
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<@Nullable K, @Nullable V> entryToAdd = mapEntry(null, null);
try {
entrySet.add((Entry<K, V>) entryToAdd);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
assertInvariants(map);
try {
entrySet.addAll(singleton((Entry<K, V>) entryToAdd));
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
assertInvariants(map);
}
public void testEntrySetSetValue() {
// TODO: Investigate the extent to which, in practice, maps that support
// put() also support Entry.setValue().
if (!supportsPut) {
return;
}
Map<K, V> map;
V valueToSet;
try {
map = makePopulatedMap();
valueToSet = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry = entrySet.iterator().next();
V oldValue = entry.getValue();
V returnedValue = entry.setValue(valueToSet);
assertEquals(oldValue, returnedValue);
assertTrue(entrySet.contains(mapEntry(entry.getKey(), valueToSet)));
assertEquals(valueToSet, map.get(entry.getKey()));
assertInvariants(map);
}
public void testEntrySetSetValueSameValue() {
// TODO: Investigate the extent to which, in practice, maps that support
// put() also support Entry.setValue().
if (!supportsPut) {
return;
}
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<Entry<K, V>> entrySet = map.entrySet();
Entry<K, V> entry = entrySet.iterator().next();
V oldValue = entry.getValue();
V returnedValue = entry.setValue(oldValue);
assertEquals(oldValue, returnedValue);
assertTrue(entrySet.contains(mapEntry(entry.getKey(), oldValue)));
assertEquals(oldValue, map.get(entry.getKey()));
assertInvariants(map);
}
public void testEqualsForEqualMap() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
// Explicitly call `equals`; `assertEquals` might return fast
assertTrue(map.equals(map));
assertTrue(makePopulatedMap().equals(map));
assertFalse(map.equals(emptyMap()));
// no-inspection ObjectEqualsNull
assertFalse(map.equals(null));
}
public void testEqualsForLargerMap() {
if (!supportsPut) {
return;
}
Map<K, V> map;
Map<K, V> largerMap;
try {
map = makePopulatedMap();
largerMap = makePopulatedMap();
largerMap.put(getKeyNotInPopulatedMap(), getValueNotInPopulatedMap());
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.equals(largerMap));
}
public void testEqualsForSmallerMap() {
if (!supportsRemove) {
return;
}
Map<K, V> map;
Map<K, V> smallerMap;
try {
map = makePopulatedMap();
smallerMap = makePopulatedMap();
smallerMap.remove(smallerMap.keySet().iterator().next());
} catch (UnsupportedOperationException e) {
return;
}
assertFalse(map.equals(smallerMap));
}
public void testEqualsForEmptyMap() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
// Explicitly call `equals`; `assertEquals` might return fast
assertTrue(map.equals(map));
assertTrue(makeEmptyMap().equals(map));
assertEquals(emptyMap(), map);
assertFalse(map.equals(emptySet()));
// noinspection ObjectEqualsNull
assertFalse(map.equals(null));
}
public void testGet() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (Entry<K, V> entry : map.entrySet()) {
assertEquals(entry.getValue(), map.get(entry.getKey()));
}
K unmappedKey = null;
try {
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertNull(map.get(unmappedKey));
}
public void testGetForEmptyMap() {
Map<K, V> map;
K unmappedKey = null;
try {
map = makeEmptyMap();
unmappedKey = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertNull(map.get(unmappedKey));
}
public void testGetNull() {
Map<K, V> map = makeEitherMap();
if (allowsNullKeys) {
if (allowsNullValues) {
// TODO: decide what to test here.
} else {
assertEquals(map.containsKey(null), map.get(null) != null);
}
} else {
try {
V unused = map.get(null);
} catch (NullPointerException optional) {
}
}
assertInvariants(map);
}
public void testHashCode() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
public void testHashCodeForEmptyMap() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
}
public void testPutNewKey() {
Map<K, V> map = makeEitherMap();
K keyToPut;
V valueToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsPut) {
int initialSize = map.size();
V oldValue = map.put(keyToPut, valueToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize + 1, map.size());
assertNull(oldValue);
} else {
assertThrows(UnsupportedOperationException.class, () -> map.put(keyToPut, valueToPut));
}
assertInvariants(map);
}
public void testPutExistingKey() {
Map<K, V> map;
V valueToPut;
try {
map = makePopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
K keyToPut = map.keySet().iterator().next();
if (supportsPut) {
int initialSize = map.size();
map.put(keyToPut, valueToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize, map.size());
} else {
assertThrows(UnsupportedOperationException.class, () -> map.put(keyToPut, valueToPut));
}
assertInvariants(map);
}
public void testPutNullKey() {
if (!supportsPut) {
return;
}
Map<K, V> map = makeEitherMap();
V valueToPut;
try {
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullKeys) {
V oldValue = map.get(null);
V returnedValue = map.put(null, valueToPut);
assertEquals(oldValue, returnedValue);
assertEquals(valueToPut, map.get(null));
assertTrue(map.containsKey(null));
assertTrue(map.containsValue(valueToPut));
} else {
assertThrows(RuntimeException.class, () -> map.put(null, valueToPut));
}
assertInvariants(map);
}
public void testPutNullValue() {
if (!supportsPut) {
return;
}
Map<K, V> map = makeEitherMap();
K keyToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullValues) {
int initialSize = map.size();
V oldValue = map.get(keyToPut);
V returnedValue = map.put(keyToPut, null);
assertEquals(oldValue, returnedValue);
assertNull(map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(null));
assertEquals(initialSize + 1, map.size());
} else {
assertThrows(RuntimeException.class, () -> map.put(keyToPut, null));
}
assertInvariants(map);
}
public void testPutNullValueForExistingKey() {
if (!supportsPut) {
return;
}
Map<K, V> map;
K keyToPut;
try {
map = makePopulatedMap();
keyToPut = map.keySet().iterator().next();
} catch (UnsupportedOperationException e) {
return;
}
if (allowsNullValues) {
int initialSize = map.size();
V oldValue = map.get(keyToPut);
V returnedValue = map.put(keyToPut, null);
assertEquals(oldValue, returnedValue);
assertNull(map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(null));
assertEquals(initialSize, map.size());
} else {
assertThrows(RuntimeException.class, () -> map.put(keyToPut, null));
}
assertInvariants(map);
}
public void testPutAllNewKey() {
Map<K, V> map = makeEitherMap();
K keyToPut;
V valueToPut;
try {
keyToPut = getKeyNotInPopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Map<K, V> mapToPut = singletonMap(keyToPut, valueToPut);
if (supportsPut) {
int initialSize = map.size();
map.putAll(mapToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
assertEquals(initialSize + 1, map.size());
} else {
assertThrows(UnsupportedOperationException.class, () -> map.putAll(mapToPut));
}
assertInvariants(map);
}
public void testPutAllExistingKey() {
Map<K, V> map;
V valueToPut;
try {
map = makePopulatedMap();
valueToPut = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
K keyToPut = map.keySet().iterator().next();
Map<K, V> mapToPut = singletonMap(keyToPut, valueToPut);
int initialSize = map.size();
if (supportsPut) {
map.putAll(mapToPut);
assertEquals(valueToPut, map.get(keyToPut));
assertTrue(map.containsKey(keyToPut));
assertTrue(map.containsValue(valueToPut));
} else {
assertThrows(UnsupportedOperationException.class, () -> map.putAll(mapToPut));
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
K keyToRemove = map.keySet().iterator().next();
if (supportsRemove) {
int initialSize = map.size();
V expectedValue = map.get(keyToRemove);
V oldValue = map.remove(keyToRemove);
assertEquals(expectedValue, oldValue);
assertFalse(map.containsKey(keyToRemove));
assertEquals(initialSize - 1, map.size());
} else {
assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove));
}
assertInvariants(map);
}
public void testRemoveMissingKey() {
Map<K, V> map;
K keyToRemove;
try {
map = makePopulatedMap();
keyToRemove = getKeyNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
if (supportsRemove) {
int initialSize = map.size();
assertNull(map.remove(keyToRemove));
assertEquals(initialSize, map.size());
} else {
assertThrows(UnsupportedOperationException.class, () -> map.remove(keyToRemove));
}
assertInvariants(map);
}
public void testSize() {
assertInvariants(makeEitherMap());
}
public void testKeySetRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
int initialSize = map.size();
keys.remove(key);
assertEquals(initialSize - 1, map.size());
assertFalse(map.containsKey(key));
} else {
assertThrows(UnsupportedOperationException.class, () -> keys.remove(key));
}
assertInvariants(map);
}
public void testKeySetRemoveAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
int initialSize = map.size();
assertTrue(keys.removeAll(singleton(key)));
assertEquals(initialSize - 1, map.size());
assertFalse(map.containsKey(key));
} else {
assertThrows(UnsupportedOperationException.class, () -> keys.removeAll(singleton(key)));
}
assertInvariants(map);
}
public void testKeySetRetainAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keys = map.keySet();
K key = keys.iterator().next();
if (supportsRemove) {
keys.retainAll(singleton(key));
assertEquals(1, map.size());
assertTrue(map.containsKey(key));
} else {
assertThrows(UnsupportedOperationException.class, () -> keys.retainAll(singleton(key)));
}
assertInvariants(map);
}
public void testKeySetClear() {
Map<K, V> map;
try {
map = makeEitherMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsClear) {
keySet.clear();
assertTrue(keySet.isEmpty());
} else {
assertThrows(UnsupportedOperationException.class, keySet::clear);
}
assertInvariants(map);
}
public void testKeySetRemoveAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsRemove) {
assertThrows(NullPointerException.class, () -> keySet.removeAll(null));
} else {
try {
keySet.removeAll(null);
fail("Expected UnsupportedOperationException or NullPointerException.");
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testKeySetRetainAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Set<K> keySet = map.keySet();
if (supportsRemove) {
try {
keySet.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException tolerated) {
}
} else {
try {
keySet.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValues() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
assertInvariants(map);
Collection<V> valueCollection = map.values();
V unmappedValue;
try {
unmappedValue = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
for (V value : valueCollection) {
assertFalse(unmappedValue.equals(value));
}
}
public void testValuesIteratorRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Iterator<V> iterator = valueCollection.iterator();
if (supportsIteratorRemove) {
int initialSize = map.size();
iterator.next();
iterator.remove();
assertEquals(initialSize - 1, map.size());
// (We can't assert that the values collection no longer contains the
// removed value, because the underlying map can have multiple mappings
// to the same value.)
assertInvariants(map);
assertThrows(IllegalStateException.class, iterator::remove);
} else {
iterator.next();
assertThrows(UnsupportedOperationException.class, iterator::remove);
}
assertInvariants(map);
}
public void testValuesRemove() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
if (supportsRemove) {
int initialSize = map.size();
valueCollection.remove(valueCollection.iterator().next());
assertEquals(initialSize - 1, map.size());
// (We can't assert that the values collection no longer contains the
// removed value, because the underlying map can have multiple mappings
// to the same value.)
} else {
assertThrows(
UnsupportedOperationException.class,
() -> valueCollection.remove(valueCollection.iterator().next()));
}
assertInvariants(map);
}
public void testValuesRemoveMissing() {
Map<K, V> map;
V valueToRemove;
try {
map = makeEitherMap();
valueToRemove = getValueNotInPopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
int initialSize = map.size();
if (supportsRemove) {
assertFalse(valueCollection.remove(valueToRemove));
} else {
try {
assertFalse(valueCollection.remove(valueToRemove));
} catch (UnsupportedOperationException e) {
// Tolerated.
}
}
assertEquals(initialSize, map.size());
assertInvariants(map);
}
public void testValuesRemoveAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Set<V> valuesToRemove = singleton(valueCollection.iterator().next());
if (supportsRemove) {
valueCollection.removeAll(valuesToRemove);
for (V value : valuesToRemove) {
assertFalse(valueCollection.contains(value));
}
for (V value : valueCollection) {
assertFalse(valuesToRemove.contains(value));
}
} else {
assertThrows(
UnsupportedOperationException.class, () -> valueCollection.removeAll(valuesToRemove));
}
assertInvariants(map);
}
public void testValuesRemoveAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> values = map.values();
if (supportsRemove) {
try {
values.removeAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException tolerated) {
}
} else {
try {
values.removeAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesRetainAll() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
Set<V> valuesToRetain = singleton(valueCollection.iterator().next());
if (supportsRemove) {
valueCollection.retainAll(valuesToRetain);
for (V value : valuesToRetain) {
assertTrue(valueCollection.contains(value));
}
for (V value : valueCollection) {
assertTrue(valuesToRetain.contains(value));
}
} else {
assertThrows(
UnsupportedOperationException.class, () -> valueCollection.retainAll(valuesToRetain));
}
assertInvariants(map);
}
public void testValuesRetainAllNullFromEmpty() {
Map<K, V> map;
try {
map = makeEmptyMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> values = map.values();
if (supportsRemove) {
try {
values.retainAll(null);
// Returning successfully is not ideal, but tolerated.
} catch (NullPointerException tolerated) {
}
} else {
try {
values.retainAll(null);
// We have to tolerate a successful return (Sun bug 4802647)
} catch (UnsupportedOperationException | NullPointerException e) {
// Expected.
}
}
assertInvariants(map);
}
public void testValuesClear() {
Map<K, V> map;
try {
map = makePopulatedMap();
} catch (UnsupportedOperationException e) {
return;
}
Collection<V> valueCollection = map.values();
if (supportsClear) {
valueCollection.clear();
assertTrue(valueCollection.isEmpty());
} else {
assertThrows(UnsupportedOperationException.class, valueCollection::clear);
}
assertInvariants(map);
}
}
| under |
java | elastic__elasticsearch | modules/transport-netty4/src/internalClusterTest/java/org/elasticsearch/http/netty4/Netty4PipeliningIT.java | {
"start": 18984,
"end": 20948
} | class ____ extends Plugin implements ActionPlugin {
static final String ROUTE = "/_test/countdown_3";
@Override
public Collection<RestHandler> getRestHandlers(
Settings settings,
NamedWriteableRegistry namedWriteableRegistry,
RestController restController,
ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings,
SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster,
Predicate<NodeFeature> clusterSupportsFeature
) {
return List.of(new BaseRestHandler() {
private final SubscribableListener<ToXContentObject> subscribableListener = new SubscribableListener<>();
private final CountDownActionListener countDownActionListener = new CountDownActionListener(
3,
subscribableListener.map(v -> EMPTY_RESPONSE)
);
private void addListener(ActionListener<ToXContentObject> listener) {
subscribableListener.addListener(listener);
countDownActionListener.onResponse(null);
}
@Override
public String getName() {
return ROUTE;
}
@Override
public List<Route> routes() {
return List.of(new Route(GET, ROUTE));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
return channel -> addListener(new RestToXContentListener<>(channel));
}
});
}
}
/**
* Adds an HTTP route that starts to emit a chunked response and then fails before its completion.
*/
public static | CountDown3Plugin |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsOnlyNulls_Test.java | {
"start": 1517,
"end": 3467
} | class ____ extends IterablesBaseTest {
private List<String> actual = new ArrayList<>();
@Test
void should_pass_if_actual_contains_null_once() {
actual.add(null);
iterables.assertContainsOnlyNulls(someInfo(), actual);
}
@Test
void should_pass_if_actual_contains_null_more_than_once() {
actual = newArrayList(null, null, null);
iterables.assertContainsOnlyNulls(someInfo(), actual);
}
@Test
void should_fail_if_actual_is_null() {
actual = null;
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> iterables.assertContainsOnlyNulls(someInfo(), actual))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_actual_is_empty() {
AssertionInfo info = someInfo();
Throwable error = catchThrowable(() -> iterables.assertContainsOnlyNulls(info, actual));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainOnlyNulls(actual));
}
@Test
void should_fail_if_actual_contains_null_and_non_null_elements() {
AssertionInfo info = someInfo();
actual = newArrayList(null, null, "person");
List<String> nonNulls = newArrayList("person");
Throwable error = catchThrowable(() -> iterables.assertContainsOnlyNulls(info, actual));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainOnlyNulls(actual, nonNulls));
}
@Test
void should_fail_if_actual_contains_non_null_elements_only() {
AssertionInfo info = someInfo();
actual = newArrayList("person", "person2");
List<String> nonNulls = newArrayList("person", "person2");
Throwable error = catchThrowable(() -> iterables.assertContainsOnlyNulls(info, actual));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainOnlyNulls(actual, nonNulls));
}
}
| Iterables_assertContainsOnlyNulls_Test |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/FunctionParameterType.java | {
"start": 491,
"end": 3027
} | enum ____ {
/**
* @see org.hibernate.type.SqlTypes#isCharacterType(int)
*/
STRING,
/**
* @see org.hibernate.type.SqlTypes#isNumericType(int)
*/
NUMERIC,
/**
* @see org.hibernate.type.SqlTypes#isIntegral(int)
*/
INTEGER,
/**
* @see org.hibernate.type.SqlTypes#isTemporalType(int)
*/
TEMPORAL,
/**
* @see org.hibernate.type.SqlTypes#hasDatePart(int)
*/
DATE,
/**
* @see org.hibernate.type.SqlTypes#hasTimePart(int)
*/
TIME,
/**
* Indicates that the argument should be of type
* {@link org.hibernate.type.SqlTypes#BOOLEAN} or
* a logical expression (predicate)
*/
BOOLEAN,
/**
* @see org.hibernate.type.SqlTypes#isBinaryType(int)
*/
BINARY,
/**
* Indicates a parameter that accepts any type
*/
ANY,
/**
* A temporal unit, used by the {@code extract()} function, and
* some native database functions
*
* @see TemporalUnit
* @see org.hibernate.query.sqm.tree.expression.SqmExtractUnit
* @see org.hibernate.query.sqm.tree.expression.SqmDurationUnit
*/
TEMPORAL_UNIT,
/**
* A trim specification, for trimming and padding functions
*
* @see org.hibernate.query.sqm.tree.expression.SqmTrimSpecification
*/
TRIM_SPEC,
/**
* A collation, used by the {@code collate()} function
*
* @see org.hibernate.query.sqm.tree.expression.SqmCollation
*/
COLLATION,
/**
* Any type with an order (numeric, string, and temporal types)
*/
COMPARABLE,
/**
* @see org.hibernate.type.SqlTypes#isCharacterOrClobType(int)
*/
STRING_OR_CLOB,
/**
* Indicates that the argument should be a spatial type
* @see org.hibernate.type.SqlTypes#isSpatialType(int)
*/
SPATIAL,
/**
* Indicates that the argument should be a JSON type
* @see org.hibernate.type.SqlTypes#isJsonType(int)
* @since 7.0
*/
JSON,
/**
* Indicates that the argument should be a JSON or String type
* @see org.hibernate.type.SqlTypes#isImplicitJsonType(int)
* @since 7.0
*/
IMPLICIT_JSON,
/**
* Indicates that the argument should be an ENUM type
* @see org.hibernate.type.SqlTypes#isEnumType(int)
* @since 7.0
*/
ENUM,
/**
* Indicates that the argument should be a XML type
* @see org.hibernate.type.SqlTypes#isXmlType(int)
* @since 7.0
*/
XML,
/**
* Indicates that the argument should be a XML or String type
* @see org.hibernate.type.SqlTypes#isImplicitXmlType(int)
* @since 7.0
*/
IMPLICIT_XML,
/**
* Indicates a parameter that accepts any type, except untyped expressions like {@code null} literals
*/
NO_UNTYPED
}
| FunctionParameterType |
java | apache__logging-log4j2 | log4j-taglib/src/main/java/org/apache/logging/log4j/taglib/Log4jTaglibLoggerContext.java | {
"start": 1710,
"end": 5157
} | class ____ implements LoggerContext {
private static final ReadWriteLock LOCK = new ReentrantReadWriteLock();
private static final Lock READ_LOCK = LOCK.readLock();
private static final Lock WRITE_LOCK = LOCK.writeLock();
private static final Map<ServletContext, Log4jTaglibLoggerContext> LOGGER_CONTEXT_BY_SERVLET_CONTEXT =
new WeakHashMap<>();
private static final MessageFactory DEFAULT_MESSAGE_FACTORY = ParameterizedMessageFactory.INSTANCE;
private final LoggerRegistry<Log4jTaglibLogger> loggerRegistry = new LoggerRegistry<>();
private final ServletContext servletContext;
private Log4jTaglibLoggerContext(final ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public Object getExternalContext() {
return servletContext;
}
@Override
public Log4jTaglibLogger getLogger(final String name) {
return getLogger(name, DEFAULT_MESSAGE_FACTORY);
}
@Override
public Log4jTaglibLogger getLogger(final String name, @Nullable final MessageFactory messageFactory) {
final MessageFactory effectiveMessageFactory =
messageFactory != null ? messageFactory : DEFAULT_MESSAGE_FACTORY;
final Log4jTaglibLogger oldLogger = loggerRegistry.getLogger(name, effectiveMessageFactory);
if (oldLogger != null) {
return oldLogger;
}
final Log4jTaglibLogger newLogger = createLogger(name, effectiveMessageFactory);
loggerRegistry.putIfAbsent(name, effectiveMessageFactory, newLogger);
return loggerRegistry.getLogger(name, effectiveMessageFactory);
}
private Log4jTaglibLogger createLogger(final String name, final MessageFactory messageFactory) {
final LoggerContext loggerContext = LogManager.getContext(false);
final ExtendedLogger delegateLogger = loggerContext.getLogger(name, messageFactory);
return new Log4jTaglibLogger(delegateLogger, name, delegateLogger.getMessageFactory());
}
@Override
public boolean hasLogger(final String name) {
return loggerRegistry.hasLogger(name, DEFAULT_MESSAGE_FACTORY);
}
@Override
public boolean hasLogger(final String name, @Nullable final MessageFactory messageFactory) {
final MessageFactory effectiveMessageFactory =
messageFactory != null ? messageFactory : DEFAULT_MESSAGE_FACTORY;
return loggerRegistry.hasLogger(name, effectiveMessageFactory);
}
@Override
public boolean hasLogger(final String name, final Class<? extends MessageFactory> messageFactoryClass) {
return loggerRegistry.hasLogger(name, messageFactoryClass);
}
static Log4jTaglibLoggerContext getInstance(final ServletContext servletContext) {
// Get the associated logger context, if exists
READ_LOCK.lock();
try {
final Log4jTaglibLoggerContext loggerContext = LOGGER_CONTEXT_BY_SERVLET_CONTEXT.get(servletContext);
if (loggerContext != null) {
return loggerContext;
}
} finally {
READ_LOCK.unlock();
}
// Create the logger context
WRITE_LOCK.lock();
try {
return LOGGER_CONTEXT_BY_SERVLET_CONTEXT.computeIfAbsent(servletContext, Log4jTaglibLoggerContext::new);
} finally {
WRITE_LOCK.unlock();
}
}
}
| Log4jTaglibLoggerContext |
java | apache__flink | flink-datastream/src/main/java/org/apache/flink/datastream/impl/context/AbstractPartitionedContext.java | {
"start": 1518,
"end": 2881
} | class ____ implements BasePartitionedContext {
protected final RuntimeContext context;
protected final DefaultStateManager stateManager;
protected final ProcessingTimeManager processingTimeManager;
public AbstractPartitionedContext(
RuntimeContext context,
Supplier<Object> currentKeySupplier,
BiConsumer<Runnable, Object> processorWithKey,
ProcessingTimeManager processingTimeManager,
StreamingRuntimeContext operatorContext,
OperatorStateStore operatorStateStore) {
this.context = context;
this.stateManager =
new DefaultStateManager(
currentKeySupplier, processorWithKey, operatorContext, operatorStateStore);
this.processingTimeManager = processingTimeManager;
}
@Override
public JobInfo getJobInfo() {
return context.getJobInfo();
}
@Override
public TaskInfo getTaskInfo() {
return context.getTaskInfo();
}
@Override
public DefaultStateManager getStateManager() {
return stateManager;
}
@Override
public ProcessingTimeManager getProcessingTimeManager() {
return processingTimeManager;
}
@Override
public MetricGroup getMetricGroup() {
return context.getMetricGroup();
}
}
| AbstractPartitionedContext |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/EqualsGetClass.java | {
"start": 3007,
"end": 3667
} | class ____ extends BugChecker implements MethodInvocationTreeMatcher {
private static final Matcher<ExpressionTree> GET_CLASS =
instanceMethod().onDescendantOf("java.lang.Object").named("getClass");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!GET_CLASS.matches(tree, state)) {
return Description.NO_MATCH;
}
TreePath methodTreePath = state.findPathToEnclosing(MethodTree.class);
if (methodTreePath == null) {
return Description.NO_MATCH;
}
ClassTree classTree = state.findEnclosing(ClassTree.class);
// Using getClass is harmless if a | EqualsGetClass |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/collectionbasictype/EnumHolder.java | {
"start": 204,
"end": 288
} | class ____ {
public <E extends Enum<E>> E getMyEnum() {
return null;
}
}
| EnumHolder |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/path/JSONPath_field_access_filter_compare_string_simple.java | {
"start": 194,
"end": 5002
} | class ____ extends TestCase {
public void test_list_eq() throws Exception {
JSONPath path = new JSONPath("[name = 'ljw2083']");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));
}
public void test_list_eq_x() throws Exception {
JSONPath path = new JSONPath("[name = 'ljw2083']");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));
}
public void test_list_eq_null() throws Exception {
JSONPath path = new JSONPath("$[name = null]");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(2), result.get(0));
Assert.assertSame(entities.get(3), result.get(1));
}
public void test_list_not_null() throws Exception {
JSONPath path = new JSONPath("$[name != null]");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
}
public void test_list_gt() throws Exception {
JSONPath path = new JSONPath("$[name > 'ljw2083']");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(1), result.get(0));
}
public void test_list_ge() throws Exception {
JSONPath path = new JSONPath("$[name >= 'ljw2083']");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
}
public void test_list_lt() throws Exception {
JSONPath path = new JSONPath("$[?(@.name < 'wenshao')]");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));
}
public void test_list_le() throws Exception {
JSONPath path = new JSONPath("$[name <= 'wenshao']");
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, null));
entities.add(new Entity(null, null));
List<Object> result = (List<Object>) path.eval(entities);
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
}
public static | JSONPath_field_access_filter_compare_string_simple |
java | google__jimfs | jimfs/src/test/java/com/google/common/jimfs/TestAttributes.java | {
"start": 718,
"end": 821
} | interface ____ extends BasicFileAttributes {
String foo();
long bar();
int baz();
}
| TestAttributes |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/FirstValueWithRetractAggFunctionWithoutOrderTest.java | {
"start": 2053,
"end": 2122
} | class ____ `accumulate`
* method without order argument.
*/
final | tests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/unused/RemoveUnusedBeansTest.java | {
"start": 3741,
"end": 3992
} | class ____ extends Foo {
@Inject
Instance<InjectedViaInstance> instance;
@Inject
Instance<Comparable<? extends Foo>> instanceWildcard2;
@Inject
String foo;
}
@Singleton
static | FooAlternative |
java | apache__hadoop | hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpWithAcls.java | {
"start": 5642,
"end": 5783
} | class ____ throws UnsupportedOperationException for the
* ACL methods, so we don't need to override them.
*/
public static | implementation |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/RedundantTest.java | {
"start": 969,
"end": 1736
} | class ____ implements ExtraProcessor, ExtraTypeProvider {
public void processExtra(Object object, String key, Object value) {
VO vo = (VO) object;
vo.getAttributes().put(key, value);
}
public Type getExtraType(Object object, String key) {
if ("value".equals(key)) {
return int.class;
}
return null;
}
};
ExtraProcessor processor = new MyExtraProcessor();
VO vo = JSON.parseObject("{\"id\":123,\"value\":\"123456\"}", VO.class, processor);
Assert.assertEquals(123, vo.getId());
Assert.assertEquals(123456, vo.getAttributes().get("value"));
}
public static | MyExtraProcessor |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RecipientListMEPTest.java | {
"start": 1035,
"end": 2431
} | class ____ extends ContextTestSupport {
@Test
public void testMEPInOnly() throws Exception {
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World", "Hello Again");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World", "Bye World");
template.sendBody("direct:start", "Hello World");
template.sendBody("direct:start", "Hello Again");
assertMockEndpointsSatisfied();
}
@Test
public void testMEPInOutOnly() throws Exception {
getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World", "Hello Again");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World", "Bye World");
String out = template.requestBody("direct:start", "Hello World", String.class);
assertEquals("Bye World", out);
out = template.requestBody("direct:start", "Hello Again", String.class);
assertEquals("Bye World", out);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").recipientList().constant("seda:foo?exchangePattern=InOut").to("mock:result");
from("seda:foo").to("mock:foo").transform().constant("Bye World");
}
};
}
}
| RecipientListMEPTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/delegate/MutationDelegateTest.java | {
"start": 7194,
"end": 7872
} | class ____ {
@Id
@Column( name = "id_column" )
private Integer id;
@Generated( event = EventType.INSERT )
@ColumnDefault( "'default_name'" )
private String name;
@UpdateTimestamp( source = SourceType.DB )
private Date updateDate;
@SuppressWarnings( "FieldCanBeLocal" )
private String data;
public ValuesAndRowId() {
}
private ValuesAndRowId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public Date getUpdateDate() {
return updateDate;
}
public void setData(String data) {
this.data = data;
}
}
@Entity( name = "ValuesAndNaturalId" )
@SuppressWarnings( "unused" )
public static | ValuesAndRowId |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithCascadeOnPersist.java | {
"start": 3314,
"end": 3965
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ID_TABLE_2")
@TableGenerator(name = "ID_TABLE_2", pkColumnValue = "MarketBidGroup", allocationSize = 10000)
private Long id;
private String bidGroup;
@OneToMany(mappedBy = "group")
private final Set<MarketBid> marketBids = new HashSet<>();
public void addMarketBid(MarketBid marketBid) {
this.marketBids.add( marketBid );
}
public String getBidGroup() {
return bidGroup;
}
public void setBidGroup(String bidGroup) {
this.bidGroup = bidGroup;
}
}
@Entity(name = "MarketResult")
@Access(AccessType.FIELD)
public static | MarketBidGroup |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableZipIterable.java | {
"start": 2235,
"end": 4883
} | class ____<T, U, V> implements Observer<T>, Disposable {
final Observer<? super V> downstream;
final Iterator<U> iterator;
final BiFunction<? super T, ? super U, ? extends V> zipper;
Disposable upstream;
boolean done;
ZipIterableObserver(Observer<? super V> actual, Iterator<U> iterator,
BiFunction<? super T, ? super U, ? extends V> zipper) {
this.downstream = actual;
this.iterator = iterator;
this.zipper = zipper;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void dispose() {
upstream.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onNext(T t) {
if (done) {
return;
}
U u;
try {
u = Objects.requireNonNull(iterator.next(), "The iterator returned a null value");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
fail(e);
return;
}
V v;
try {
v = Objects.requireNonNull(zipper.apply(t, u), "The zipper function returned a null value");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
fail(e);
return;
}
downstream.onNext(v);
boolean b;
try {
b = iterator.hasNext();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
fail(e);
return;
}
if (!b) {
done = true;
upstream.dispose();
downstream.onComplete();
}
}
void fail(Throwable e) {
done = true;
upstream.dispose();
downstream.onError(e);
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
done = true;
downstream.onError(t);
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
downstream.onComplete();
}
}
}
| ZipIterableObserver |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/ExistingPropertyTest.java | {
"start": 3587,
"end": 3720
} | class ____ {
public String name;
protected Car(String n) { name = n; }
}
@JsonTypeName("accord")
static | Car |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.java | {
"start": 1865,
"end": 10693
} | class ____ {
private final EmbeddedDatabaseFactory databaseFactory;
private final ResourceDatabasePopulator databasePopulator;
private final ResourceLoader resourceLoader;
/**
* Create a new embedded database builder with a {@link DefaultResourceLoader}.
*/
public EmbeddedDatabaseBuilder() {
this(new DefaultResourceLoader());
}
/**
* Create a new embedded database builder with the given {@link ResourceLoader}.
* @param resourceLoader the {@code ResourceLoader} to delegate to
*/
public EmbeddedDatabaseBuilder(ResourceLoader resourceLoader) {
this.databaseFactory = new EmbeddedDatabaseFactory();
this.databasePopulator = new ResourceDatabasePopulator();
this.databaseFactory.setDatabasePopulator(this.databasePopulator);
this.resourceLoader = resourceLoader;
}
/**
* Specify whether a unique ID should be generated and used as the database name.
* <p>If the configuration for this builder is reused across multiple
* application contexts within a single JVM, this flag should be <em>enabled</em>
* (i.e., set to {@code true}) in order to ensure that each application context
* gets its own embedded database.
* <p>Enabling this flag overrides any explicit name set via {@link #setName}.
* @param flag {@code true} if a unique database name should be generated
* @return {@code this}, to facilitate method chaining
* @since 4.2
* @see #setName
*/
public EmbeddedDatabaseBuilder generateUniqueName(boolean flag) {
this.databaseFactory.setGenerateUniqueDatabaseName(flag);
return this;
}
/**
* Set the name of the embedded database.
* <p>Defaults to {@link EmbeddedDatabaseFactory#DEFAULT_DATABASE_NAME} if
* not called.
* <p>Will be overridden if the {@code generateUniqueName} flag has been
* set to {@code true}.
* @param databaseName the name of the embedded database to build
* @return {@code this}, to facilitate method chaining
* @see #generateUniqueName
*/
public EmbeddedDatabaseBuilder setName(String databaseName) {
this.databaseFactory.setDatabaseName(databaseName);
return this;
}
/**
* Set the type of embedded database. Consider using {@link #setDatabaseConfigurer}
* if customization of the connections properties is necessary.
* <p>Defaults to HSQL if not called.
* @param databaseType the type of embedded database to build
* @return {@code this}, to facilitate method chaining
*/
public EmbeddedDatabaseBuilder setType(EmbeddedDatabaseType databaseType) {
this.databaseFactory.setDatabaseType(databaseType);
return this;
}
/**
* Set the {@linkplain EmbeddedDatabaseConfigurer configurer} to use to
* configure the embedded database, as an alternative to {@link #setType}.
* @param configurer the configurer of the embedded database
* @return {@code this}, to facilitate method chaining
* @since 6.2
* @see EmbeddedDatabaseConfigurers
*/
public EmbeddedDatabaseBuilder setDatabaseConfigurer(EmbeddedDatabaseConfigurer configurer) {
this.databaseFactory.setDatabaseConfigurer(configurer);
return this;
}
/**
* Set the factory to use to create the {@link DataSource} instance that
* connects to the embedded database.
* <p>Defaults to {@link SimpleDriverDataSourceFactory} but can be overridden,
* for example to introduce connection pooling.
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder setDataSourceFactory(DataSourceFactory dataSourceFactory) {
Assert.notNull(dataSourceFactory, "DataSourceFactory is required");
this.databaseFactory.setDataSourceFactory(dataSourceFactory);
return this;
}
/**
* Add default SQL scripts to execute to populate the database.
* <p>The default scripts are {@code "schema.sql"} to create the database
* schema and {@code "data.sql"} to populate the database with data.
* @return {@code this}, to facilitate method chaining
*/
public EmbeddedDatabaseBuilder addDefaultScripts() {
return addScripts("schema.sql", "data.sql");
}
/**
* Add an SQL script to execute to initialize or populate the database.
* @param script the script to execute
* @return {@code this}, to facilitate method chaining
*/
public EmbeddedDatabaseBuilder addScript(String script) {
this.databasePopulator.addScript(this.resourceLoader.getResource(script));
return this;
}
/**
* Add multiple SQL scripts to execute to initialize or populate the database.
* @param scripts the scripts to execute
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder addScripts(String... scripts) {
for (String script : scripts) {
addScript(script);
}
return this;
}
/**
* Specify the character encoding used in all SQL scripts, if different from
* the platform encoding.
* @param scriptEncoding the encoding used in scripts
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder setScriptEncoding(String scriptEncoding) {
this.databasePopulator.setSqlScriptEncoding(scriptEncoding);
return this;
}
/**
* Specify the statement separator used in all SQL scripts, if a custom one.
* <p>Defaults to {@code ";"} if not specified and falls back to {@code "\n"}
* as a last resort; may be set to {@link ScriptUtils#EOF_STATEMENT_SEPARATOR}
* to signal that each script contains a single statement without a separator.
* @param separator the statement separator
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder setSeparator(String separator) {
this.databasePopulator.setSeparator(separator);
return this;
}
/**
* Specify the single-line comment prefix used in all SQL scripts.
* <p>Defaults to {@code "--"}.
* @param commentPrefix the prefix for single-line comments
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
* @see #setCommentPrefixes(String...)
*/
public EmbeddedDatabaseBuilder setCommentPrefix(String commentPrefix) {
this.databasePopulator.setCommentPrefix(commentPrefix);
return this;
}
/**
* Specify the prefixes that identify single-line comments within all SQL scripts.
* <p>Defaults to {@code ["--"]}.
* @param commentPrefixes the prefixes for single-line comments
* @return {@code this}, to facilitate method chaining
* @since 5.2
*/
public EmbeddedDatabaseBuilder setCommentPrefixes(String... commentPrefixes) {
this.databasePopulator.setCommentPrefixes(commentPrefixes);
return this;
}
/**
* Specify the start delimiter for block comments in all SQL scripts.
* <p>Defaults to {@code "/*"}.
* @param blockCommentStartDelimiter the start delimiter for block comments
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
* @see #setBlockCommentEndDelimiter
*/
public EmbeddedDatabaseBuilder setBlockCommentStartDelimiter(String blockCommentStartDelimiter) {
this.databasePopulator.setBlockCommentStartDelimiter(blockCommentStartDelimiter);
return this;
}
/**
* Specify the end delimiter for block comments in all SQL scripts.
* <p>Defaults to <code>"*/"</code>.
* @param blockCommentEndDelimiter the end delimiter for block comments
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
* @see #setBlockCommentStartDelimiter
*/
public EmbeddedDatabaseBuilder setBlockCommentEndDelimiter(String blockCommentEndDelimiter) {
this.databasePopulator.setBlockCommentEndDelimiter(blockCommentEndDelimiter);
return this;
}
/**
* Specify that all failures which occur while executing SQL scripts should
* be logged but should not cause a failure.
* <p>Defaults to {@code false}.
* @param flag {@code true} if script execution should continue on error
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder continueOnError(boolean flag) {
this.databasePopulator.setContinueOnError(flag);
return this;
}
/**
* Specify that a failed SQL {@code DROP} statement within an executed
* script can be ignored.
* <p>This is useful for a database whose SQL dialect does not support an
* {@code IF EXISTS} clause in a {@code DROP} statement.
* <p>The default is {@code false} so that {@link #build building} will fail
* fast if a script starts with a {@code DROP} statement.
* @param flag {@code true} if failed drop statements should be ignored
* @return {@code this}, to facilitate method chaining
* @since 4.0.3
*/
public EmbeddedDatabaseBuilder ignoreFailedDrops(boolean flag) {
this.databasePopulator.setIgnoreFailedDrops(flag);
return this;
}
/**
* Build the embedded database.
* @return the embedded database
*/
public EmbeddedDatabase build() {
return this.databaseFactory.getDatabase();
}
}
| EmbeddedDatabaseBuilder |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/state/internals/ChangeLoggingSessionBytesStore.java | {
"start": 1464,
"end": 5267
} | class ____
extends WrappedStateStore<SessionStore<Bytes, byte[]>, byte[], byte[]>
implements SessionStore<Bytes, byte[]> {
private InternalProcessorContext<?, ?> internalContext;
ChangeLoggingSessionBytesStore(final SessionStore<Bytes, byte[]> bytesStore) {
super(bytesStore);
}
@Override
public void init(final StateStoreContext stateStoreContext, final StateStore root) {
internalContext = asInternalProcessorContext(stateStoreContext);
super.init(stateStoreContext, root);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Bytes key, final long earliestSessionEndTime, final long latestSessionStartTime) {
return wrapped().findSessions(key, earliestSessionEndTime, latestSessionStartTime);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFindSessions(final Bytes key,
final long earliestSessionEndTime,
final long latestSessionStartTime) {
return wrapped().backwardFindSessions(key, earliestSessionEndTime, latestSessionStartTime);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final Bytes keyFrom, final Bytes keyTo, final long earliestSessionEndTime, final long latestSessionStartTime) {
return wrapped().findSessions(keyFrom, keyTo, earliestSessionEndTime, latestSessionStartTime);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFindSessions(final Bytes keyFrom, final Bytes keyTo,
final long earliestSessionEndTime,
final long latestSessionStartTime) {
return wrapped().backwardFindSessions(keyFrom, keyTo, earliestSessionEndTime, latestSessionStartTime);
}
@Override
public void remove(final Windowed<Bytes> sessionKey) {
wrapped().remove(sessionKey);
internalContext.logChange(name(), SessionKeySchema.toBinary(sessionKey), null, internalContext.recordContext().timestamp(), wrapped().getPosition());
}
@Override
public void put(final Windowed<Bytes> sessionKey, final byte[] aggregate) {
wrapped().put(sessionKey, aggregate);
internalContext.logChange(name(), SessionKeySchema.toBinary(sessionKey), aggregate, internalContext.recordContext().timestamp(), wrapped().getPosition());
}
@Override
public byte[] fetchSession(final Bytes key, final long earliestSessionEndTime, final long latestSessionStartTime) {
return wrapped().fetchSession(key, earliestSessionEndTime, latestSessionStartTime);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> findSessions(final long earliestSessionEndTime,
final long latestSessionEndTime) {
return wrapped().findSessions(earliestSessionEndTime, latestSessionEndTime);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFetch(final Bytes key) {
return wrapped().backwardFetch(key);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> fetch(final Bytes key) {
return wrapped().fetch(key);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> backwardFetch(final Bytes keyFrom, final Bytes keyTo) {
return wrapped().backwardFetch(keyFrom, keyTo);
}
@Override
public KeyValueIterator<Windowed<Bytes>, byte[]> fetch(final Bytes keyFrom, final Bytes keyTo) {
return wrapped().fetch(keyFrom, keyTo);
}
} | ChangeLoggingSessionBytesStore |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletablePeekTest.java | {
"start": 1077,
"end": 1842
} | class ____ extends RxJavaTest {
@Test
public void onAfterTerminateCrashes() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
Completable.complete()
.doAfterTerminate(new Action() {
@Override
public void run() throws Exception {
throw new TestException();
}
})
.test()
.assertResult();
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void disposed() {
TestHelper.checkDisposed(CompletableSubject.create().doOnComplete(Functions.EMPTY_ACTION));
}
}
| CompletablePeekTest |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/rank/textsimilarity/TextSimilarityTestPlugin.java | {
"start": 2626,
"end": 3818
} | class ____ extends Plugin implements ActionPlugin {
private static final String inferenceId = "inference-id";
private static final String inferenceText = "inference-text";
private static final float minScore = 0.0f;
private final SetOnce<TestFilter> testFilter = new SetOnce<>();
@Override
public Collection<?> createComponents(PluginServices services) {
testFilter.set(new TestFilter());
return Collections.emptyList();
}
@Override
public List<ActionFilter> getActionFilters() {
return singletonList(testFilter.get());
}
private static final String THROWING_REQUEST_ACTION_BASED_RANK_BUILDER_NAME = "throwing_request_action_based_rank";
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
return List.of(
new NamedWriteableRegistry.Entry(
RankBuilder.class,
THROWING_REQUEST_ACTION_BASED_RANK_BUILDER_NAME,
ThrowingMockRequestActionBasedRankBuilder::new
)
);
}
/**
* Action filter that captures the inference action and injects a mock response.
*/
static | TextSimilarityTestPlugin |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/VelocityEndpointBuilderFactory.java | {
"start": 13761,
"end": 15902
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final VelocityHeaderNameBuilder INSTANCE = new VelocityHeaderNameBuilder();
/**
* The name of the velocity template.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code VelocityResourceUri}.
*/
public String velocityResourceUri() {
return "CamelVelocityResourceUri";
}
/**
* The content of the velocity template.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code VelocityTemplate}.
*/
public String velocityTemplate() {
return "CamelVelocityTemplate";
}
/**
* The velocity context to use.
*
* The option is a: {@code org.apache.velocity.context.Context} type.
*
* Group: producer
*
* @return the name of the header {@code VelocityContext}.
*/
public String velocityContext() {
return "CamelVelocityContext";
}
/**
* To add additional information to the used VelocityContext. The value
* of this header should be a Map with key/values that will added
* (override any existing key with the same name). This can be used to
* pre setup some common key/values you want to reuse in your velocity
* endpoints.
*
* The option is a: {@code Map<String, Object>} type.
*
* Group: producer
*
* @return the name of the header {@code VelocitySupplementalContext}.
*/
public String velocitySupplementalContext() {
return "CamelVelocitySupplementalContext";
}
}
static VelocityEndpointBuilder endpointBuilder(String componentName, String path) {
| VelocityHeaderNameBuilder |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/service/MasterServiceTests.java | {
"start": 112364,
"end": 113590
} | class ____ extends ClusterStateUpdateTask {
BlockingTask() {
super(Priority.IMMEDIATE);
}
@Override
public ClusterState execute(ClusterState currentState) {
var targetTime = deterministicTaskQueue.getCurrentTimeMillis() + between(1, 1000);
deterministicTaskQueue.scheduleAt(targetTime, () -> {});
while (deterministicTaskQueue.getCurrentTimeMillis() < targetTime) {
deterministicTaskQueue.advanceTime();
}
return currentState;
}
@Override
public void clusterStateProcessed(ClusterState initialState, ClusterState newState) {
if (actionCount.get() < 2) {
masterService.submitUnbatchedStateUpdateTask("blocker", BlockingTask.this);
}
}
@Override
public void onFailure(Exception e) {
fail(e);
}
}
masterService.submitUnbatchedStateUpdateTask("blocker", new BlockingTask());
| BlockingTask |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/java/org/apache/flink/table/codesplit/BlockStatementGrouperTest.java | {
"start": 1269,
"end": 8028
} | class ____ {
@Test
public void testExtractIfInWhileGroups() {
String parameters = "a, b";
String givenBlock = readResource("groups/code/IfInWhile.txt");
String expectedBlock = readResource("groups/expected/IfInWhile.txt");
BlockStatementGrouper grouper = new BlockStatementGrouper(givenBlock, 10, parameters);
RewriteGroupedCode rewriteGroupedCode = grouper.rewrite("myFun");
String rewriteCode = rewriteGroupedCode.getRewriteCode();
Map<String, List<String>> groups = rewriteGroupedCode.getGroups();
// Trying to mitigate any indentation issues between all sort of platforms by simply
// trim every line of the "class". Before this change, code-splitter test could fail on
// Windows machines while passing on Unix.
assertThat(trimLines(rewriteCode)).isEqualTo(trimLines(expectedBlock));
assertThat(groups).hasSize(4);
List<String> group1 = groups.get("myFun_rewriteGroup0_1_rewriteGroup3");
assertThat(group1).hasSize(2);
assertThat(group1.get(0)).isEqualTo("myFun_whileBody0_0(a, b);");
assertThat(trimLines(group1.get(1)))
.isEqualTo(
trimLines(
""
+ " if (a[0] > 0) {\n"
+ " myFun_whileBody0_0_ifBody0(a, b);\n"
+ " } else {\n"
+ " myFun_whileBody0_0_ifBody1(a, b);\n"
+ " }"));
List<String> group2 = groups.get("myFun_rewriteGroup0_1_rewriteGroup5");
assertThat(group2).hasSize(3);
assertThat(group2.get(0)).isEqualTo("a[2] += b[2];");
assertThat(group2.get(1)).isEqualTo("b[3] += a[3];");
assertThat(trimLines(group2.get(2)))
.isEqualTo(
trimLines(
"if (a[0] > 0) {\n"
+ " System.out.println(\"Hello\");\n"
+ " } else {\n"
+ " System.out.println(\"World\");\n"
+ " }"));
List<String> group3 = groups.get("myFun_rewriteGroup6");
assertThat(group3).hasSize(3);
assertThat(group3.get(0)).isEqualTo("a[0] += b[1];");
assertThat(group3.get(1)).isEqualTo("b[1] += a[1];");
assertThat(trimLines(group3.get(2)))
.isEqualTo(
trimLines(
" while (counter > 0) {\n"
+ " myFun_rewriteGroup0_1_rewriteGroup3(a, b);\n"
+ " \n"
+ " myFun_rewriteGroup0_1_rewriteGroup5(a, b);\n"
+ " \n"
+ " counter--;\n"
+ "}"));
List<String> group4 = groups.get("myFun_rewriteGroup7");
assertThat(group4).containsExactly("a[4] += b[4];", "b[5] += a[5];");
}
@Test
public void testExtractWhileInIfGroups() {
String parameters = "a, b";
String givenBlock = readResource("groups/code/WhileInIf.txt");
String expectedBlock = readResource("groups/expected/WhileInIf.txt");
BlockStatementGrouper grouper = new BlockStatementGrouper(givenBlock, 10, parameters);
RewriteGroupedCode rewriteGroupedCode = grouper.rewrite("myFun");
String rewriteCode = rewriteGroupedCode.getRewriteCode();
Map<String, List<String>> groups = rewriteGroupedCode.getGroups();
// Trying to mitigate any indentation issues between all sort of platforms by simply
// trim every line of the "class". Before this change, code-splitter test could fail on
// Windows machines while passing on Unix.
assertThat(trimLines(rewriteCode)).isEqualTo(trimLines(expectedBlock));
assertThat(groups).hasSize(5);
List<String> group1 = groups.get("myFun_rewriteGroup0_1_rewriteGroup2_3_rewriteGroup5");
assertThat(group1).hasSize(2);
assertThat(group1.get(0)).isEqualTo("myFun_whileBody0_0(a, b);");
assertThat(trimLines(group1.get(1)))
.isEqualTo(
trimLines(
""
+ " if (a[0] > 0) {\n"
+ " myFun_whileBody0_0_ifBody0(a, b);\n"
+ " } else {\n"
+ " myFun_whileBody0_0_ifBody1(a, b);\n"
+ " }"));
List<String> group2 = groups.get("myFun_rewriteGroup0_1_rewriteGroup6");
assertThat(group2).hasSize(1);
assertThat(trimLines(group2.get(0)))
.isEqualTo(
trimLines(
""
+ "while (counter > 0) {\n"
+ " myFun_rewriteGroup0_1_rewriteGroup2_3_rewriteGroup5(a, b);\n"
+ " counter--;\n"
+ "}"));
List<String> group3 = groups.get("myFun_rewriteGroup0_1_rewriteGroup7");
assertThat(group3).containsExactly("a[2] += b[2];", "b[3] += a[3];");
List<String> group4 = groups.get("myFun_rewriteGroup8");
assertThat(group4).hasSize(3);
assertThat(group4.get(0)).isEqualTo("a[0] += b[1];");
assertThat(group4.get(1)).isEqualTo("b[1] += a[1];");
assertThat(trimLines(group4.get(2)))
.isEqualTo(
trimLines(
"if (a.length < 100) {\n"
+ " myFun_rewriteGroup0_1_rewriteGroup6(a, b);\n"
+ " \n"
+ " myFun_rewriteGroup0_1_rewriteGroup7(a, b);\n"
+ " } else {\n"
+ " while (counter < 100) {\n"
+ " b[4] = b[4]++;\n"
+ " counter++;\n"
+ " }\n"
+ "}"));
List<String> group5 = groups.get("myFun_rewriteGroup9");
assertThat(group5).containsExactly("a[5] += b[5];", "b[6] += a[6];");
}
}
| BlockStatementGrouperTest |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java | {
"start": 52897,
"end": 53268
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
return http
.httpBasic(withDefaults())
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().hasAuthority("ROLE_USER")
)
.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static | RoleUserAuthorityConfig |
java | google__dagger | javatests/dagger/internal/codegen/ComponentValidationTest.java | {
"start": 17343,
"end": 17660
} | class ____ extends AbstractModule {}");
Source component =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component(modules = SubclassedModule.class)",
" | SubclassedModule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.