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-web/src/main/java/org/springframework/web/util/WhatWgUrlParser.java | {
"start": 93905,
"end": 94144
} | interface ____ permits PathSegment, PathSegments {
void append(int codePoint);
void append(String s);
boolean isEmpty();
void shorten(String scheme);
boolean isOpaque();
Path clone();
String name();
}
static final | Path |
java | apache__flink | flink-rpc/flink-rpc-akka/src/test/java/org/apache/flink/runtime/rpc/pekko/RpcSerializedValueTest.java | {
"start": 1268,
"end": 4152
} | class ____ {
@Test
void testNullValue() throws Exception {
RpcSerializedValue serializedValue = RpcSerializedValue.valueOf(null);
assertThat(serializedValue.getSerializedData()).isNull();
assertThat(serializedValue.getSerializedDataLength()).isEqualTo(0);
assertThat((Object) serializedValue.deserializeValue(getClass().getClassLoader())).isNull();
RpcSerializedValue otherSerializedValue = RpcSerializedValue.valueOf(null);
assertThat(otherSerializedValue).isEqualTo(serializedValue);
assertThat(otherSerializedValue.hashCode()).isEqualTo(serializedValue.hashCode());
RpcSerializedValue clonedSerializedValue = InstantiationUtil.clone(serializedValue);
assertThat(clonedSerializedValue.getSerializedData()).isNull();
assertThat(clonedSerializedValue.getSerializedDataLength()).isEqualTo(0);
assertThat((Object) clonedSerializedValue.deserializeValue(getClass().getClassLoader()))
.isNull();
assertThat(clonedSerializedValue).isEqualTo(serializedValue);
assertThat(clonedSerializedValue.hashCode()).isEqualTo(serializedValue.hashCode());
}
static Stream<Object> serializationArguments() {
return Stream.of(
true,
(byte) 5,
(short) 6,
5,
5L,
5.5F,
6.5,
'c',
"string",
Instant.now(),
BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN),
BigDecimal.valueOf(Math.PI));
}
@ParameterizedTest
@MethodSource("serializationArguments")
void testNotNullValues(Object value) throws Exception {
RpcSerializedValue serializedValue = RpcSerializedValue.valueOf(value);
assertThat(serializedValue.getSerializedData()).isNotNull();
assertThat(serializedValue.getSerializedDataLength()).isGreaterThan(0);
assertThat((Object) serializedValue.deserializeValue(getClass().getClassLoader()))
.isEqualTo(value);
RpcSerializedValue otherSerializedValue = RpcSerializedValue.valueOf(value);
assertThat(otherSerializedValue).isEqualTo(serializedValue);
assertThat(otherSerializedValue.hashCode()).isEqualTo(serializedValue.hashCode());
RpcSerializedValue clonedSerializedValue = InstantiationUtil.clone(serializedValue);
assertThat(clonedSerializedValue.getSerializedData())
.isEqualTo(serializedValue.getSerializedData());
assertThat((Object) clonedSerializedValue.deserializeValue(getClass().getClassLoader()))
.isEqualTo(value);
assertThat(clonedSerializedValue).isEqualTo(serializedValue);
assertThat(clonedSerializedValue.hashCode()).isEqualTo(serializedValue.hashCode());
}
}
| RpcSerializedValueTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumDeserializationTest.java | {
"start": 1335,
"end": 1638
} | class ____ extends StdDeserializer<Object>
{
public DummyDeserializer() { super(Object.class); }
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
{
return AnnotatedTestEnum.OK;
}
}
public static | DummyDeserializer |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/reuse/ReuseCircuitBreakerTest.java | {
"start": 832,
"end": 2957
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot(jar -> jar.addClasses(HelloService.class, MyGuard.class));
@Inject
HelloService helloService;
@Inject
CircuitBreakerMaintenance cb;
@BeforeEach
public void reset() {
CircuitBreakerMaintenance.get().resetAll();
}
@Test
public void test() {
// force guard instantiation
assertThatCode(() -> {
helloService.hello(null);
}).doesNotThrowAnyException();
CircuitBreakerMaintenance cbm = CircuitBreakerMaintenance.get();
assertThat(cb.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.CLOSED);
assertThat(cbm.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.CLOSED);
AtomicInteger helloStateChanges = new AtomicInteger();
cbm.onStateChange(MyGuard.NAME, ignored -> {
helloStateChanges.incrementAndGet();
});
for (int i = 0; i < MyGuard.THRESHOLD - 1; i++) { // `- 1` because of the initial invocation above
assertThatThrownBy(() -> {
helloService.hello(new IOException());
}).isExactlyInstanceOf(IOException.class);
}
assertThat(cb.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.OPEN);
assertThat(cbm.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.OPEN);
// 1. closed -> open
assertThat(helloStateChanges).hasValue(1);
await().atMost(MyGuard.DELAY * 2, TimeUnit.MILLISECONDS)
.ignoreException(CircuitBreakerOpenException.class)
.untilAsserted(() -> {
assertThat(helloService.hello(null)).isEqualTo(HelloService.OK);
});
assertThat(cb.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.CLOSED);
assertThat(cbm.currentState(MyGuard.NAME)).isEqualTo(CircuitBreakerState.CLOSED);
// 2. open -> half-open
// 3. half-open -> closed
assertThat(helloStateChanges).hasValue(3);
}
}
| ReuseCircuitBreakerTest |
java | quarkusio__quarkus | integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/resources/BookResource.java | {
"start": 340,
"end": 651
} | class ____ {
@Inject
BookDao bookDao;
@Transactional
@GET
@Path("/{name}/{author}")
public List<Book> addAndListAll(@PathParam("name") String name, @PathParam("author") String author) {
bookDao.persist(new Book(name, author));
return bookDao.listAll();
}
}
| BookResource |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/checkpointing/UnalignedCheckpointFailureHandlingITCase.java | {
"start": 15250,
"end": 15385
} | class ____ extends IOException {
public TestException(String message) {
super(message);
}
}
}
| TestException |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java | {
"start": 1709,
"end": 2592
} | class ____ {
@Autowired
private ClassHierarchyWithMergedConfigLevelOneTests.AppConfig appConfig;
@Bean
String user() {
return appConfig.parent() + " + test user";
}
@Bean
String beanFromTestUserConfig() {
return "from TestUserConfig";
}
}
@Autowired
private String beanFromTestUserConfig;
@Test
@Override
void loadContextHierarchy() {
assertThat(context).as("child ApplicationContext").isNotNull();
assertThat(context.getParent()).as("parent ApplicationContext").isNotNull();
assertThat(context.getParent().getParent()).as("grandparent ApplicationContext").isNull();
assertThat(parent).isEqualTo("parent");
assertThat(user).isEqualTo("parent + test user");
assertThat(beanFromTestUserConfig).isEqualTo("from TestUserConfig");
assertThat(beanFromUserConfig).as("Bean from UserConfig should not be present.").isNull();
}
}
| TestUserConfig |
java | spring-projects__spring-boot | module/spring-boot-micrometer-observation/src/main/java/org/springframework/boot/micrometer/observation/autoconfigure/ObservationProperties.java | {
"start": 1073,
"end": 1902
} | class ____ {
private final Http http = new Http();
/**
* Common key-values that are applied to every observation.
*/
private Map<String, String> keyValues = new LinkedHashMap<>();
/**
* Whether observations starting with the specified name should be enabled. The
* longest match wins, the key 'all' can also be used to configure all observations.
*/
private Map<String, Boolean> enable = new LinkedHashMap<>();
public Map<String, Boolean> getEnable() {
return this.enable;
}
public void setEnable(Map<String, Boolean> enable) {
this.enable = enable;
}
public Http getHttp() {
return this.http;
}
public Map<String, String> getKeyValues() {
return this.keyValues;
}
public void setKeyValues(Map<String, String> keyValues) {
this.keyValues = keyValues;
}
public static | ObservationProperties |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/support/CustomSQLErrorCodesTranslation.java | {
"start": 2031,
"end": 2158
} | class ____ the specified error codes.
*/
public @Nullable Class<?> getExceptionClass() {
return this.exceptionClass;
}
}
| for |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/dynamic/DynMethods.java | {
"start": 8827,
"end": 9031
} | class ____ found on supplied classloader.
LOG.debug("failed to load class {}", className, e);
}
return this;
}
/**
* Checks for an implementation, first finding the given | not |
java | apache__rocketmq | remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/LockBatchRequestBody.java | {
"start": 1078,
"end": 2284
} | class ____ extends RemotingSerializable {
private String consumerGroup;
private String clientId;
private boolean onlyThisBroker = false;
private Set<MessageQueue> mqSet = new HashSet<>();
public String getConsumerGroup() {
return consumerGroup;
}
public void setConsumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public boolean isOnlyThisBroker() {
return onlyThisBroker;
}
public void setOnlyThisBroker(boolean onlyThisBroker) {
this.onlyThisBroker = onlyThisBroker;
}
public Set<MessageQueue> getMqSet() {
return mqSet;
}
public void setMqSet(Set<MessageQueue> mqSet) {
this.mqSet = mqSet;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("consumerGroup", consumerGroup)
.add("clientId", clientId)
.add("onlyThisBroker", onlyThisBroker)
.add("mqSet", mqSet)
.toString();
}
}
| LockBatchRequestBody |
java | apache__camel | components/camel-huawei/camel-huaweicloud-obs/src/main/java/org/apache/camel/component/huaweicloud/obs/OBSProducer.java | {
"start": 2340,
"end": 18928
} | class ____ extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(OBSProducer.class);
private OBSEndpoint endpoint;
private ObsClient obsClient;
private Gson gson;
public OBSProducer(OBSEndpoint endpoint) {
super(endpoint);
this.endpoint = endpoint;
}
@Override
protected void doInit() throws Exception {
super.doInit();
this.gson = new Gson();
}
public void process(Exchange exchange) throws Exception {
ClientConfigurations clientConfigurations = new ClientConfigurations();
if (obsClient == null) {
this.obsClient = endpoint.initClient();
}
updateClientConfigs(exchange, clientConfigurations);
switch (clientConfigurations.getOperation()) {
case OBSOperations.LIST_BUCKETS:
listBuckets(exchange);
break;
case OBSOperations.CREATE_BUCKET:
createBucket(exchange, clientConfigurations);
break;
case OBSOperations.DELETE_BUCKET:
deleteBucket(exchange, clientConfigurations);
break;
case OBSOperations.CHECK_BUCKET_EXISTS:
checkBucketExists(exchange, clientConfigurations);
break;
case OBSOperations.GET_BUCKET_METADATA:
getBucketMetadata(exchange, clientConfigurations);
break;
case OBSOperations.LIST_OBJECTS:
listObjects(exchange, clientConfigurations);
break;
case OBSOperations.GET_OBJECT:
getObject(exchange, clientConfigurations);
break;
case OBSOperations.PUT_OBJECT:
putObject(exchange, clientConfigurations);
break;
default:
throw new UnsupportedOperationException(
String.format("%s is not a supported operation", clientConfigurations.getOperation()));
}
}
private void putObject(Exchange exchange, ClientConfigurations clientConfigurations) throws IOException {
Object body = exchange.getMessage().getBody();
// if body doesn't contain File, then user must pass object name. Bucket name is mandatory in all case
if ((ObjectHelper.isEmpty(clientConfigurations.getBucketName()) ||
ObjectHelper.isEmpty(clientConfigurations.getObjectName())) && !(body instanceof File)) {
throw new IllegalArgumentException("Bucket and object names are mandatory to put objects into bucket");
}
// check if bucket exists. if not, create one
LOG.trace("Checking if bucket {} exists", clientConfigurations.getBucketName());
if (!obsClient.headBucket(clientConfigurations.getBucketName())) {
LOG.warn("No bucket found with name {}. Attempting to create", clientConfigurations.getBucketName());
OBSRegion.checkValidRegion(clientConfigurations.getBucketLocation());
CreateBucketRequest request = new CreateBucketRequest(
clientConfigurations.getBucketName(),
clientConfigurations.getBucketLocation());
obsClient.createBucket(request);
LOG.warn("Bucket with name {} created. Continuing to upload object into it", request.getBucketName());
}
PutObjectResult putObjectResult = null;
if (body instanceof File) {
LOG.trace("Exchange payload is of type File");
// user file name by default if user has not over-riden it
String objectName = ObjectHelper.isEmpty(clientConfigurations.getObjectName())
? ((File) body).getName()
: clientConfigurations.getObjectName();
putObjectResult = obsClient.putObject(clientConfigurations.getBucketName(),
objectName, (File) body);
} else if (body instanceof String) {
// the string content will be stored in the remote object
LOG.trace("Writing text body into an object");
InputStream stream = new ByteArrayInputStream(((String) body).getBytes());
putObjectResult = obsClient.putObject(clientConfigurations.getBucketName(),
clientConfigurations.getObjectName(), stream);
stream.close();
} else if (body instanceof InputStream) {
// this covers miscellaneous file types
LOG.trace("Exchange payload is of type InputStream");
putObjectResult = obsClient.putObject(clientConfigurations.getBucketName(),
clientConfigurations.getObjectName(), (InputStream) body);
} else {
throw new IllegalArgumentException("Body should be of type file, string or an input stream");
}
exchange.getMessage().setBody(gson.toJson(putObjectResult));
}
/**
* downloads an object from remote OBS bucket
*
* @param exchange
* @param clientConfigurations
*/
private void getObject(Exchange exchange, ClientConfigurations clientConfigurations) {
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName()) ||
ObjectHelper.isEmpty(clientConfigurations.getObjectName())) {
throw new IllegalArgumentException("Bucket and object names are mandatory to get objects");
}
LOG.debug("Downloading remote obs object {} from bucket {}", clientConfigurations.getObjectName(),
clientConfigurations.getBucketLocation());
ObsObject obsObject = obsClient
.getObject(clientConfigurations.getBucketName(), clientConfigurations.getObjectName());
LOG.debug("Successfully downloaded obs object {}", clientConfigurations.getObjectName());
OBSUtils.mapObsObject(exchange, obsObject);
}
/**
* Perform list buckets operation
*
* @param exchange
* @throws ObsException
*/
private void listBuckets(Exchange exchange) throws ObsException {
// invoke list buckets method and map response object to exchange body
ListBucketsRequest request = new ListBucketsRequest();
ListBucketsResult response = obsClient.listBucketsV2(request);
exchange.getMessage().setBody(gson.toJson(response.getBuckets()));
}
/**
* Perform create bucket operation
*
* @param exchange
* @param clientConfigurations
* @throws ObsException
*/
private void createBucket(Exchange exchange, ClientConfigurations clientConfigurations) throws ObsException {
CreateBucketRequest request = null;
// checking if user inputted exchange body containing bucket information. Body must be a CreateBucketRequest or a valid JSON string (Advanced users)
Object exchangeBody = exchange.getMessage().getBody();
if (exchangeBody instanceof CreateBucketRequest) {
request = (CreateBucketRequest) exchangeBody;
} else if (exchangeBody instanceof String) {
String strBody = (String) exchangeBody;
try {
request = new ObjectMapper().readValue(strBody, CreateBucketRequest.class);
} catch (JsonProcessingException e) {
LOG.warn(
"String request body must be a valid JSON representation of a CreateBucketRequest. Attempting to create a bucket from endpoint parameters");
}
}
// if no CreateBucketRequest was found in the exchange body, then create one from endpoint parameters (Basic users)
if (request == null) {
// check for bucket name, which is mandatory to create a new bucket
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName())) {
LOG.error("No bucket name given");
throw new IllegalArgumentException("Bucket name is mandatory to create bucket");
}
// check for bucket location, which is optional to create a new bucket
if (ObjectHelper.isEmpty(clientConfigurations.getBucketLocation())) {
LOG.warn("No bucket location given, defaulting to '{}'", OBSConstants.DEFAULT_LOCATION);
clientConfigurations.setBucketLocation(OBSConstants.DEFAULT_LOCATION);
}
// verify valid bucket location
OBSRegion.checkValidRegion(clientConfigurations.getBucketLocation());
request = new CreateBucketRequest(clientConfigurations.getBucketName(), clientConfigurations.getBucketLocation());
}
// invoke create bucket method and map response object to exchange body
ObsBucket response = obsClient.createBucket(request);
exchange.getMessage().setBody(gson.toJson(response));
}
/**
* Perform delete bucket operation
*
* @param exchange
* @param clientConfigurations
* @throws ObsException
*/
private void deleteBucket(Exchange exchange, ClientConfigurations clientConfigurations) throws ObsException {
// check for bucket name, which is mandatory to delete a bucket
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName())) {
LOG.error("No bucket name given");
throw new IllegalArgumentException("Bucket name is mandatory to delete bucket");
}
// invoke delete bucket method and map response object to exchange body
HeaderResponse response = obsClient.deleteBucket(clientConfigurations.getBucketName());
exchange.getMessage().setBody(gson.toJson(response.getResponseHeaders()));
}
/**
* Perform check bucket exists operation
*
* @param exchange
* @param clientConfigurations
* @throws ObsException
*/
private void checkBucketExists(Exchange exchange, ClientConfigurations clientConfigurations) throws ObsException {
// check for bucket name, which is mandatory to check if a bucket exists
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName())) {
LOG.error("No bucket name given");
throw new IllegalArgumentException("Bucket name is mandatory to check if bucket exists");
}
// invoke check bucket exists method and map response to exchange property
boolean bucketExists = obsClient.headBucket(clientConfigurations.getBucketName());
exchange.setProperty(OBSProperties.BUCKET_EXISTS, bucketExists);
}
/**
* Perform get bucket metadata operation
*
* @param exchange
* @param clientConfigurations
* @throws ObsException
*/
private void getBucketMetadata(Exchange exchange, ClientConfigurations clientConfigurations) throws ObsException {
// check for bucket name, which is mandatory to get bucket metadata
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName())) {
LOG.error("No bucket name given");
throw new IllegalArgumentException("Bucket name is mandatory to get bucket metadata");
}
// invoke get bucket metadata method and map response object to exchange body
BucketMetadataInfoRequest request = new BucketMetadataInfoRequest(clientConfigurations.getBucketName());
BucketMetadataInfoResult response = obsClient.getBucketMetadata(request);
exchange.getMessage().setBody(gson.toJson(response));
}
/**
* Perform list objects operation
*
* @param exchange
* @param clientConfigurations
* @throws ObsException
*/
private void listObjects(Exchange exchange, ClientConfigurations clientConfigurations) throws ObsException {
ListObjectsRequest request = null;
// checking if user inputted exchange body containing list objects information. Body must be a ListObjectsRequest or a valid JSON string (Advanced users)
Object exchangeBody = exchange.getMessage().getBody();
if (exchangeBody instanceof ListObjectsRequest) {
request = (ListObjectsRequest) exchangeBody;
} else if (exchangeBody instanceof String) {
String strBody = (String) exchangeBody;
try {
request = new ObjectMapper().readValue(strBody, ListObjectsRequest.class);
} catch (JsonProcessingException e) {
LOG.warn(
"String request body must be a valid JSON representation of a ListObjectsRequest. Attempting to list objects from endpoint parameters");
}
}
// if no ListObjectsRequest was found in the exchange body, then list from endpoint parameters (Basic users)
if (request == null) {
// check for bucket name, which is mandatory to list objects
if (ObjectHelper.isEmpty(clientConfigurations.getBucketName())) {
LOG.error("No bucket name given");
throw new IllegalArgumentException("Bucket name is mandatory to list objects");
}
request = new ListObjectsRequest(clientConfigurations.getBucketName());
}
// invoke list objects method. Each result only holds a maximum of 1000 objects, so keep listing each object until all objects have been listed
ObjectListing result;
List<ObsObject> objects = new ArrayList<>();
do {
result = obsClient.listObjects(request);
objects.addAll(result.getObjects());
request.setMarker(result.getNextMarker());
} while (result.isTruncated());
exchange.getMessage().setBody(gson.toJson(objects));
}
/**
* Update dynamic client configurations. Some endpoint parameters (operation, and bucket name and location) can also
* be passed via exchange properties, so they can be updated between each transaction. Since they can change, we
* must clear the previous transaction and update these parameters with their new values
*
* @param exchange
* @param clientConfigurations
*/
private void updateClientConfigs(Exchange exchange, ClientConfigurations clientConfigurations) {
// checking for required operation (exchange overrides endpoint operation if both are provided)
if (ObjectHelper.isEmpty(exchange.getProperty(OBSProperties.OPERATION))
&& ObjectHelper.isEmpty(endpoint.getOperation())) {
LOG.error("No operation name given. Cannot proceed with OBS operations.");
throw new IllegalArgumentException("Operation name not found");
} else {
clientConfigurations.setOperation(
ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.OPERATION))
? (String) exchange.getProperty(OBSProperties.OPERATION)
: endpoint.getOperation());
}
// checking for optional bucketName (exchange overrides endpoint bucketName if both are provided)
if (ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.BUCKET_NAME))
|| ObjectHelper.isNotEmpty(endpoint.getBucketName())) {
clientConfigurations.setBucketName(
ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.BUCKET_NAME))
? (String) exchange.getProperty(OBSProperties.BUCKET_NAME)
: endpoint.getBucketName());
}
// checking for optional bucketLocation (exchange overrides endpoint bucketLocation if both are provided)
if (ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.BUCKET_LOCATION))
|| ObjectHelper.isNotEmpty(endpoint.getBucketLocation())) {
clientConfigurations.setBucketLocation(
ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.BUCKET_LOCATION))
? (String) exchange.getProperty(OBSProperties.BUCKET_LOCATION)
: endpoint.getBucketLocation());
}
// checking for optional object name (exchange overrides endpoint bucketLocation if both are provided)
if (ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.OBJECT_NAME))
|| ObjectHelper.isNotEmpty(endpoint.getObjectName())) {
clientConfigurations.setObjectName(
ObjectHelper.isNotEmpty(exchange.getProperty(OBSProperties.OBJECT_NAME))
? (String) exchange.getProperty(OBSProperties.OBJECT_NAME)
: endpoint.getObjectName());
}
}
}
| OBSProducer |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/pkg/PackageConfig.java | {
"start": 975,
"end": 3288
} | class ____ a main method, or {@link io.quarkus.runtime.QuarkusApplication}.
* <p>
* If your application has main classes annotated with {@link io.quarkus.runtime.annotations.QuarkusMain}
* then this can also reference the name given in the annotation, to avoid the need to specify fully qualified
* names in the config.
*/
Optional<String> mainClass();
/**
* The directory into which the output package(s) should be written.
* Relative paths are resolved from the build systems target directory.
*/
Optional<Path> outputDirectory();
/**
* The name of the final artifact, excluding the suffix and file extension.
*/
Optional<String> outputName();
/**
* The timestamp used as a reference for generating the packages (e.g. for the creation timestamp of ZIP entries).
* <p>
* The approach is similar to what is done by the maven-jar-plugin with `project.build.outputTimestamp`.
*/
Optional<Instant> outputTimestamp();
/**
* Setting this switch to {@code true} will cause Quarkus to write the transformed application bytecode
* to the build tool's output directory.
* This is useful for post-build tools that need to scan the application bytecode (for example, offline code-coverage
* tools).
* <p>
* For example, if using Maven, enabling this feature will result in the classes in {@code target/classes} being
* replaced with classes that have been transformed by Quarkus.
* <p>
* Setting this to {@code true}, however, should be done with a lot of caution and only if subsequent builds are done
* in a clean environment (i.e. the build tool's output directory has been completely cleaned).
*/
@WithDefault("false")
boolean writeTransformedBytecodeToBuildOutput();
/**
* The suffix that is applied to the runner artifact's base file name.
*/
@WithDefault("-runner")
String runnerSuffix();
/**
* {@return the runner suffix if <code>addRunnerSuffix</code> is <code>true<code>, or an empty string otherwise}
*/
default String computedRunnerSuffix() {
return jar().addRunnerSuffix() ? runnerSuffix() : "";
}
/**
* Configuration for creating packages as JARs.
*/
@ConfigGroup
| with |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest46.java | {
"start": 982,
"end": 2847
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"select *"
+ " FROM MT_PRODUCT_ORDER T1,MT_ORDER T2 WHERE "
+ " T1.MT_ORDER_ID = T2.MT_ORDER_ID"
+ " and SELLER_SSOID = 1"
+ " AND T1.MT_ORDER_ID = '1'"
+ " AND T1.MT_BATCH_ORDER_ID IN '1'";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(2, visitor.getTables().size());
assertEquals(6, visitor.getColumns().size());
String text = TestUtils.outputOracle(stmt);
assertEquals("SELECT *"
+ "\nFROM MT_PRODUCT_ORDER T1, MT_ORDER T2"
+ "\nWHERE T1.MT_ORDER_ID = T2.MT_ORDER_ID"
+ "\n\tAND SELLER_SSOID = 1"
+ "\n\tAND T1.MT_ORDER_ID = '1'"
+ "\n\tAND T1.MT_BATCH_ORDER_ID IN ('1')", text);
// assertTrue(visitor.getColumns().contains(new TableStat.Column("acduser.vw_acd_info", "xzqh")));
// assertTrue(visitor.getOrderByColumns().contains(new TableStat.Column("employees", "last_name")));
}
}
| OracleSelectTest46 |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/BeanToFileTest.java | {
"start": 2248,
"end": 2367
} | class ____ {
public String doSomething(String input) {
return "Bye " + input;
}
}
}
| MyBean |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java | {
"start": 1241,
"end": 29484
} | class ____ {
private static final String NL = "\r\n";
@Mock
HttpServletResponse delegate;
@Mock
PrintWriter writer;
@Mock
ServletOutputStream out;
OnCommittedResponseWrapper response;
boolean committed;
@BeforeEach
public void setup() throws Exception {
this.response = new OnCommittedResponseWrapper(this.delegate) {
@Override
protected void onResponseCommitted() {
OnCommittedResponseWrapperTests.this.committed = true;
}
};
}
private void givenGetWriterThenReturn() throws IOException {
given(this.delegate.getWriter()).willReturn(this.writer);
}
private void givenGetOutputStreamThenReturn() throws IOException {
given(this.delegate.getOutputStream()).willReturn(this.out);
}
@Test
public void printWriterHashCode() throws Exception {
givenGetWriterThenReturn();
int expected = this.writer.hashCode();
assertThat(this.response.getWriter().hashCode()).isEqualTo(expected);
}
@Test
public void printWriterCheckError() throws Exception {
givenGetWriterThenReturn();
boolean expected = true;
given(this.writer.checkError()).willReturn(expected);
assertThat(this.response.getWriter().checkError()).isEqualTo(expected);
}
@Test
public void printWriterWriteInt() throws Exception {
givenGetWriterThenReturn();
int expected = 1;
this.response.getWriter().write(expected);
verify(this.writer).write(expected);
}
@Test
public void printWriterWriteCharIntInt() throws Exception {
givenGetWriterThenReturn();
char[] buff = new char[0];
int off = 2;
int len = 3;
this.response.getWriter().write(buff, off, len);
verify(this.writer).write(buff, off, len);
}
@Test
public void printWriterWriteChar() throws Exception {
givenGetWriterThenReturn();
char[] buff = new char[0];
this.response.getWriter().write(buff);
verify(this.writer).write(buff);
}
@Test
public void printWriterWriteStringIntInt() throws Exception {
givenGetWriterThenReturn();
String s = "";
int off = 2;
int len = 3;
this.response.getWriter().write(s, off, len);
verify(this.writer).write(s, off, len);
}
@Test
public void printWriterWriteString() throws Exception {
givenGetWriterThenReturn();
String s = "";
this.response.getWriter().write(s);
verify(this.writer).write(s);
}
@Test
public void printWriterPrintBoolean() throws Exception {
givenGetWriterThenReturn();
boolean b = true;
this.response.getWriter().print(b);
verify(this.writer).print(b);
}
@Test
public void printWriterPrintChar() throws Exception {
givenGetWriterThenReturn();
char c = 1;
this.response.getWriter().print(c);
verify(this.writer).print(c);
}
@Test
public void printWriterPrintInt() throws Exception {
givenGetWriterThenReturn();
int i = 1;
this.response.getWriter().print(i);
verify(this.writer).print(i);
}
@Test
public void printWriterPrintLong() throws Exception {
givenGetWriterThenReturn();
long l = 1;
this.response.getWriter().print(l);
verify(this.writer).print(l);
}
@Test
public void printWriterPrintFloat() throws Exception {
givenGetWriterThenReturn();
float f = 1;
this.response.getWriter().print(f);
verify(this.writer).print(f);
}
@Test
public void printWriterPrintDouble() throws Exception {
givenGetWriterThenReturn();
double x = 1;
this.response.getWriter().print(x);
verify(this.writer).print(x);
}
@Test
public void printWriterPrintCharArray() throws Exception {
givenGetWriterThenReturn();
char[] x = new char[0];
this.response.getWriter().print(x);
verify(this.writer).print(x);
}
@Test
public void printWriterPrintString() throws Exception {
givenGetWriterThenReturn();
String x = "1";
this.response.getWriter().print(x);
verify(this.writer).print(x);
}
@Test
public void printWriterPrintObject() throws Exception {
givenGetWriterThenReturn();
Object x = "1";
this.response.getWriter().print(x);
verify(this.writer).print(x);
}
@Test
public void printWriterPrintln() throws Exception {
givenGetWriterThenReturn();
this.response.getWriter().println();
verify(this.writer).println();
}
@Test
public void printWriterPrintlnBoolean() throws Exception {
givenGetWriterThenReturn();
boolean b = true;
this.response.getWriter().println(b);
verify(this.writer).println(b);
}
@Test
public void printWriterPrintlnChar() throws Exception {
givenGetWriterThenReturn();
char c = 1;
this.response.getWriter().println(c);
verify(this.writer).println(c);
}
@Test
public void printWriterPrintlnInt() throws Exception {
givenGetWriterThenReturn();
int i = 1;
this.response.getWriter().println(i);
verify(this.writer).println(i);
}
@Test
public void printWriterPrintlnLong() throws Exception {
givenGetWriterThenReturn();
long l = 1;
this.response.getWriter().println(l);
verify(this.writer).println(l);
}
@Test
public void printWriterPrintlnFloat() throws Exception {
givenGetWriterThenReturn();
float f = 1;
this.response.getWriter().println(f);
verify(this.writer).println(f);
}
@Test
public void printWriterPrintlnDouble() throws Exception {
givenGetWriterThenReturn();
double x = 1;
this.response.getWriter().println(x);
verify(this.writer).println(x);
}
@Test
public void printWriterPrintlnCharArray() throws Exception {
givenGetWriterThenReturn();
char[] x = new char[0];
this.response.getWriter().println(x);
verify(this.writer).println(x);
}
@Test
public void printWriterPrintlnString() throws Exception {
givenGetWriterThenReturn();
String x = "1";
this.response.getWriter().println(x);
verify(this.writer).println(x);
}
@Test
public void printWriterPrintlnObject() throws Exception {
givenGetWriterThenReturn();
Object x = "1";
this.response.getWriter().println(x);
verify(this.writer).println(x);
}
@Test
public void printWriterPrintfStringObjectVargs() throws Exception {
givenGetWriterThenReturn();
String format = "format";
Object[] args = new Object[] { "1" };
this.response.getWriter().printf(format, args);
verify(this.writer).printf(format, args);
}
@Test
public void printWriterPrintfLocaleStringObjectVargs() throws Exception {
givenGetWriterThenReturn();
Locale l = Locale.US;
String format = "format";
Object[] args = new Object[] { "1" };
this.response.getWriter().printf(l, format, args);
verify(this.writer).printf(l, format, args);
}
@Test
public void printWriterFormatStringObjectVargs() throws Exception {
givenGetWriterThenReturn();
String format = "format";
Object[] args = new Object[] { "1" };
this.response.getWriter().format(format, args);
verify(this.writer).format(format, args);
}
@Test
public void printWriterFormatLocaleStringObjectVargs() throws Exception {
givenGetWriterThenReturn();
Locale l = Locale.US;
String format = "format";
Object[] args = new Object[] { "1" };
this.response.getWriter().format(l, format, args);
verify(this.writer).format(l, format, args);
}
@Test
public void printWriterAppendCharSequence() throws Exception {
givenGetWriterThenReturn();
String x = "a";
this.response.getWriter().append(x);
verify(this.writer).append(x);
}
@Test
public void printWriterAppendCharSequenceIntInt() throws Exception {
givenGetWriterThenReturn();
String x = "abcdef";
int start = 1;
int end = 3;
this.response.getWriter().append(x, start, end);
verify(this.writer).append(x, start, end);
}
@Test
public void printWriterAppendChar() throws Exception {
givenGetWriterThenReturn();
char x = 1;
this.response.getWriter().append(x);
verify(this.writer).append(x);
}
// servletoutputstream
@Test
public void outputStreamHashCode() throws Exception {
givenGetOutputStreamThenReturn();
int expected = this.out.hashCode();
assertThat(this.response.getOutputStream().hashCode()).isEqualTo(expected);
}
@Test
public void outputStreamWriteInt() throws Exception {
givenGetOutputStreamThenReturn();
int expected = 1;
this.response.getOutputStream().write(expected);
verify(this.out).write(expected);
}
@Test
public void outputStreamWriteByte() throws Exception {
givenGetOutputStreamThenReturn();
byte[] expected = new byte[0];
this.response.getOutputStream().write(expected);
verify(this.out).write(expected);
}
@Test
public void outputStreamWriteByteIntInt() throws Exception {
givenGetOutputStreamThenReturn();
int start = 1;
int end = 2;
byte[] expected = new byte[0];
this.response.getOutputStream().write(expected, start, end);
verify(this.out).write(expected, start, end);
}
@Test
public void outputStreamPrintBoolean() throws Exception {
givenGetOutputStreamThenReturn();
boolean b = true;
this.response.getOutputStream().print(b);
verify(this.out).print(b);
}
@Test
public void outputStreamPrintChar() throws Exception {
givenGetOutputStreamThenReturn();
char c = 1;
this.response.getOutputStream().print(c);
verify(this.out).print(c);
}
@Test
public void outputStreamPrintInt() throws Exception {
givenGetOutputStreamThenReturn();
int i = 1;
this.response.getOutputStream().print(i);
verify(this.out).print(i);
}
@Test
public void outputStreamPrintLong() throws Exception {
givenGetOutputStreamThenReturn();
long l = 1;
this.response.getOutputStream().print(l);
verify(this.out).print(l);
}
@Test
public void outputStreamPrintFloat() throws Exception {
givenGetOutputStreamThenReturn();
float f = 1;
this.response.getOutputStream().print(f);
verify(this.out).print(f);
}
@Test
public void outputStreamPrintDouble() throws Exception {
givenGetOutputStreamThenReturn();
double x = 1;
this.response.getOutputStream().print(x);
verify(this.out).print(x);
}
@Test
public void outputStreamPrintString() throws Exception {
givenGetOutputStreamThenReturn();
String x = "1";
this.response.getOutputStream().print(x);
verify(this.out).print(x);
}
@Test
public void outputStreamPrintln() throws Exception {
givenGetOutputStreamThenReturn();
this.response.getOutputStream().println();
verify(this.out).println();
}
@Test
public void outputStreamPrintlnBoolean() throws Exception {
givenGetOutputStreamThenReturn();
boolean b = true;
this.response.getOutputStream().println(b);
verify(this.out).println(b);
}
@Test
public void outputStreamPrintlnChar() throws Exception {
givenGetOutputStreamThenReturn();
char c = 1;
this.response.getOutputStream().println(c);
verify(this.out).println(c);
}
@Test
public void outputStreamPrintlnInt() throws Exception {
givenGetOutputStreamThenReturn();
int i = 1;
this.response.getOutputStream().println(i);
verify(this.out).println(i);
}
@Test
public void outputStreamPrintlnLong() throws Exception {
givenGetOutputStreamThenReturn();
long l = 1;
this.response.getOutputStream().println(l);
verify(this.out).println(l);
}
@Test
public void outputStreamPrintlnFloat() throws Exception {
givenGetOutputStreamThenReturn();
float f = 1;
this.response.getOutputStream().println(f);
verify(this.out).println(f);
}
@Test
public void outputStreamPrintlnDouble() throws Exception {
givenGetOutputStreamThenReturn();
double x = 1;
this.response.getOutputStream().println(x);
verify(this.out).println(x);
}
@Test
public void outputStreamPrintlnString() throws Exception {
givenGetOutputStreamThenReturn();
String x = "1";
this.response.getOutputStream().println(x);
verify(this.out).println(x);
}
// The amount of content specified in the setContentLength method of the response
// has been greater than zero and has been written to the response.
// gh-3823
@Test
public void contentLengthPrintWriterWriteNullCommits() throws Exception {
givenGetWriterThenReturn();
String expected = null;
this.response.setContentLength(String.valueOf(expected).length() + 1);
this.response.getWriter().write(expected);
assertThat(this.committed).isFalse();
this.response.getWriter().write("a");
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteIntCommits() throws Exception {
givenGetWriterThenReturn();
int expected = 1;
this.response.setContentLength(String.valueOf(expected).length());
this.response.getWriter().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteIntMultiDigitCommits() throws Exception {
givenGetWriterThenReturn();
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length());
this.response.getWriter().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() throws Exception {
givenGetWriterThenReturn();
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length() + 1);
this.response.getWriter().write(expected);
assertThat(this.committed).isFalse();
this.response.getWriter().write(1);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteCharIntIntCommits() throws Exception {
givenGetWriterThenReturn();
char[] buff = new char[0];
int off = 2;
int len = 3;
this.response.setContentLength(3);
this.response.getWriter().write(buff, off, len);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteCharCommits() throws Exception {
givenGetWriterThenReturn();
char[] buff = new char[4];
this.response.setContentLength(buff.length);
this.response.getWriter().write(buff);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteStringIntIntCommits() throws Exception {
givenGetWriterThenReturn();
String s = "";
int off = 2;
int len = 3;
this.response.setContentLength(3);
this.response.getWriter().write(s, off, len);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterWriteStringCommits() throws IOException {
givenGetWriterThenReturn();
String body = "something";
this.response.setContentLength(body.length());
this.response.getWriter().write(body);
assertThat(this.committed).isTrue();
}
@Test
public void printWriterWriteStringContentLengthCommits() throws IOException {
givenGetWriterThenReturn();
String body = "something";
this.response.getWriter().write(body);
this.response.setContentLength(body.length());
assertThat(this.committed).isTrue();
}
@Test
public void printWriterWriteStringDoesNotCommit() throws IOException {
givenGetWriterThenReturn();
String body = "something";
this.response.getWriter().write(body);
assertThat(this.committed).isFalse();
}
@Test
public void contentLengthPrintWriterPrintBooleanCommits() throws Exception {
givenGetWriterThenReturn();
boolean b = true;
this.response.setContentLength(1);
this.response.getWriter().print(b);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintCharCommits() throws Exception {
givenGetWriterThenReturn();
char c = 1;
this.response.setContentLength(1);
this.response.getWriter().print(c);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintIntCommits() throws Exception {
givenGetWriterThenReturn();
int i = 1234;
this.response.setContentLength(String.valueOf(i).length());
this.response.getWriter().print(i);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintLongCommits() throws Exception {
givenGetWriterThenReturn();
long l = 12345;
this.response.setContentLength(String.valueOf(l).length());
this.response.getWriter().print(l);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintFloatCommits() throws Exception {
givenGetWriterThenReturn();
float f = 12345;
this.response.setContentLength(String.valueOf(f).length());
this.response.getWriter().print(f);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintDoubleCommits() throws Exception {
givenGetWriterThenReturn();
double x = 1.2345;
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintCharArrayCommits() throws Exception {
givenGetWriterThenReturn();
char[] x = new char[10];
this.response.setContentLength(x.length);
this.response.getWriter().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintStringCommits() throws Exception {
givenGetWriterThenReturn();
String x = "12345";
this.response.setContentLength(x.length());
this.response.getWriter().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintObjectCommits() throws Exception {
givenGetWriterThenReturn();
Object x = "12345";
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnCommits() throws Exception {
givenGetWriterThenReturn();
this.response.setContentLength(NL.length());
this.response.getWriter().println();
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnBooleanCommits() throws Exception {
givenGetWriterThenReturn();
boolean b = true;
this.response.setContentLength(1);
this.response.getWriter().println(b);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnCharCommits() throws Exception {
givenGetWriterThenReturn();
char c = 1;
this.response.setContentLength(1);
this.response.getWriter().println(c);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnIntCommits() throws Exception {
givenGetWriterThenReturn();
int i = 12345;
this.response.setContentLength(String.valueOf(i).length());
this.response.getWriter().println(i);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnLongCommits() throws Exception {
givenGetWriterThenReturn();
long l = 12345678;
this.response.setContentLength(String.valueOf(l).length());
this.response.getWriter().println(l);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnFloatCommits() throws Exception {
givenGetWriterThenReturn();
float f = 1234;
this.response.setContentLength(String.valueOf(f).length());
this.response.getWriter().println(f);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnDoubleCommits() throws Exception {
givenGetWriterThenReturn();
double x = 1;
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnCharArrayCommits() throws Exception {
givenGetWriterThenReturn();
char[] x = new char[20];
this.response.setContentLength(x.length);
this.response.getWriter().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnStringCommits() throws Exception {
givenGetWriterThenReturn();
String x = "1";
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterPrintlnObjectCommits() throws Exception {
givenGetWriterThenReturn();
Object x = "1";
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterAppendCharSequenceCommits() throws Exception {
givenGetWriterThenReturn();
String x = "a";
this.response.setContentLength(String.valueOf(x).length());
this.response.getWriter().append(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterAppendCharSequenceIntIntCommits() throws Exception {
givenGetWriterThenReturn();
String x = "abcdef";
int start = 1;
int end = 3;
this.response.setContentLength(end - start);
this.response.getWriter().append(x, start, end);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPrintWriterAppendCharCommits() throws Exception {
givenGetWriterThenReturn();
char x = 1;
this.response.setContentLength(1);
this.response.getWriter().append(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamWriteIntCommits() throws Exception {
givenGetOutputStreamThenReturn();
int expected = 1;
this.response.setContentLength(String.valueOf(expected).length());
this.response.getOutputStream().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamWriteIntMultiDigitCommits() throws Exception {
givenGetOutputStreamThenReturn();
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length());
this.response.getOutputStream().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() throws Exception {
givenGetOutputStreamThenReturn();
int expected = 10000;
this.response.setContentLength(String.valueOf(expected).length() + 1);
this.response.getOutputStream().write(expected);
assertThat(this.committed).isFalse();
this.response.getOutputStream().write(1);
assertThat(this.committed).isTrue();
}
// gh-171
@Test
public void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits() throws Exception {
givenGetOutputStreamThenReturn();
String expected = "{\n" + " \"parameterName\" : \"_csrf\",\n"
+ " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" + " \"headerName\" : \"X-CSRF-TOKEN\"\n"
+ "}";
this.response.setContentLength(expected.length() + 1);
this.response.getOutputStream().write(expected.getBytes());
assertThat(this.committed).isFalse();
this.response.getOutputStream().write("1".getBytes("UTF-8"));
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintBooleanCommits() throws Exception {
givenGetOutputStreamThenReturn();
boolean b = true;
this.response.setContentLength(1);
this.response.getOutputStream().print(b);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintCharCommits() throws Exception {
givenGetOutputStreamThenReturn();
char c = 1;
this.response.setContentLength(1);
this.response.getOutputStream().print(c);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintIntCommits() throws Exception {
givenGetOutputStreamThenReturn();
int i = 1234;
this.response.setContentLength(String.valueOf(i).length());
this.response.getOutputStream().print(i);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintLongCommits() throws Exception {
givenGetOutputStreamThenReturn();
long l = 12345;
this.response.setContentLength(String.valueOf(l).length());
this.response.getOutputStream().print(l);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintFloatCommits() throws Exception {
givenGetOutputStreamThenReturn();
float f = 12345;
this.response.setContentLength(String.valueOf(f).length());
this.response.getOutputStream().print(f);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintDoubleCommits() throws Exception {
givenGetOutputStreamThenReturn();
double x = 1.2345;
this.response.setContentLength(String.valueOf(x).length());
this.response.getOutputStream().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintStringCommits() throws Exception {
givenGetOutputStreamThenReturn();
String x = "12345";
this.response.setContentLength(x.length());
this.response.getOutputStream().print(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnCommits() throws Exception {
givenGetOutputStreamThenReturn();
this.response.setContentLength(NL.length());
this.response.getOutputStream().println();
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnBooleanCommits() throws Exception {
givenGetOutputStreamThenReturn();
boolean b = true;
this.response.setContentLength(1);
this.response.getOutputStream().println(b);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnCharCommits() throws Exception {
givenGetOutputStreamThenReturn();
char c = 1;
this.response.setContentLength(1);
this.response.getOutputStream().println(c);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnIntCommits() throws Exception {
givenGetOutputStreamThenReturn();
int i = 12345;
this.response.setContentLength(String.valueOf(i).length());
this.response.getOutputStream().println(i);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnLongCommits() throws Exception {
givenGetOutputStreamThenReturn();
long l = 12345678;
this.response.setContentLength(String.valueOf(l).length());
this.response.getOutputStream().println(l);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnFloatCommits() throws Exception {
givenGetOutputStreamThenReturn();
float f = 1234;
this.response.setContentLength(String.valueOf(f).length());
this.response.getOutputStream().println(f);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnDoubleCommits() throws Exception {
givenGetOutputStreamThenReturn();
double x = 1;
this.response.setContentLength(String.valueOf(x).length());
this.response.getOutputStream().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthOutputStreamPrintlnStringCommits() throws Exception {
givenGetOutputStreamThenReturn();
String x = "1";
this.response.setContentLength(String.valueOf(x).length());
this.response.getOutputStream().println(x);
assertThat(this.committed).isTrue();
}
@Test
public void contentLengthDoesNotCommit() {
String body = "something";
this.response.setContentLength(body.length());
assertThat(this.committed).isFalse();
}
@Test
public void contentLengthOutputStreamWriteStringCommits() throws IOException {
givenGetOutputStreamThenReturn();
String body = "something";
this.response.setContentLength(body.length());
this.response.getOutputStream().print(body);
assertThat(this.committed).isTrue();
}
// gh-7261
@Test
public void contentLengthLongOutputStreamWriteStringCommits() throws IOException {
givenGetOutputStreamThenReturn();
String body = "something";
this.response.setContentLengthLong(body.length());
this.response.getOutputStream().print(body);
assertThat(this.committed).isTrue();
}
@Test
public void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception {
givenGetWriterThenReturn();
int expected = 1234;
this.response.addHeader("Content-Length", String.valueOf(String.valueOf(expected).length()));
this.response.getWriter().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void bufferSizePrintWriterWriteCommits() throws Exception {
givenGetWriterThenReturn();
String expected = "1234567890";
given(this.response.getBufferSize()).willReturn(expected.length());
this.response.getWriter().write(expected);
assertThat(this.committed).isTrue();
}
@Test
public void bufferSizeCommitsOnce() throws Exception {
givenGetWriterThenReturn();
String expected = "1234567890";
given(this.response.getBufferSize()).willReturn(expected.length());
this.response.getWriter().write(expected);
assertThat(this.committed).isTrue();
this.committed = false;
this.response.getWriter().write(expected);
assertThat(this.committed).isFalse();
}
}
| OnCommittedResponseWrapperTests |
java | apache__maven | compat/maven-compat/src/main/java/org/apache/maven/toolchain/ToolchainManager.java | {
"start": 1165,
"end": 2427
} | interface ____ {
// NOTE: Some plugins like Surefire access this field directly!
@Deprecated
String ROLE = ToolchainManager.class.getName();
/**
* Retrieve toolchain of specified type from build context. It is expected that
* <code>maven-toolchains-plugin</code> contains the configuration to select the appropriate
* toolchain and is executed at the beginning of the build.
*
* @param type the type, must not be {@code null}
* @param context the Maven session, must not be {@code null}
* @return the toolchain selected by <code>maven-toolchains-plugin</code>
*/
Toolchain getToolchainFromBuildContext(String type, MavenSession context);
/**
* Select all toolchains available in user settings matching the type and requirements,
* independently from <code>maven-toolchains-plugin</code>.
*
* @param session the Maven session, must not be {@code null}
* @param type the type, must not be {@code null}
* @param requirements the requirements, may be {@code null}
* @return the matching toolchains, never {@code null}
* @since 3.3.0
*/
List<Toolchain> getToolchains(MavenSession session, String type, Map<String, String> requirements);
}
| ToolchainManager |
java | google__guava | android/guava/src/com/google/common/cache/RemovalNotification.java | {
"start": 1170,
"end": 1362
} | class ____
* strong references to the key and value, regardless of the type of references the cache may be
* using.
*
* @author Charles Fry
* @since 10.0
*/
@GwtCompatible
public final | holds |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/physical/RegexExtractExec.java | {
"start": 716,
"end": 2232
} | class ____ extends UnaryExec implements EstimatesRowSize {
protected final Expression inputExpression;
protected final List<Attribute> extractedFields;
protected RegexExtractExec(Source source, PhysicalPlan child, Expression inputExpression, List<Attribute> extractedFields) {
super(source, child);
this.inputExpression = inputExpression;
this.extractedFields = extractedFields;
}
@Override
public List<Attribute> output() {
return mergeOutputAttributes(extractedFields, child().output());
}
@Override
protected AttributeSet computeReferences() {
return inputExpression.references();
}
public Expression inputExpression() {
return inputExpression;
}
public List<Attribute> extractedFields() {
return extractedFields;
}
@Override
public PhysicalPlan estimateRowSize(State state) {
state.add(false, extractedFields);
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (super.equals(o) == false) return false;
RegexExtractExec that = (RegexExtractExec) o;
return Objects.equals(inputExpression, that.inputExpression) && Objects.equals(extractedFields, that.extractedFields);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), inputExpression, extractedFields);
}
}
| RegexExtractExec |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/visitor/ExecNodeVisitor.java | {
"start": 1017,
"end": 1183
} | interface ____ {
/**
* Visits a node during a traversal.
*
* @param node ExecNode to visit
*/
void visit(ExecNode<?> node);
}
| ExecNodeVisitor |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/ai/model/a2a/AgentVersionDetail.java | {
"start": 753,
"end": 2101
} | class ____ {
private String version;
private String createdAt;
private String updatedAt;
private boolean isLatest;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public boolean isLatest() {
return isLatest;
}
public void setLatest(boolean latest) {
isLatest = latest;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
AgentVersionDetail that = (AgentVersionDetail) o;
return Objects.equals(version, that.version) && Objects.equals(createdAt, that.createdAt) && Objects.equals(
updatedAt, that.updatedAt) && Objects.equals(isLatest, that.isLatest);
}
@Override
public int hashCode() {
return Objects.hash(version, createdAt, updatedAt, isLatest);
}
}
| AgentVersionDetail |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/JodaDateTimeConstantsTest.java | {
"start": 877,
"end": 1219
} | class ____ {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(JodaDateTimeConstants.class, getClass());
@Test
public void assignment() {
helper
.addSourceLines(
"TestClass.java",
"import org.joda.time.DateTimeConstants;",
"public | JodaDateTimeConstantsTest |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/support/TypeWrapper.java | {
"start": 6269,
"end": 8081
} | class ____ implements InvocationHandler, Serializable {
private final TypeProvider provider;
public TypeProxyInvocationHandler(TypeProvider provider) {
this.provider = provider;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("equals")) {
Object other = args[0];
// Unwrap proxies for speed
if (other instanceof Type) {
other = unwrap((Type) other);
}
return this.provider.getType().equals(other);
} else if (method.getName().equals("hashCode")) {
return this.provider.getType().hashCode();
} else if (method.getName().equals("getTypeProvider")) {
return this.provider;
}
if (Type.class == method.getReturnType()) {
return forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, -1));
} else if (Type[].class == method.getReturnType()) {
Type[] result = new Type[((Type[]) method.invoke(this.provider.getType(), args)).length];
for (int i = 0; i < result.length; i++) {
result[i] = forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, i));
}
return result;
}
try {
return method.invoke(this.provider.getType(), args);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
/**
* {@link TypeProvider} for {@link Type}s obtained from a {@link Field}.
*/
@SuppressWarnings("serial")
static | TypeProxyInvocationHandler |
java | spring-projects__spring-framework | spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java | {
"start": 3505,
"end": 4089
} | class ____ implements EntryProcessor<Object, Object, Object> {
private static final PutIfAbsentEntryProcessor INSTANCE = new PutIfAbsentEntryProcessor();
@Override
@SuppressWarnings("NullAway") // Overridden method does not define nullness
public @Nullable Object process(MutableEntry<Object, @Nullable Object> entry, @Nullable Object... arguments) throws EntryProcessorException {
Object existingValue = entry.getValue();
if (existingValue == null) {
entry.setValue(arguments[0]);
}
return existingValue;
}
}
private static final | PutIfAbsentEntryProcessor |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java | {
"start": 34342,
"end": 34790
} | enum ____ {
ONE,
TWO,
UNRECOGNIZED
}
boolean m(Case c) {
return switch (c) {
case ONE -> true;
case TWO -> false;
default -> throw new AssertionError();
};
}
}
""")
.addOutputLines(
"out/Test.java",
"""
| Case |
java | quarkusio__quarkus | independent-projects/arc/tcks/arquillian/src/main/java/io/quarkus/arc/arquillian/ArcProtocol.java | {
"start": 7503,
"end": 8861
} | class ____<T> implements InjectionPoint {
private final Parameter parameter;
private final BeanManager beanManager;
FakeInjectionPoint(Parameter parameter, BeanManager beanManager) {
this.parameter = parameter;
this.beanManager = beanManager;
}
public Type getType() {
return parameter.getParameterizedType();
}
public Set<Annotation> getQualifiers() {
Set<Annotation> qualifiers = new HashSet<>();
for (Annotation annotation : parameter.getAnnotations()) {
if (beanManager.isQualifier(annotation.annotationType())) {
qualifiers.add(annotation);
}
}
return qualifiers;
}
public Bean<?> getBean() {
Set<Bean<?>> beans = beanManager.getBeans(getType(), getQualifiers().toArray(new Annotation[0]));
return beanManager.resolve(beans);
}
public Member getMember() {
return parameter.getDeclaringExecutable();
}
public Annotated getAnnotated() {
return new FakeAnnotatedParameter<T>();
}
public boolean isDelegate() {
return false;
}
public boolean isTransient() {
return false;
}
| FakeInjectionPoint |
java | apache__hadoop | hadoop-tools/hadoop-sls/src/main/java/org/apache/hadoop/yarn/sls/synthetic/SynthUtils.java | {
"start": 1211,
"end": 2878
} | class ____ not meant to be instantiated
}
public static int getWeighted(Collection<Double> weights, Random rr) {
double totalWeight = 0;
for (Double i : weights) {
totalWeight += i;
}
double rand = rr.nextDouble() * totalWeight;
double cur = 0;
int ind = 0;
for (Double i : weights) {
cur += i;
if (cur > rand) {
break;
}
ind++;
}
return ind;
}
public static NormalDistribution getNormalDist(JDKRandomGenerator rand,
double average, double stdDev) {
if (average <= 0) {
return null;
}
// set default for missing param
if (stdDev == 0) {
stdDev = average / 6;
}
NormalDistribution ret = new NormalDistribution(average, stdDev,
NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
ret.reseedRandomGenerator(rand.nextLong());
return ret;
}
public static LogNormalDistribution getLogNormalDist(JDKRandomGenerator rand,
double mean, double stdDev) {
if (mean <= 0) {
return null;
}
// set default for missing param
if (stdDev == 0) {
stdDev = mean / 6;
}
// derive lognormal parameters for X = LogNormal(mu, sigma)
// sigma^2 = ln (1+Var[X]/(E[X])^2)
// mu = ln(E[X]) - 1/2 * sigma^2
double var = stdDev * stdDev;
double sigmasq = Math.log1p(var / (mean * mean));
double sigma = Math.sqrt(sigmasq);
double mu = Math.log(mean) - 0.5 * sigmasq;
LogNormalDistribution ret = new LogNormalDistribution(mu, sigma,
LogNormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
ret.reseedRandomGenerator(rand.nextLong());
return ret;
}
}
| is |
java | spring-projects__spring-boot | module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextType.java | {
"start": 791,
"end": 1180
} | enum ____ {
/**
* The management context is the same as the main application context.
*/
SAME,
/**
* The management context is a separate context that is a child of the main
* application context.
*/
CHILD,
/**
* The management context can be either the same as the main application context or a
* child of the main application context.
*/
ANY
}
| ManagementContextType |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/ToOneMultipleFetchesTest.java | {
"start": 6467,
"end": 6799
} | class ____ {
@Id
private Long id;
@ManyToOne( fetch = FetchType.LAZY )
private EntityB entityB;
public EntityA() {
}
public EntityA(Long id, EntityB entityB) {
this.id = id;
this.entityB = entityB;
}
public EntityB getEntityB() {
return entityB;
}
}
@Entity( name = "EntityB" )
public static | EntityA |
java | netty__netty | handler/src/test/java/io/netty/handler/ssl/OpenSslJdkSslEngineInteroptTest.java | {
"start": 1251,
"end": 7859
} | class ____ extends SSLEngineTest {
public OpenSslJdkSslEngineInteroptTest() {
super(SslProvider.isTlsv13Supported(SslProvider.JDK) &&
SslProvider.isTlsv13Supported(SslProvider.OPENSSL));
}
@Override
protected List<SSLEngineTestParam> newTestParams() {
List<SSLEngineTestParam> params = super.newTestParams();
List<SSLEngineTestParam> testParams = new ArrayList<SSLEngineTestParam>();
for (SSLEngineTestParam param: params) {
OpenSslEngineTestParam.expandCombinations(param, testParams);
}
return testParams;
}
@BeforeAll
public static void checkOpenSsl() {
OpenSsl.ensureAvailability();
}
@Override
protected SslProvider sslClientProvider() {
return SslProvider.OPENSSL;
}
@Override
protected SslProvider sslServerProvider() {
return SslProvider.JDK;
}
@MethodSource("newTestParams")
@ParameterizedTest
@Disabled /* Does the JDK support a "max certificate chain length"? */
@Override
public void testMutualAuthValidClientCertChainTooLongFailOptionalClientAuth(SSLEngineTestParam param)
throws Exception {
}
@MethodSource("newTestParams")
@ParameterizedTest
@Disabled /* Does the JDK support a "max certificate chain length"? */
@Override
public void testMutualAuthValidClientCertChainTooLongFailRequireClientAuth(SSLEngineTestParam param)
throws Exception {
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testMutualAuthInvalidIntermediateCASucceedWithOptionalClientAuth(SSLEngineTestParam param)
throws Exception {
checkShouldUseKeyManagerFactory();
super.testMutualAuthInvalidIntermediateCASucceedWithOptionalClientAuth(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testMutualAuthInvalidIntermediateCAFailWithOptionalClientAuth(SSLEngineTestParam param)
throws Exception {
checkShouldUseKeyManagerFactory();
super.testMutualAuthInvalidIntermediateCAFailWithOptionalClientAuth(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testMutualAuthInvalidIntermediateCAFailWithRequiredClientAuth(SSLEngineTestParam param)
throws Exception {
checkShouldUseKeyManagerFactory();
super.testMutualAuthInvalidIntermediateCAFailWithRequiredClientAuth(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionAfterHandshakeKeyManagerFactoryMutualAuth(SSLEngineTestParam param) throws Exception {
checkShouldUseKeyManagerFactory();
super.testSessionAfterHandshakeKeyManagerFactoryMutualAuth(param);
}
@Override
protected boolean mySetupMutualAuthServerIsValidServerException(Throwable cause) {
// TODO(scott): work around for a JDK issue. The exception should be SSLHandshakeException.
return super.mySetupMutualAuthServerIsValidServerException(cause) || causedBySSLException(cause);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testHandshakeSession(SSLEngineTestParam param) throws Exception {
checkShouldUseKeyManagerFactory();
super.testHandshakeSession(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSupportedSignatureAlgorithms(SSLEngineTestParam param) throws Exception {
checkShouldUseKeyManagerFactory();
super.testSupportedSignatureAlgorithms(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionLocalWhenNonMutualWithKeyManager(SSLEngineTestParam param) throws Exception {
checkShouldUseKeyManagerFactory();
super.testSessionLocalWhenNonMutualWithKeyManager(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionLocalWhenNonMutualWithoutKeyManager(SSLEngineTestParam param) throws Exception {
// This only really works when the KeyManagerFactory is supported as otherwise we not really know when
// we need to provide a cert.
assumeTrue(OpenSsl.supportsKeyManagerFactory());
super.testSessionLocalWhenNonMutualWithoutKeyManager(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionCache(SSLEngineTestParam param) throws Exception {
assumeTrue(OpenSsl.isSessionCacheSupported());
super.testSessionCache(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionCacheTimeout(SSLEngineTestParam param) throws Exception {
assumeTrue(OpenSsl.isSessionCacheSupported());
super.testSessionCacheTimeout(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testSessionCacheSize(SSLEngineTestParam param) throws Exception {
assumeTrue(OpenSsl.isSessionCacheSupported());
super.testSessionCacheSize(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@Override
public void testRSASSAPSS(SSLEngineTestParam param) throws Exception {
assumeFalse(PlatformDependent.javaVersion() == 26, "Fails on JDK26, possible JDK bug?");
checkShouldUseKeyManagerFactory();
super.testRSASSAPSS(param);
}
private static boolean isWrappingTrustManagerSupported() {
return OpenSslX509TrustManagerWrapper.isWrappingSupported();
}
@MethodSource("newTestParams")
@ParameterizedTest
@EnabledIf("isWrappingTrustManagerSupported")
@Override
public void testUsingX509TrustManagerVerifiesHostname(SSLEngineTestParam param) throws Exception {
super.testUsingX509TrustManagerVerifiesHostname(param);
}
@MethodSource("newTestParams")
@ParameterizedTest
@EnabledIf("isWrappingTrustManagerSupported")
@Override
public void testUsingX509TrustManagerVerifiesSNIHostname(SSLEngineTestParam param) throws Exception {
super.testUsingX509TrustManagerVerifiesSNIHostname(param);
}
@Override
protected SSLEngine wrapEngine(SSLEngine engine) {
return Java8SslTestUtils.wrapSSLEngineForTesting(engine);
}
@Override
protected SslContext wrapContext(SSLEngineTestParam param, SslContext context) {
return OpenSslEngineTestParam.wrapContext(param, context);
}
}
| OpenSslJdkSslEngineInteroptTest |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/asm/MethodWriter.java | {
"start": 1951,
"end": 12058
} | class ____ to which this method must be added.
*/
final ClassWriter cw;
/**
* Access flags of this method.
*/
private int access;
/**
* The index of the constant pool item that contains the name of this method.
*/
private final int name;
/**
* The index of the constant pool item that contains the descriptor of this method.
*/
private final int desc;
/**
* Number of exceptions that can be thrown by this method.
*/
int exceptionCount;
/**
* The exceptions that can be thrown by this method. More precisely, this array contains the indexes of the constant
* pool items that contain the internal names of these exception classes.
*/
int[] exceptions;
/**
* The bytecode of this method.
*/
private ByteVector code = new ByteVector();
/**
* Maximum stack size of this method.
*/
private int maxStack;
/**
* Maximum number of local variables for this method.
*/
private int maxLocals;
// ------------------------------------------------------------------------
/*
* Fields for the control flow graph analysis algorithm (used to compute the maximum stack size). A control flow
* graph contains one node per "basic block", and one edge per "jump" from one basic block to another. Each node
* (i.e., each basic block) is represented by the Label object that corresponds to the first instruction of this
* basic block. Each node also stores the list of its successors in the graph, as a linked list of Edge objects.
*/
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
public MethodWriter(final ClassWriter cw, final int access, final String name, final String desc, final String signature, final String[] exceptions){
if (cw.firstMethod == null) {
cw.firstMethod = this;
} else {
cw.lastMethod.next = this;
}
cw.lastMethod = this;
this.cw = cw;
this.access = access;
this.name = cw.newUTF8(name);
this.desc = cw.newUTF8(desc);
if (exceptions != null && exceptions.length > 0) {
exceptionCount = exceptions.length;
this.exceptions = new int[exceptionCount];
for (int i = 0; i < exceptionCount; ++i) {
this.exceptions[i] = cw.newClassItem(exceptions[i]).index;
}
}
}
// ------------------------------------------------------------------------
// Implementation of the MethodVisitor interface
// ------------------------------------------------------------------------
public void visitInsn(final int opcode) {
// adds the instruction to the bytecode of the method
code.putByte(opcode);
// update currentBlock
// Label currentBlock = this.currentBlock;
}
public void visitIntInsn(final int opcode, final int operand) {
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
// if (opcode == Opcodes.SIPUSH) {
// code.put12(opcode, operand);
// } else { // BIPUSH or NEWARRAY
code.put11(opcode, operand);
// }
}
public void visitVarInsn(final int opcode, final int var) {
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
if (var < 4 && opcode != Opcodes.RET) {
int opt;
if (opcode < Opcodes.ISTORE) {
/* ILOAD_0 */
opt = 26 + ((opcode - Opcodes.ILOAD) << 2) + var;
} else {
/* ISTORE_0 */
opt = 59 + ((opcode - Opcodes.ISTORE) << 2) + var;
}
code.putByte(opt);
} else if (var >= 256) {
code.putByte(196 /* WIDE */).put12(opcode, var);
} else {
code.put11(opcode, var);
}
}
public void visitTypeInsn(final int opcode, final String type) {
Item i = cw.newClassItem(type);
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
code.put12(opcode, i.index);
}
public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
Item i = cw.newFieldItem(owner, name, desc);
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
code.put12(opcode, i.index);
}
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) {
boolean itf = opcode == Opcodes.INVOKEINTERFACE;
Item i = cw.newMethodItem(owner, name, desc, itf);
int argSize = i.intVal;
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
if (itf) {
if (argSize == 0) {
argSize = Type.getArgumentsAndReturnSizes(desc);
i.intVal = argSize;
}
code.put12(Opcodes.INVOKEINTERFACE, i.index).put11(argSize >> 2, 0);
} else {
code.put12(opcode, i.index);
}
}
public void visitJumpInsn(final int opcode, final Label label) {
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
if ((label.status & 2 /* Label.RESOLVED */ ) != 0 && label.position - code.length < Short.MIN_VALUE) {
throw new UnsupportedOperationException();
} else {
/*
* case of a backward jump with an offset >= -32768, or of a forward jump with, of course, an unknown
* offset. In these cases we store the offset in 2 bytes (which will be increased in resizeInstructions, if
* needed).
*/
code.putByte(opcode);
// Currently, GOTO_W is the only supported wide reference
label.put(this, code, code.length - 1, opcode == Opcodes.GOTO_W);
}
}
public void visitLabel(final Label label) {
// resolves previous forward references to label, if any
label.resolve(this, code.length, code.data);
}
public void visitLdcInsn(final Object cst) {
Item i = cw.newConstItem(cst);
// Label currentBlock = this.currentBlock;
// adds the instruction to the bytecode of the method
int index = i.index;
if (i.type == 5 /* ClassWriter.LONG */ || i.type == 6 /* ClassWriter.DOUBLE */) {
code.put12(20 /* LDC2_W */, index);
} else if (index >= 256) {
code.put12(19 /* LDC_W */, index);
} else {
code.put11(18 /*Opcodes.LDC*/, index);
}
}
public void visitIincInsn(final int var, final int increment) {
// adds the instruction to the bytecode of the method
// if ((var > 255) || (increment > 127) || (increment < -128)) {
// code.putByte(196 /* WIDE */).put12(Opcodes.IINC, var).putShort(increment);
// } else {
code.putByte(132 /* Opcodes.IINC*/ ).put11(var, increment);
// }
}
public void visitMaxs(final int maxStack, final int maxLocals) {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
}
public void visitEnd() {
}
// ------------------------------------------------------------------------
// Utility methods: control flow analysis algorithm
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Utility methods: stack map frames
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Utility methods: dump bytecode array
// ------------------------------------------------------------------------
/**
* Returns the size of the bytecode of this method.
*
* @return the size of the bytecode of this method.
*/
final int getSize() {
int size = 8;
if (code.length > 0) {
cw.newUTF8("Code");
size += 18 + code.length + 8 * 0;
}
if (exceptionCount > 0) {
cw.newUTF8("Exceptions");
size += 8 + 2 * exceptionCount;
}
return size;
}
/**
* Puts the bytecode of this method in the given byte vector.
*
* @param out the byte vector into which the bytecode of this method must be copied.
*/
final void put(final ByteVector out) {
final int mask = 393216; //Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC));
out.putShort(access & ~mask).putShort(name).putShort(desc);
int attributeCount = 0;
if (code.length > 0) {
++attributeCount;
}
if (exceptionCount > 0) {
++attributeCount;
}
out.putShort(attributeCount);
if (code.length > 0) {
int size = 12 + code.length + 8 * 0; // handlerCount
out.putShort(cw.newUTF8("Code")).putInt(size);
out.putShort(maxStack).putShort(maxLocals);
out.putInt(code.length).putByteArray(code.data, 0, code.length);
out.putShort(0); // handlerCount
attributeCount = 0;
out.putShort(attributeCount);
}
if (exceptionCount > 0) {
out.putShort(cw.newUTF8("Exceptions")).putInt(2 * exceptionCount + 2);
out.putShort(exceptionCount);
for (int i = 0; i < exceptionCount; ++i) {
out.putShort(exceptions[i]);
}
}
}
}
| writer |
java | spring-projects__spring-boot | loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Library.java | {
"start": 1059,
"end": 4290
} | class ____ {
private final String name;
private final @Nullable File file;
private final @Nullable LibraryScope scope;
private final @Nullable LibraryCoordinates coordinates;
private final boolean unpackRequired;
private final boolean local;
private final boolean included;
/**
* Create a new {@link Library}.
* @param file the source file
* @param scope the scope of the library
*/
public Library(File file, LibraryScope scope) {
this(null, file, scope, null, false, false, true);
}
/**
* Create a new {@link Library}.
* @param name the name of the library as it should be written or {@code null} to use
* the file name
* @param file the source file
* @param scope the scope of the library
* @param coordinates the library coordinates or {@code null}
* @param unpackRequired if the library needs to be unpacked before it can be used
* @param local if the library is local (part of the same build) to the application
* that is being packaged
* @param included if the library is included in the uber jar
* @since 2.4.8
*/
public Library(@Nullable String name, @Nullable File file, @Nullable LibraryScope scope,
@Nullable LibraryCoordinates coordinates, boolean unpackRequired, boolean local, boolean included) {
this.name = (name != null) ? name : getFileName(file);
this.file = file;
this.scope = scope;
this.coordinates = coordinates;
this.unpackRequired = unpackRequired;
this.local = local;
this.included = included;
}
private static String getFileName(@Nullable File file) {
Assert.state(file != null, "'file' must not be null");
return file.getName();
}
/**
* Return the name of file as it should be written.
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Return the library file.
* @return the file
*/
public @Nullable File getFile() {
return this.file;
}
/**
* Open a stream that provides the content of the source file.
* @return the file content
* @throws IOException on error
*/
InputStream openStream() throws IOException {
Assert.state(this.file != null, "'file' must not be null");
return new FileInputStream(this.file);
}
/**
* Return the scope of the library.
* @return the scope
*/
public @Nullable LibraryScope getScope() {
return this.scope;
}
/**
* Return the {@linkplain LibraryCoordinates coordinates} of the library.
* @return the coordinates
*/
public @Nullable LibraryCoordinates getCoordinates() {
return this.coordinates;
}
/**
* Return if the file cannot be used directly as a nested jar and needs to be
* unpacked.
* @return if unpack is required
*/
public boolean isUnpackRequired() {
return this.unpackRequired;
}
long getLastModified() {
Assert.state(this.file != null, "'file' must not be null");
return this.file.lastModified();
}
/**
* Return if the library is local (part of the same build) to the application that is
* being packaged.
* @return if the library is local
*/
public boolean isLocal() {
return this.local;
}
/**
* Return if the library is included in the uber jar.
* @return if the library is included
*/
public boolean isIncluded() {
return this.included;
}
}
| Library |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java | {
"start": 17091,
"end": 17126
} | class ____"));
}
}
}
| loader |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/processor/AbstractSalesforceProcessor.java | {
"start": 9234,
"end": 9369
} | class ____ fully qualified name
* @return Class, if found.
* @throws SalesforceException if unable to find | by |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/groups/GenericValueMetricGroup.java | {
"start": 1336,
"end": 2073
} | class ____ extends GenericMetricGroup {
private String key;
private final String value;
GenericValueMetricGroup(MetricRegistry registry, GenericKeyMetricGroup parent, String value) {
super(registry, parent, value);
this.key = parent.getGroupName(name -> name);
this.value = value;
}
// ------------------------------------------------------------------------
@Override
protected void putVariables(Map<String, String> variables) {
variables.put(ScopeFormat.asVariable(this.key), value);
}
@Override
protected String createLogicalScope(CharacterFilter filter, char delimiter) {
return parent.getLogicalScope(filter, delimiter);
}
}
| GenericValueMetricGroup |
java | resilience4j__resilience4j | resilience4j-cache/src/main/java/io/github/resilience4j/cache/event/CacheOnErrorEvent.java | {
"start": 760,
"end": 1369
} | class ____ extends AbstractCacheEvent {
private final Throwable throwable;
public CacheOnErrorEvent(String cacheName, Throwable throwable) {
super(cacheName);
this.throwable = throwable;
}
@Override
public Type getEventType() {
return Type.ERROR;
}
public Throwable getThrowable() {
return throwable;
}
@Override
public String toString() {
return String.format("%s: Cache '%s' recorded an error: '%s'.",
getCreationTime(),
getCacheName(),
getThrowable().toString());
}
}
| CacheOnErrorEvent |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/task/support/CompositeTaskDecorator.java | {
"start": 984,
"end": 1657
} | class ____ implements TaskDecorator {
private final List<TaskDecorator> taskDecorators;
/**
* Create a new instance.
* @param taskDecorators the taskDecorators to delegate to
*/
public CompositeTaskDecorator(Collection<? extends TaskDecorator> taskDecorators) {
Assert.notNull(taskDecorators, "TaskDecorators must not be null");
this.taskDecorators = new ArrayList<>(taskDecorators);
}
@Override
public Runnable decorate(Runnable runnable) {
Assert.notNull(runnable, "Runnable must not be null");
for (TaskDecorator taskDecorator : this.taskDecorators) {
runnable = taskDecorator.decorate(runnable);
}
return runnable;
}
}
| CompositeTaskDecorator |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/ApiVersions.java | {
"start": 1090,
"end": 1157
} | class ____ intended for INTERNAL usage only within Kafka.
*/
public | is |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/StreamBufferingEncoder.java | {
"start": 2885,
"end": 3417
} | class ____ {
private final int lastStreamId;
private final long errorCode;
private final byte[] debugData;
GoAwayDetail(int lastStreamId, long errorCode, byte[] debugData) {
this.lastStreamId = lastStreamId;
this.errorCode = errorCode;
this.debugData = debugData.clone();
}
}
/**
* Thrown by {@link StreamBufferingEncoder} if buffered streams are terminated due to
* receipt of a {@code GOAWAY}.
*/
public static final | GoAwayDetail |
java | greenrobot__greendao | tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/entity/TransactionTest.java | {
"start": 256,
"end": 1071
} | class ____ extends TestEntityTestBase {
public void testUpdateTxFailed() {
String sql = "CREATE UNIQUE INDEX test_simple_string_unique ON " + TestEntityDao.TABLENAME + "(" +
Properties.SimpleString.columnName + ")";
dao.getDatabase().execSQL(sql);
ArrayList<TestEntity> entities = insert(2);
TestEntity entity1 = entities.get(0);
String valueBeforeUpdate = entity1.getSimpleString();
entity1.setSimpleString("unique");
entities.get(1).setSimpleString("unique");
try {
dao.updateInTx(entities);
fail("Should have thrown");
} catch (RuntimeException e) {
// OK
}
dao.refresh(entity1);
assertEquals(valueBeforeUpdate, entity1.getSimpleString());
}
}
| TransactionTest |
java | apache__camel | core/camel-core-reifier/src/main/java/org/apache/camel/reifier/errorhandler/DefaultErrorHandlerReifier.java | {
"start": 1493,
"end": 6074
} | class ____ extends ErrorHandlerReifier<DefaultErrorHandlerDefinition> {
public DefaultErrorHandlerReifier(Route route, DefaultErrorHandlerDefinition definition) {
super(route, definition);
}
@Override
public Processor createErrorHandler(Processor processor) throws Exception {
// optimize to use shared default instance if using out of the box settings
RedeliveryPolicy redeliveryPolicy = resolveRedeliveryPolicy(definition, camelContext);
CamelLogger logger = resolveLogger(definition);
DefaultErrorHandler answer = new DefaultErrorHandler(
camelContext, processor, logger,
getProcessor(definition.getOnRedeliveryProcessor(), definition.getOnRedeliveryRef()),
redeliveryPolicy,
getPredicate(definition.getRetryWhilePredicate(), definition.getRetryWhileRef()),
getExecutorService(definition.getExecutorServiceBean(), definition.getExecutorServiceRef()),
getProcessor(definition.getOnPrepareFailureProcessor(), definition.getOnPrepareFailureRef()),
getProcessor(definition.getOnExceptionOccurredProcessor(), definition.getOnExceptionOccurredRef()));
// configure error handler before we can use it
configure(answer);
return answer;
}
private CamelLogger resolveLogger(DefaultErrorHandlerDefinition definition) {
CamelLogger answer = definition.getLoggerBean();
if (answer == null && definition.getLoggerRef() != null) {
answer = mandatoryLookup(definition.getLoggerRef(), CamelLogger.class);
}
if (answer == null) {
answer = new CamelLogger(LoggerFactory.getLogger(DefaultErrorHandler.class), LoggingLevel.ERROR);
}
if (definition.getLevel() != null) {
answer.setLevel(parse(LoggingLevel.class, definition.getLevel()));
}
return answer;
}
private RedeliveryPolicy resolveRedeliveryPolicy(DefaultErrorHandlerDefinition definition, CamelContext camelContext) {
if (definition.hasRedeliveryPolicy() && definition.getRedeliveryPolicyRef() != null) {
throw new IllegalArgumentException(
"Cannot have both redeliveryPolicy and redeliveryPolicyRef set at the same time.");
}
RedeliveryPolicy answer = null;
RedeliveryPolicyDefinition def = definition.hasRedeliveryPolicy() ? definition.getRedeliveryPolicy() : null;
if (def != null) {
answer = ErrorHandlerReifier.createRedeliveryPolicy(def, camelContext, null);
}
if (def == null && definition.getRedeliveryPolicyRef() != null) {
answer = mandatoryLookup(definition.getRedeliveryPolicyRef(), RedeliveryPolicy.class);
}
if (answer == null) {
answer = RedeliveryPolicy.DEFAULT_POLICY;
}
return answer;
}
protected ScheduledExecutorService getExecutorService(
ScheduledExecutorService executorService, String executorServiceRef) {
lock.lock();
try {
executorServiceRef = parseString(executorServiceRef);
if (executorService == null || executorService.isShutdown()) {
// camel context will shutdown the executor when it shutdown so no
// need to shut it down when stopping
if (executorServiceRef != null) {
executorService = lookupByNameAndType(executorServiceRef, ScheduledExecutorService.class);
if (executorService == null) {
ExecutorServiceManager manager = camelContext.getExecutorServiceManager();
ThreadPoolProfile profile = manager.getThreadPoolProfile(executorServiceRef);
executorService = manager.newScheduledThreadPool(this, executorServiceRef, profile);
}
if (executorService == null) {
throw new IllegalArgumentException("ExecutorService " + executorServiceRef + " not found in registry.");
}
} else {
// no explicit configured thread pool, so leave it up to the
// error handler to decide if it need a default thread pool from
// CamelContext#getErrorHandlerExecutorService
executorService = null;
}
}
return executorService;
} finally {
lock.unlock();
}
}
}
| DefaultErrorHandlerReifier |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/monitor/process/ProcessStats.java | {
"start": 2403,
"end": 4020
} | class ____ {
static final String PROCESS = "process";
static final String TIMESTAMP = "timestamp";
static final String OPEN_FILE_DESCRIPTORS = "open_file_descriptors";
static final String MAX_FILE_DESCRIPTORS = "max_file_descriptors";
static final String CPU = "cpu";
static final String PERCENT = "percent";
static final String TOTAL = "total";
static final String TOTAL_IN_MILLIS = "total_in_millis";
static final String MEM = "mem";
static final String TOTAL_VIRTUAL = "total_virtual";
static final String TOTAL_VIRTUAL_IN_BYTES = "total_virtual_in_bytes";
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.PROCESS);
builder.field(Fields.TIMESTAMP, timestamp);
builder.field(Fields.OPEN_FILE_DESCRIPTORS, openFileDescriptors);
builder.field(Fields.MAX_FILE_DESCRIPTORS, maxFileDescriptors);
if (cpu != null) {
builder.startObject(Fields.CPU);
builder.field(Fields.PERCENT, cpu.percent);
builder.humanReadableField(Fields.TOTAL_IN_MILLIS, Fields.TOTAL, new TimeValue(cpu.total));
builder.endObject();
}
if (mem != null) {
builder.startObject(Fields.MEM);
builder.humanReadableField(Fields.TOTAL_VIRTUAL_IN_BYTES, Fields.TOTAL_VIRTUAL, ByteSizeValue.ofBytes(mem.totalVirtual));
builder.endObject();
}
builder.endObject();
return builder;
}
public static | Fields |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/BinderIdentityRestoredDangerouslyTest.java | {
"start": 2353,
"end": 2741
} | class ____ {
void foo() {
long identity = Binder.clearCallingIdentity();
// Do something (typically Binder IPC)
// BUG: Diagnostic contains: Binder.restoreCallingIdentity() in a finally block
Binder.restoreCallingIdentity(identity);
}
}
""")
.doTest();
}
}
| InFinally |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/windowing/assigners/GlobalWindows.java | {
"start": 1662,
"end": 3319
} | class ____ extends WindowAssigner<Object, GlobalWindow> {
private static final long serialVersionUID = 1L;
@Nullable private final Trigger<Object, GlobalWindow> defaultTrigger;
private GlobalWindows(Trigger<Object, GlobalWindow> defaultTrigger) {
this.defaultTrigger = defaultTrigger;
}
@Override
public Collection<GlobalWindow> assignWindows(
Object element, long timestamp, WindowAssignerContext context) {
return Collections.singletonList(GlobalWindow.get());
}
@Override
public Trigger<Object, GlobalWindow> getDefaultTrigger() {
return defaultTrigger == null ? new NeverTrigger() : defaultTrigger;
}
@Override
public String toString() {
return "GlobalWindows(trigger=" + getDefaultTrigger().getClass().getSimpleName() + ")";
}
/**
* Creates a {@link WindowAssigner} that assigns all elements to the same {@link GlobalWindow}.
* The window is only useful if you also specify a custom trigger. Otherwise, the window will
* never be triggered and no computation will be performed.
*/
public static GlobalWindows create() {
return new GlobalWindows(new NeverTrigger());
}
/**
* Creates a {@link WindowAssigner} that assigns all elements to the same {@link GlobalWindow}
* and the window is triggered if and only if the input stream is ended.
*/
public static GlobalWindows createWithEndOfStreamTrigger() {
return new GlobalWindows(new EndOfStreamTrigger());
}
/** A trigger that never fires, as default Trigger for GlobalWindows. */
@Internal
public static | GlobalWindows |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldMatch.java | {
"start": 989,
"end": 2762
} | class ____ extends BasicErrorMessageFactory {
// @format:off
public static final String ADVICE = format("%n%n"+
"You can use 'matches(Predicate p, String description)' to have a better error message%n" +
"For example:%n" +
" assertThat(player).matches(p -> p.isRookie(), \"is rookie\");%n" +
"will give an error message looking like:%n" +
"%n" +
"Expecting actual:%n" +
" player%n" +
"to match 'is rookie' predicate");
// @format:on
/**
* Creates a new <code>{@link ShouldMatch}</code>.
*
* @param <T> guarantees that the type of the actual value and the generic type of the {@code Predicate} are the same.
* @param actual the actual value in the failed assertion.
* @param predicate the {@code Predicate}.
* @param predicateDescription predicate description to include in the error message
* @return the created {@code ErrorMessageFactory}.
*/
public static <T> ErrorMessageFactory shouldMatch(T actual, Predicate<? super T> predicate,
PredicateDescription predicateDescription) {
requireNonNull(predicateDescription, "The predicate description must not be null");
return new ShouldMatch(actual, predicateDescription);
}
private ShouldMatch(Object actual, PredicateDescription description) {
super("%nExpecting actual:%n %s%nto match %s predicate." + (description.isDefault() ? ADVICE : ""), actual, description);
}
}
| ShouldMatch |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/LocalRepositoryManager.java | {
"start": 1825,
"end": 2146
} | interface ____ part of Maven's repository management system and works in
* conjunction with {@link RemoteRepository} and {@link LocalRepository} to provide
* a complete artifact resolution and storage solution.
*
* @since 4.0.0
* @see LocalRepository
* @see RemoteRepository
* @see Artifact
*/
@Experimental
public | is |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionEncoder.java | {
"start": 1685,
"end": 20206
} | class ____ implements Http2ConnectionEncoder, Http2SettingsReceivedConsumer {
private final Http2FrameWriter frameWriter;
private final Http2Connection connection;
private Http2LifecycleManager lifecycleManager;
// We prefer ArrayDeque to LinkedList because later will produce more GC.
// This initial capacity is plenty for SETTINGS traffic.
private final Queue<Http2Settings> outstandingLocalSettingsQueue = new ArrayDeque<Http2Settings>(4);
private Queue<Http2Settings> outstandingRemoteSettingsQueue;
public DefaultHttp2ConnectionEncoder(Http2Connection connection, Http2FrameWriter frameWriter) {
this.connection = checkNotNull(connection, "connection");
this.frameWriter = checkNotNull(frameWriter, "frameWriter");
if (connection.remote().flowController() == null) {
connection.remote().flowController(new DefaultHttp2RemoteFlowController(connection));
}
}
@Override
public void lifecycleManager(Http2LifecycleManager lifecycleManager) {
this.lifecycleManager = checkNotNull(lifecycleManager, "lifecycleManager");
}
@Override
public Http2FrameWriter frameWriter() {
return frameWriter;
}
@Override
public Http2Connection connection() {
return connection;
}
@Override
public final Http2RemoteFlowController flowController() {
return connection().remote().flowController();
}
@Override
public void remoteSettings(Http2Settings settings) throws Http2Exception {
Boolean pushEnabled = settings.pushEnabled();
Http2FrameWriter.Configuration config = configuration();
Http2HeadersEncoder.Configuration outboundHeaderConfig = config.headersConfiguration();
Http2FrameSizePolicy outboundFrameSizePolicy = config.frameSizePolicy();
if (pushEnabled != null) {
if (!connection.isServer() && pushEnabled) {
throw connectionError(PROTOCOL_ERROR,
"Client received a value of ENABLE_PUSH specified to other than 0");
}
connection.remote().allowPushTo(pushEnabled);
}
Long maxConcurrentStreams = settings.maxConcurrentStreams();
if (maxConcurrentStreams != null) {
connection.local().maxActiveStreams((int) min(maxConcurrentStreams, MAX_VALUE));
}
Long headerTableSize = settings.headerTableSize();
if (headerTableSize != null) {
outboundHeaderConfig.maxHeaderTableSize(headerTableSize);
}
Long maxHeaderListSize = settings.maxHeaderListSize();
if (maxHeaderListSize != null) {
outboundHeaderConfig.maxHeaderListSize(maxHeaderListSize);
}
Integer maxFrameSize = settings.maxFrameSize();
if (maxFrameSize != null) {
outboundFrameSizePolicy.maxFrameSize(maxFrameSize);
}
Integer initialWindowSize = settings.initialWindowSize();
if (initialWindowSize != null) {
flowController().initialWindowSize(initialWindowSize);
}
}
@Override
public ChannelFuture writeData(final ChannelHandlerContext ctx, final int streamId, ByteBuf data, int padding,
final boolean endOfStream, ChannelPromise promise) {
promise = promise.unvoid();
final Http2Stream stream;
try {
stream = requireStream(streamId);
// Verify that the stream is in the appropriate state for sending DATA frames.
switch (stream.state()) {
case OPEN:
case HALF_CLOSED_REMOTE:
// Allowed sending DATA frames in these states.
break;
default:
throw new IllegalStateException("Stream " + stream.id() + " in unexpected state " + stream.state());
}
} catch (Throwable e) {
data.release();
return promise.setFailure(e);
}
// Hand control of the frame to the flow controller.
flowController().addFlowControlled(stream,
new FlowControlledData(stream, data, padding, endOfStream, promise));
return promise;
}
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, false, 0, (short) 0, false, padding, endStream, promise);
}
private static boolean validateHeadersSentState(Http2Stream stream, Http2Headers headers, boolean isServer,
boolean endOfStream) {
boolean isInformational = isServer && HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;
if ((isInformational || !endOfStream) && stream.isHeadersSent() || stream.isTrailersSent()) {
throw new IllegalStateException("Stream " + stream.id() + " sent too many headers EOS: " + endOfStream);
}
return isInformational;
}
@Override
public ChannelFuture writeHeaders(final ChannelHandlerContext ctx, final int streamId,
final Http2Headers headers, final int streamDependency, final short weight,
final boolean exclusive, final int padding, final boolean endOfStream, ChannelPromise promise) {
return writeHeaders0(ctx, streamId, headers, true, streamDependency,
weight, exclusive, padding, endOfStream, promise);
}
/**
* Write headers via {@link Http2FrameWriter}. If {@code hasPriority} is {@code false} it will ignore the
* {@code streamDependency}, {@code weight} and {@code exclusive} parameters.
*/
private static ChannelFuture sendHeaders(Http2FrameWriter frameWriter, ChannelHandlerContext ctx, int streamId,
Http2Headers headers, final boolean hasPriority,
int streamDependency, final short weight,
boolean exclusive, final int padding,
boolean endOfStream, ChannelPromise promise) {
if (hasPriority) {
return frameWriter.writeHeaders(ctx, streamId, headers, streamDependency,
weight, exclusive, padding, endOfStream, promise);
}
return frameWriter.writeHeaders(ctx, streamId, headers, padding, endOfStream, promise);
}
private ChannelFuture writeHeaders0(final ChannelHandlerContext ctx, final int streamId,
final Http2Headers headers, final boolean hasPriority,
final int streamDependency, final short weight,
final boolean exclusive, final int padding,
final boolean endOfStream, ChannelPromise promise) {
try {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
try {
// We don't create the stream in a `halfClosed` state because if this is an initial
// HEADERS frame we don't want the connection state to signify that the HEADERS have
// been sent until after they have been encoded and placed in the outbound buffer.
// Therefore, we let the `LifeCycleManager` will take care of transitioning the state
// as appropriate.
stream = connection.local().createStream(streamId, /*endOfStream*/ false);
} catch (Http2Exception cause) {
if (connection.remote().mayHaveCreatedStream(streamId)) {
promise.tryFailure(new IllegalStateException("Stream no longer exists: " + streamId, cause));
return promise;
}
throw cause;
}
} else {
switch (stream.state()) {
case RESERVED_LOCAL:
stream.open(endOfStream);
break;
case OPEN:
case HALF_CLOSED_REMOTE:
// Allowed sending headers in these states.
break;
default:
throw new IllegalStateException("Stream " + stream.id() + " in unexpected state " +
stream.state());
}
}
// Trailing headers must go through flow control if there are other frames queued in flow control
// for this stream.
Http2RemoteFlowController flowController = flowController();
if (!endOfStream || !flowController.hasFlowControlled(stream)) {
// The behavior here should mirror that in FlowControlledHeaders
promise = promise.unvoid();
boolean isInformational = validateHeadersSentState(stream, headers, connection.isServer(), endOfStream);
ChannelFuture future = sendHeaders(frameWriter, ctx, streamId, headers, hasPriority, streamDependency,
weight, exclusive, padding, endOfStream, promise);
// Writing headers may fail during the encode state if they violate HPACK limits.
Throwable failureCause = future.cause();
if (failureCause == null) {
// Synchronously set the headersSent flag to ensure that we do not subsequently write
// other headers containing pseudo-header fields.
//
// This just sets internal stream state which is used elsewhere in the codec and doesn't
// necessarily mean the write will complete successfully.
stream.headersSent(isInformational);
if (!future.isSuccess()) {
// Either the future is not done or failed in the meantime.
notifyLifecycleManagerOnError(future, ctx);
}
} else {
lifecycleManager.onError(ctx, true, failureCause);
}
if (endOfStream) {
// Must handle calling onError before calling closeStreamLocal, otherwise the error handler will
// incorrectly think the stream no longer exists and so may not send RST_STREAM or perform similar
// appropriate action.
lifecycleManager.closeStreamLocal(stream, future);
}
return future;
} else {
// Pass headers to the flow-controller so it can maintain their sequence relative to DATA frames.
flowController.addFlowControlled(stream,
new FlowControlledHeaders(stream, headers, hasPriority, streamDependency,
weight, exclusive, padding, true, promise));
return promise;
}
} catch (Throwable t) {
lifecycleManager.onError(ctx, true, t);
promise.tryFailure(t);
return promise;
}
}
@Override
public ChannelFuture writePriority(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
boolean exclusive, ChannelPromise promise) {
return frameWriter.writePriority(ctx, streamId, streamDependency, weight, exclusive, promise);
}
@Override
public ChannelFuture writeRstStream(ChannelHandlerContext ctx, int streamId, long errorCode,
ChannelPromise promise) {
// Delegate to the lifecycle manager for proper updating of connection state.
return lifecycleManager.resetStream(ctx, streamId, errorCode, promise);
}
@Override
public ChannelFuture writeSettings(ChannelHandlerContext ctx, Http2Settings settings,
ChannelPromise promise) {
outstandingLocalSettingsQueue.add(settings);
try {
Boolean pushEnabled = settings.pushEnabled();
if (pushEnabled != null && connection.isServer()) {
throw connectionError(PROTOCOL_ERROR, "Server sending SETTINGS frame with ENABLE_PUSH specified");
}
} catch (Throwable e) {
return promise.setFailure(e);
}
return frameWriter.writeSettings(ctx, settings, promise);
}
@Override
public ChannelFuture writeSettingsAck(ChannelHandlerContext ctx, ChannelPromise promise) {
if (outstandingRemoteSettingsQueue == null) {
return frameWriter.writeSettingsAck(ctx, promise);
}
Http2Settings settings = outstandingRemoteSettingsQueue.poll();
if (settings == null) {
return promise.setFailure(new Http2Exception(INTERNAL_ERROR, "attempted to write a SETTINGS ACK with no " +
" pending SETTINGS"));
}
SimpleChannelPromiseAggregator aggregator = new SimpleChannelPromiseAggregator(promise, ctx.channel(),
ctx.executor());
// Acknowledge receipt of the settings. We should do this before we process the settings to ensure our
// remote peer applies these settings before any subsequent frames that we may send which depend upon
// these new settings. See https://github.com/netty/netty/issues/6520.
frameWriter.writeSettingsAck(ctx, aggregator.newPromise());
// We create a "new promise" to make sure that status from both the write and the application are taken into
// account independently.
ChannelPromise applySettingsPromise = aggregator.newPromise();
try {
remoteSettings(settings);
applySettingsPromise.setSuccess();
} catch (Throwable e) {
applySettingsPromise.setFailure(e);
lifecycleManager.onError(ctx, true, e);
}
return aggregator.doneAllocatingPromises();
}
@Override
public ChannelFuture writePing(ChannelHandlerContext ctx, boolean ack, long data, ChannelPromise promise) {
return frameWriter.writePing(ctx, ack, data, promise);
}
@Override
public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding, ChannelPromise promise) {
try {
if (connection.goAwayReceived()) {
throw connectionError(PROTOCOL_ERROR, "Sending PUSH_PROMISE after GO_AWAY received.");
}
Http2Stream stream = requireStream(streamId);
// Reserve the promised stream.
connection.local().reservePushStream(promisedStreamId, stream);
promise = promise.unvoid();
ChannelFuture future = frameWriter.writePushPromise(ctx, streamId, promisedStreamId, headers, padding,
promise);
// Writing headers may fail during the encode state if they violate HPACK limits.
Throwable failureCause = future.cause();
if (failureCause == null) {
// This just sets internal stream state which is used elsewhere in the codec and doesn't
// necessarily mean the write will complete successfully.
stream.pushPromiseSent();
if (!future.isSuccess()) {
// Either the future is not done or failed in the meantime.
notifyLifecycleManagerOnError(future, ctx);
}
} else {
lifecycleManager.onError(ctx, true, failureCause);
}
return future;
} catch (Throwable t) {
lifecycleManager.onError(ctx, true, t);
promise.tryFailure(t);
return promise;
}
}
@Override
public ChannelFuture writeGoAway(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData,
ChannelPromise promise) {
return lifecycleManager.goAway(ctx, lastStreamId, errorCode, debugData, promise);
}
@Override
public ChannelFuture writeWindowUpdate(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement,
ChannelPromise promise) {
return promise.setFailure(new UnsupportedOperationException("Use the Http2[Inbound|Outbound]FlowController" +
" objects to control window sizes"));
}
@Override
public ChannelFuture writeFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
ByteBuf payload, ChannelPromise promise) {
return frameWriter.writeFrame(ctx, frameType, streamId, flags, payload, promise);
}
@Override
public void close() {
frameWriter.close();
}
@Override
public Http2Settings pollSentSettings() {
return outstandingLocalSettingsQueue.poll();
}
@Override
public Configuration configuration() {
return frameWriter.configuration();
}
private Http2Stream requireStream(int streamId) {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
final String message;
if (connection.streamMayHaveExisted(streamId)) {
message = "Stream no longer exists: " + streamId;
} else {
message = "Stream does not exist: " + streamId;
}
throw new IllegalArgumentException(message);
}
return stream;
}
@Override
public void consumeReceivedSettings(Http2Settings settings) {
if (outstandingRemoteSettingsQueue == null) {
outstandingRemoteSettingsQueue = new ArrayDeque<Http2Settings>(2);
}
outstandingRemoteSettingsQueue.add(settings);
}
/**
* Wrap a DATA frame so it can be written subject to flow-control. Note that this implementation assumes it
* only writes padding once for the entire payload as opposed to writing it once per-frame. This makes the
* {@link #size} calculation deterministic thereby greatly simplifying the implementation.
* <p>
* If frame-splitting is required to fit within max-frame-size and flow-control constraints we ensure that
* the passed promise is not completed until last frame write.
* </p>
*/
private final | DefaultHttp2ConnectionEncoder |
java | apache__camel | components/camel-aws/camel-aws2-sqs/src/test/java/org/apache/camel/component/aws2/sqs/integration/SqsProducerSendByteArrayLocalstackIT.java | {
"start": 1300,
"end": 2849
} | class ____ extends Aws2SQSBaseTest {
@EndpointInject("direct:start")
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void sendInOnly() throws Exception {
result.expectedMessageCount(1);
Exchange exchange = template.send("direct:start", ExchangePattern.InOnly, new Processor() {
@Override
public void process(Exchange exchange) {
byte[] headerValue = "HeaderTest".getBytes();
exchange.getIn().setHeader("value1", headerValue);
exchange.getIn().setBody("Test");
}
});
MockEndpoint.assertIsSatisfied(context);
Assertions.assertEquals(3, result.getExchanges().get(0).getMessage().getHeaders().size());
Assertions.assertEquals("HeaderTest",
Strings.fromByteArray((byte[]) result.getExchanges().get(0).getMessage().getHeaders().get("value1")));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").startupOrder(2).toF("aws2-sqs://%s?autoCreateQueue=true", sharedNameGenerator.getName())
.to("mock:result");
fromF("aws2-sqs://%s?deleteAfterRead=true&autoCreateQueue=true", sharedNameGenerator.getName()).startupOrder(1)
.log("${body}");
}
};
}
}
| SqsProducerSendByteArrayLocalstackIT |
java | greenrobot__EventBus | EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusBasicTest.java | {
"start": 8124,
"end": 8240
} | class ____ {
@Subscribe
public void onEvent(Object event) {
}
}
public | ObjectSubscriber |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/RetryRouteScopedUntilRecipientListIssueTest.java | {
"start": 1684,
"end": 8731
} | class ____ extends ContextTestSupport {
private final AtomicInteger invoked = new AtomicInteger();
@BeforeEach
public void resetInvoked() {
invoked.set(0);
}
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("myRetryBean", new MyRetryBean());
return jndi;
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.addEndpoint("fail", new DefaultEndpoint() {
public Producer createProducer() {
return new DefaultProducer(this) {
public void process(Exchange exchange) {
exchange.setException(new IllegalArgumentException("Damn"));
}
};
}
public Consumer createConsumer(Processor processor) {
return null;
}
@Override
protected String createEndpointUri() {
return "fail";
}
public boolean isSingleton() {
return true;
}
});
context.addEndpoint("not-fail", new DefaultEndpoint() {
public Producer createProducer() {
return new DefaultProducer(this) {
public void process(Exchange exchange) {
// noop
}
};
}
public Consumer createConsumer(Processor processor) {
return null;
}
@Override
protected String createEndpointUri() {
return "not-fail";
}
public boolean isSingleton() {
return true;
}
});
return context;
}
@Test
public void testRetryUntilRecipientListOkOnly() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("mock:foo").expectedMessageCount(1);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "direct:foo");
assertMockEndpointsSatisfied();
context.stop();
assertEquals(0, invoked.get());
}
@Test
public void testRetryUntilRecipientListOkNotFail() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("mock:foo").expectedMessageCount(1);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "direct:foo,not-fail");
assertMockEndpointsSatisfied();
context.stop();
assertEquals(0, invoked.get());
}
@Test
public void testRetryUntilRecipientListFailOnly() throws Exception {
NotifyBuilder event = event().whenDone(2).create();
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedMessageCount(0);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "fail");
assertMockEndpointsSatisfied();
// wait until its done before we stop and check that retry was invoked
boolean matches = event.matches(10, TimeUnit.SECONDS);
assertTrue(matches);
context.stop();
assertEquals(3, invoked.get());
}
@Test
public void testRetryUntilRecipientListFailAndOk() throws Exception {
NotifyBuilder event = event().whenDone(3).create();
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedMinimumMessageCount(0);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "fail,direct:foo");
assertMockEndpointsSatisfied();
// wait until its done before we stop and check that retry was invoked
boolean matches = event.matches(10, TimeUnit.SECONDS);
assertTrue(matches);
context.stop();
assertEquals(3, invoked.get());
}
@Test
public void testRetryUntilRecipientListOkAndFail() throws Exception {
NotifyBuilder event = event().whenDone(3).create();
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedMessageCount(1);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "direct:foo,fail");
assertMockEndpointsSatisfied();
// wait until its done before we stop and check that retry was invoked
boolean matches = event.matches(10, TimeUnit.SECONDS);
assertTrue(matches);
context.stop();
assertEquals(3, invoked.get());
}
@Test
public void testRetryUntilRecipientNotFail() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
getMockEndpoint("mock:foo").expectedMessageCount(0);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "not-fail");
assertMockEndpointsSatisfied();
context.stop();
assertEquals(0, invoked.get());
}
@Test
public void testRetryUntilRecipientFailAndNotFail() throws Exception {
NotifyBuilder event = event().whenDone(3).create();
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedMinimumMessageCount(0);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "fail,not-fail");
assertMockEndpointsSatisfied();
// wait until its done before we stop and check that retry was invoked
boolean matches = event.matches(10, TimeUnit.SECONDS);
assertTrue(matches);
context.stop();
assertEquals(3, invoked.get());
}
@Test
public void testRetryUntilRecipientNotFailAndFail() throws Exception {
NotifyBuilder event = event().whenDone(3).create();
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:foo").expectedMinimumMessageCount(0);
template.sendBodyAndHeader("seda:start", "Hello World", "recipientListHeader", "not-fail,fail");
assertMockEndpointsSatisfied();
// wait until its done before we stop and check that retry was invoked
boolean matches = event.matches(10, TimeUnit.SECONDS);
assertTrue(matches);
context.stop();
assertEquals(3, invoked.get());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:start").onException(Exception.class).redeliveryDelay(0).retryWhile(method("myRetryBean")).end()
.recipientList(header("recipientListHeader"))
.to("mock:result");
from("direct:foo").to("log:foo").to("mock:foo");
}
};
}
public | RetryRouteScopedUntilRecipientListIssueTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLReplaceStatement.java | {
"start": 862,
"end": 5165
} | class ____ extends SQLStatementImpl {
protected boolean lowPriority;
protected boolean delayed;
protected SQLExprTableSource tableSource;
protected final List<SQLExpr> columns = new ArrayList<SQLExpr>();
protected List<SQLInsertStatement.ValuesClause> valuesList = new ArrayList<SQLInsertStatement.ValuesClause>();
protected SQLQueryExpr query;
protected List<SQLCommentHint> hints;
protected List<SQLAssignItem> partitions;
public SQLName getTableName() {
if (tableSource == null) {
return null;
}
return (SQLName) tableSource.getExpr();
}
public void setTableName(SQLName tableName) {
this.setTableSource(new SQLExprTableSource(tableName));
}
public SQLExprTableSource getTableSource() {
return tableSource;
}
public void setTableSource(SQLExprTableSource tableSource) {
if (tableSource != null) {
tableSource.setParent(this);
}
this.tableSource = tableSource;
}
public List<SQLExpr> getColumns() {
return columns;
}
public void addColumn(SQLExpr column) {
if (column != null) {
column.setParent(this);
}
this.columns.add(column);
}
public boolean isLowPriority() {
return lowPriority;
}
public void setLowPriority(boolean lowPriority) {
this.lowPriority = lowPriority;
}
public boolean isDelayed() {
return delayed;
}
public void setDelayed(boolean delayed) {
this.delayed = delayed;
}
public SQLQueryExpr getQuery() {
return query;
}
public void setQuery(SQLQueryExpr query) {
if (query != null) {
query.setParent(this);
}
this.query = query;
}
public List<SQLInsertStatement.ValuesClause> getValuesList() {
return valuesList;
}
@Override
public SQLStatement clone() {
SQLReplaceStatement x = new SQLReplaceStatement();
x.setDbType(this.dbType);
if (headHints != null) {
for (SQLCommentHint h : headHints) {
SQLCommentHint clone = h.clone();
clone.setParent(x);
x.headHints.add(clone);
}
}
if (hints != null && !hints.isEmpty()) {
for (SQLCommentHint h : hints) {
SQLCommentHint clone = h.clone();
clone.setParent(x);
x.getHints().add(clone);
}
}
x.lowPriority = this.lowPriority;
x.delayed = this.delayed;
if (this.tableSource != null) {
x.tableSource = this.tableSource.clone();
}
for (SQLInsertStatement.ValuesClause clause : valuesList) {
x.getValuesList().add(clause.clone());
}
for (SQLExpr column : columns) {
x.addColumn(column.clone());
}
if (query != null) {
x.query = this.query.clone();
}
if (partitions != null) {
for (SQLAssignItem partition : partitions) {
x.addPartition(partition.clone());
}
}
return x;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, tableSource);
acceptChild(visitor, columns);
acceptChild(visitor, valuesList);
acceptChild(visitor, query);
}
visitor.endVisit(this);
}
public int getHintsSize() {
if (hints == null) {
return 0;
}
return hints.size();
}
public List<SQLCommentHint> getHints() {
if (hints == null) {
hints = new ArrayList<SQLCommentHint>(2);
}
return hints;
}
public void setHints(List<SQLCommentHint> hints) {
this.hints = hints;
}
public void addPartition(SQLAssignItem partition) {
if (partition != null) {
partition.setParent(this);
}
if (partitions == null) {
partitions = new ArrayList<SQLAssignItem>();
}
this.partitions.add(partition);
}
public List<SQLAssignItem> getPartitions() {
return partitions;
}
}
| SQLReplaceStatement |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/persistent/CompletionPersistentTaskAction.java | {
"start": 2183,
"end": 4719
} | class ____ extends MasterNodeRequest<Request> {
private final String taskId;
private final Exception exception;
private final long allocationId;
private final String localAbortReason;
public Request(StreamInput in) throws IOException {
super(in);
taskId = in.readString();
allocationId = in.readLong();
exception = in.readException();
localAbortReason = in.readOptionalString();
}
public Request(TimeValue masterNodeTimeout, String taskId, long allocationId, Exception exception, String localAbortReason) {
super(masterNodeTimeout);
this.taskId = taskId;
this.exception = exception;
this.allocationId = allocationId;
this.localAbortReason = localAbortReason;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(taskId);
out.writeLong(allocationId);
out.writeException(exception);
out.writeOptionalString(localAbortReason);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (taskId == null) {
validationException = addValidationError("task id is missing", validationException);
}
if (allocationId < 0) {
validationException = addValidationError("allocation id is negative or missing", validationException);
}
if (exception != null && localAbortReason != null) {
validationException = addValidationError("task cannot be both locally aborted and failed", validationException);
}
return validationException;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Objects.equals(taskId, request.taskId)
&& allocationId == request.allocationId
&& Objects.equals(exception, request.exception)
&& Objects.equals(localAbortReason, request.localAbortReason);
}
@Override
public int hashCode() {
return Objects.hash(taskId, allocationId, exception, localAbortReason);
}
}
public static | Request |
java | quarkusio__quarkus | extensions/security-webauthn/runtime/src/main/java/io/quarkus/security/webauthn/WebAuthnRunTimeConfig.java | {
"start": 4904,
"end": 5011
} | enum ____ used to specify the desired behaviour for resident keys with the authenticator.
*/
public | is |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/routing/allocation/allocator/BalancedShardsAllocatorTests.java | {
"start": 64714,
"end": 65495
} | class ____ extends WeightFunction {
NodeNameDrivenWeightFunction() {
super(1.0f, 1.0f, 1.0f, 1.0f);
}
@Override
public float calculateNodeWeightWithIndex(
BalancedShardsAllocator.Balancer balancer,
BalancedShardsAllocator.ModelNode node,
BalancedShardsAllocator.ProjectIndex index
) {
final var nodeId = node.getNodeId();
if (nodeId.endsWith("-high")) {
return 10.0f;
} else if (nodeId.endsWith("-low")) {
return 0.0f;
} else {
return 5.0f;
}
}
}
private static | NodeNameDrivenWeightFunction |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/LeafQueueTemplateInfo.java | {
"start": 2582,
"end": 2931
} | class ____ {
private String name;
private String value;
public ConfItem() {
// JAXB needs this
}
public ConfItem(String name, String value){
this.name = name;
this.value = value;
}
public String getKey() {
return name;
}
public String getValue() {
return value;
}
}
}
| ConfItem |
java | apache__camel | components/camel-tahu/src/main/java/org/apache/camel/component/tahu/handlers/TahuEdgeClient.java | {
"start": 1803,
"end": 5368
} | class ____ extends EdgeClient {
private static final Logger LOG = LoggerFactory.getLogger(TahuEdgeClient.class);
private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(5L);
private final EdgeNodeDescriptor edgeNodeDescriptor;
private final TahuEdgeMetricHandler tahuEdgeNodeMetricHandler;
private final TahuEdgeClientCallback tahuEdgeNodeClientCallback;
private final ExecutorService clientExecutorService;
private volatile Future<?> clientSubmittedFuture = null;
private volatile boolean suspended = false;
private final Marker loggingMarker;
private TahuEdgeClient(TahuEdgeMetricHandler tahuEdgeNodeMetricHandler, EdgeNodeDescriptor edgeNodeDescriptor,
List<String> deviceIds, String primaryHostId, boolean useAliases, Long rebirthDebounceDelay,
List<MqttServerDefinition> mqttServerDefinitions, TahuEdgeClientCallback tahuEdgeNodeClientCallback,
RandomStartupDelay randomStartupDelay, ExecutorService clientExecutorService) {
super(tahuEdgeNodeMetricHandler, edgeNodeDescriptor, deviceIds, primaryHostId, useAliases, rebirthDebounceDelay,
mqttServerDefinitions, tahuEdgeNodeClientCallback, randomStartupDelay);
this.edgeNodeDescriptor = edgeNodeDescriptor;
loggingMarker = MarkerFactory.getMarker(edgeNodeDescriptor.getDescriptorString());
this.tahuEdgeNodeMetricHandler = tahuEdgeNodeMetricHandler;
this.tahuEdgeNodeClientCallback = tahuEdgeNodeClientCallback;
this.clientExecutorService = clientExecutorService;
}
public Future<?> startup() {
if (clientSubmittedFuture == null) {
clientSubmittedFuture = clientExecutorService.submit(this);
suspended = false;
}
return clientSubmittedFuture;
}
public void suspend() {
if (clientSubmittedFuture != null && !suspended) {
this.disconnect(false);
suspended = true;
}
}
public void resume() {
if (clientSubmittedFuture != null && suspended) {
this.handleRebirthRequest(false);
suspended = false;
}
}
@Override
public void shutdown() {
Future<?> clientSubmittedFuture = this.clientSubmittedFuture;
if (clientSubmittedFuture != null) {
suspended = false;
super.shutdown();
try {
clientSubmittedFuture.get(SHUTDOWN_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException te) {
clientSubmittedFuture.cancel(true);
} catch (CancellationException | ExecutionException | InterruptedException e) {
LOG.warn(loggingMarker, "Caught exception waiting for client shutdown", e);
}
this.clientSubmittedFuture = null;
}
}
public SparkplugBPayloadMap addDeviceMetricDataPayloadMap(
SparkplugDescriptor metricDescriptor, SparkplugBPayloadMap metricDataTypePayloadMap) {
return tahuEdgeNodeMetricHandler.addDeviceMetricDataPayloadMap(metricDescriptor, metricDataTypePayloadMap);
}
public void publishData(SparkplugDescriptor sd, SparkplugBPayload payload) {
tahuEdgeNodeMetricHandler.updateCachedMetrics(sd, payload);
if (sd.isDeviceDescriptor()) {
publishDeviceData(((DeviceDescriptor) sd).getDeviceId(), payload);
} else {
publishNodeData(payload);
}
}
public static final | TahuEdgeClient |
java | google__dagger | javatests/dagger/functional/subcomponent/repeat/SubcomponentWithRepeatedModule.java | {
"start": 940,
"end": 1070
} | interface ____ {
Builder repeatedModule(RepeatedModule repeatedModule);
SubcomponentWithRepeatedModule build();
}
}
| Builder |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/lucene/LuceneSourceOperatorTests.java | {
"start": 3160,
"end": 3761
} | class ____ extends SourceOperatorTestCase {
private static final MappedFieldType S_FIELD = new NumberFieldMapper.NumberFieldType("s", NumberFieldMapper.NumberType.LONG);
@ParametersFactory(argumentFormatting = "%s %s")
public static Iterable<Object[]> parameters() {
List<Object[]> parameters = new ArrayList<>();
for (TestCase c : TestCase.values()) {
for (boolean scoring : new boolean[] { false, true }) {
parameters.add(new Object[] { c, scoring });
}
}
return parameters;
}
public | LuceneSourceOperatorTests |
java | elastic__elasticsearch | qa/smoke-test-http/src/internalClusterTest/java/org/elasticsearch/http/BlockedSearcherRestCancellationTestCase.java | {
"start": 5714,
"end": 6252
} | class ____ extends Plugin implements EnginePlugin {
@Override
public Optional<EngineFactory> getEngineFactory(IndexSettings indexSettings) {
if (BLOCK_SEARCHER_SETTING.get(indexSettings.getSettings())) {
return Optional.of(SearcherBlockingEngine::new);
}
return Optional.empty();
}
@Override
public List<Setting<?>> getSettings() {
return singletonList(BLOCK_SEARCHER_SETTING);
}
}
private static | SearcherBlockingPlugin |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/utils/OperationMatchers.java | {
"start": 6574,
"end": 7817
} | class ____ extends TypeSafeDiagnosingMatcher<Operation> {
private final Matcher<CreateTableOperation>[] nestedMatchers;
public CreateTableOperationMatcher(Matcher<CreateTableOperation>[] nestedMatchers) {
this.nestedMatchers = nestedMatchers;
}
@Override
protected boolean matchesSafely(Operation item, Description mismatchDescription) {
if (!(item instanceof CreateTableOperation)) {
return false;
}
for (Matcher<CreateTableOperation> nestedMatcher : nestedMatchers) {
if (!nestedMatcher.matches(item)) {
nestedMatcher.describeMismatch(item, mismatchDescription);
return false;
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("\n");
Arrays.stream(nestedMatchers)
.forEach(
matcher -> {
matcher.describeTo(description);
description.appendText("\n");
});
}
}
}
| CreateTableOperationMatcher |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/AopProxyFactory.java | {
"start": 1614,
"end": 1982
} | interface ____ {
/**
* Create an {@link AopProxy} for the given AOP configuration.
* @param config the AOP configuration in the form of an
* AdvisedSupport object
* @return the corresponding AOP proxy
* @throws AopConfigException if the configuration is invalid
*/
AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException;
}
| AopProxyFactory |
java | spring-projects__spring-boot | module/spring-boot-transaction/src/main/java/org/springframework/boot/transaction/autoconfigure/TransactionManagerCustomizer.java | {
"start": 995,
"end": 1231
} | interface ____<T extends TransactionManager> {
/**
* Customize the given transaction manager.
* @param transactionManager the transaction manager to customize
*/
void customize(T transactionManager);
}
| TransactionManagerCustomizer |
java | apache__camel | components/camel-rest/src/generated/java/org/apache/camel/component/rest/RestApiComponentConfigurer.java | {
"start": 731,
"end": 2712
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
RestApiComponent target = (RestApiComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "consumercomponentname":
case "consumerComponentName": target.setConsumerComponentName(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "consumercomponentname":
case "consumerComponentName": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
RestApiComponent target = (RestApiComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "consumercomponentname":
case "consumerComponentName": return target.getConsumerComponentName();
default: return null;
}
}
}
| RestApiComponentConfigurer |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java | {
"start": 449,
"end": 1415
} | interface ____<T> {
/**
* Perform whatever actions are necessary using the provided JDBC {@link Connection}.
*
* @param connection The JDBC {@link Connection}.
*
* @return The created LOB.
*
* @throws SQLException Indicates trouble accessing the JDBC driver to create the LOB
*/
T executeOnConnection(Connection connection) throws SQLException;
default T from(Connection connection) throws SQLException {
return executeOnConnection( connection );
}
}
/**
* Execute the given callback, making sure it has access to a viable JDBC {@link Connection}.
*
* @param callback The callback to execute .
* @param <T> The Java type of the type of LOB being created. One of {@link java.sql.Blob},
* {@link java.sql.Clob}, {@link java.sql.NClob}
*
* @return The LOB created by the callback.
*/
<T> T execute(Callback<T> callback);
default <T> T fromContext(Callback<T> callback) {
return execute( callback );
}
}
| Callback |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AbstractMetadataGenerator.java | {
"start": 1217,
"end": 1316
} | class ____ all metadata generator implementations.
*
* @author Chris Cranford
*/
public abstract | for |
java | quarkusio__quarkus | independent-projects/tools/utilities/src/main/java/io/quarkus/utilities/JavaBinFinder.java | {
"start": 189,
"end": 848
} | class ____ {
/**
* {@return the path of the {@code java} command (not {@code null})}
*
* @deprecated Use {@link ProcessUtil#pathOfJava()} instead.
*/
@Deprecated(forRemoval = true, since = "3.25")
public static String findBin() {
return ProcessUtil.pathOfJava().toString();
}
/**
* {@return the name of the {@code java} executable for this platform (not {@code null})}
*
* @deprecated Use {@link ProcessUtil#nameOfJava()} instead.
*/
@Deprecated(forRemoval = true, since = "3.25")
public static String simpleBinaryName() {
return ProcessUtil.nameOfJava();
}
}
| JavaBinFinder |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/ResolvableType.java | {
"start": 38753,
"end": 39737
} | interface ____ base class) with a given implementation class.
* <p>For example: {@code ResolvableType.forClass(List.class, MyArrayList.class)}.
* @param baseType the base type (must not be {@code null})
* @param implementationClass the implementation class
* @return a {@code ResolvableType} for the specified base type backed by the
* given implementation class
* @see #forClass(Class)
* @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClass(Class<?> baseType, Class<?> implementationClass) {
Assert.notNull(baseType, "Base type must not be null");
ResolvableType asType = forType(implementationClass).as(baseType);
return (asType == NONE ? forType(baseType) : asType);
}
/**
* Return a {@code ResolvableType} for the specified {@link Class} with pre-declared generics.
* @param clazz the class (or interface) to introspect
* @param generics the generics of the class
* @return a {@code ResolvableType} for the specific | or |
java | apache__flink | flink-table/flink-sql-parser/src/test/java/org/apache/flink/sql/parser/TestRelDataTypeFactory.java | {
"start": 1330,
"end": 1950
} | class ____ extends SqlTypeFactoryImpl implements ExtendedRelTypeFactory {
TestRelDataTypeFactory(RelDataTypeSystem typeSystem) {
super(typeSystem);
}
@Override
public RelDataType createRawType(String className, String serializerString) {
return canonize(new DummyRawType(className, serializerString));
}
@Override
public RelDataType createStructuredType(
String className, List<RelDataType> typeList, List<String> fieldNameList) {
return canonize(new DummyStructuredType(className, typeList, fieldNameList));
}
private static | TestRelDataTypeFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 21671,
"end": 22070
} | class ____ {
@SomeAnnotation
@some.pkg.SomeAnnotation
Void foo() {
return null;
}
}
""")
.doTest();
}
@Test
public void qualifyType_typeVariable() {
AddAnnotation.testHelper(getClass())
.addInputLines(
"in/AddAnnotation.java",
"""
| AddAnnotation |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/UserTypeCasesMapKey.java | {
"start": 958,
"end": 3412
} | class ____ extends AbstractUserTypeCases {
public static final UserTypeCasesMapKey MAP_KEY_USER_TYPE_CASES = new UserTypeCasesMapKey();
public static void applyJavaTypeAnnotationStatic(
MutableMemberDetails memberDetails,
Class<? extends BasicJavaType<?>> descriptor,
XmlDocumentContext xmlDocumentContext) {
final MapKeyJavaTypeAnnotation javaTypeAnnotation = (MapKeyJavaTypeAnnotation) memberDetails.applyAnnotationUsage(
HibernateAnnotations.MAP_KEY_JAVA_TYPE,
xmlDocumentContext.getModelBuildingContext()
);
javaTypeAnnotation.value( descriptor );
}
@Override
protected void applyJavaTypeAnnotation(
MutableMemberDetails memberDetails,
Class<? extends BasicJavaType<?>> descriptor,
XmlDocumentContext xmlDocumentContext) {
applyJavaTypeAnnotationStatic( memberDetails, descriptor, xmlDocumentContext );
}
@SuppressWarnings("deprecation")
@Override
protected void applyTemporalPrecision(
MutableMemberDetails memberDetails,
TemporalType temporalType,
XmlDocumentContext xmlDocumentContext) {
final MapKeyTemporal directUsage = memberDetails.getDirectAnnotationUsage( MapKeyTemporal.class );
if ( directUsage != null ) {
// make sure they match
if ( directUsage.value() != temporalType ) {
throw new org.hibernate.MappingException( String.format(
Locale.ROOT,
"Mismatch in expected TemporalType on %s; found %s and %s",
memberDetails,
directUsage.value(),
temporalType
) );
}
return;
}
final MapKeyTemporalJpaAnnotation temporalAnnotation = (MapKeyTemporalJpaAnnotation) memberDetails.applyAnnotationUsage(
JpaAnnotations.MAP_KEY_TEMPORAL,
xmlDocumentContext.getModelBuildingContext()
);
temporalAnnotation.value( temporalType );
}
@Override
public void handleGeneral(
JaxbUserTypeImpl jaxbType,
MutableMemberDetails memberDetails,
XmlDocumentContext xmlDocumentContext) {
final ClassDetails userTypeImpl = XmlAnnotationHelper.resolveJavaType( jaxbType.getValue(), xmlDocumentContext );
assert userTypeImpl.isImplementor( UserType.class );
final MapKeyTypeAnnotation typeAnn = (MapKeyTypeAnnotation) memberDetails.applyAnnotationUsage(
HibernateAnnotations.MAP_KEY_TYPE,
xmlDocumentContext.getModelBuildingContext()
);
typeAnn.value( userTypeImpl.toJavaClass() );
typeAnn.parameters( XmlAnnotationHelper.collectParameters( jaxbType.getParameters(), xmlDocumentContext ) );
}
}
| UserTypeCasesMapKey |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/SizeSourceImpl.java | {
"start": 304,
"end": 791
} | class ____ implements SizeSource {
private final Integer length;
private final Integer scale;
private final Integer precision;
public SizeSourceImpl(Integer length, Integer scale, Integer precision) {
this.length = length;
this.scale = scale;
this.precision = precision;
}
@Override
public Integer getLength() {
return length;
}
@Override
public Integer getPrecision() {
return precision;
}
@Override
public Integer getScale() {
return scale;
}
}
| SizeSourceImpl |
java | quarkusio__quarkus | extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/QuarkusSimpleConnectionCache.java | {
"start": 159,
"end": 1289
} | class ____ implements ConnectionCache {
volatile ThreadLocal<Acquirable> connectionCache = new ThreadLocal<>();
@Override
public Acquirable get() {
Thread thread = Thread.currentThread();
if (thread instanceof JBossThread) {
//we only want to cache on threads that we control the lifecycle
//which are the vert.x and potentially jboss threads
//JBossThread still works with FastThreadLocal, it is just slower, and for most apps
//this will not be used anyway, as we use VertThread pretty much everywhere if
//Vert.x is present
Acquirable acquirable = connectionCache.get();
return acquirable != null && acquirable.acquire() ? acquirable : null;
}
return null;
}
@Override
public void put(Acquirable acquirable) {
Thread thread = Thread.currentThread();
if (thread instanceof JBossThread) {
connectionCache.set(acquirable);
}
}
@Override
public void reset() {
connectionCache = new ThreadLocal<>();
}
}
| QuarkusSimpleConnectionCache |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/util/TagUtils.java | {
"start": 1586,
"end": 3497
} | class ____ {
/** Constant identifying the page scope. */
public static final String SCOPE_PAGE = "page";
/** Constant identifying the request scope. */
public static final String SCOPE_REQUEST = "request";
/** Constant identifying the session scope. */
public static final String SCOPE_SESSION = "session";
/** Constant identifying the application scope. */
public static final String SCOPE_APPLICATION = "application";
/**
* Determines the scope for a given input {@code String}.
* <p>If the {@code String} does not match 'request', 'session',
* 'page' or 'application', the method will return {@link PageContext#PAGE_SCOPE}.
* @param scope the {@code String} to inspect
* @return the scope found, or {@link PageContext#PAGE_SCOPE} if no scope matched
* @throws IllegalArgumentException if the supplied {@code scope} is {@code null}
*/
public static int getScope(String scope) {
Assert.notNull(scope, "Scope to search for cannot be null");
return switch (scope) {
case SCOPE_REQUEST -> PageContext.REQUEST_SCOPE;
case SCOPE_SESSION -> PageContext.SESSION_SCOPE;
case SCOPE_APPLICATION -> PageContext.APPLICATION_SCOPE;
default -> PageContext.PAGE_SCOPE;
};
}
/**
* Determine whether the supplied {@link Tag} has any ancestor tag
* of the supplied type.
* @param tag the tag whose ancestors are to be checked
* @param ancestorTagClass the ancestor {@link Class} being searched for
* @return {@code true} if the supplied {@link Tag} has any ancestor tag
* of the supplied type
* @throws IllegalArgumentException if either of the supplied arguments is {@code null};
* or if the supplied {@code ancestorTagClass} is not type-assignable to
* the {@link Tag} class
*/
public static boolean hasAncestorOfType(Tag tag, Class<?> ancestorTagClass) {
Assert.notNull(tag, "Tag cannot be null");
Assert.notNull(ancestorTagClass, "Ancestor tag | TagUtils |
java | quarkusio__quarkus | extensions/funqy/funqy-server-common/runtime/src/main/java/io/quarkus/funqy/runtime/FunqyServerRequest.java | {
"start": 42,
"end": 149
} | interface ____ {
RequestContext context();
Object extractInput(Class inputClass);
}
| FunqyServerRequest |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/ExceptionsTest.java | {
"start": 1264,
"end": 22390
} | class ____ {
//used for two addThrowableXxx tests lower in the class. each test receiving a separate instance of ExceptionsTests,
//there is no need to reset it.
volatile @Nullable Throwable addThrowable;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings("DataFlowIssue")
static final AtomicReferenceFieldUpdater<ExceptionsTest, @Nullable Throwable> ADD_THROWABLE =
AtomicReferenceFieldUpdater.newUpdater(ExceptionsTest.class, Throwable.class, "addThrowable");
static VirtualMachineError JVM_FATAL_VIRTUAL_MACHINE_ERROR = new VirtualMachineError("expected to be logged") {
@Override
public String toString() {
return "custom VirtualMachineError: expected to be logged";
}
};
static final ThreadDeath JVM_FATAL_THREAD_DEATH = new ThreadDeath() {
@Override
public String getMessage() {
return "expected to be logged";
}
@Override
public String toString() {
return "custom ThreadDeath: expected to be logged";
}
};
static final LinkageError JVM_FATAL_LINKAGE_ERROR = new LinkageError("expected to be logged") {
@Override
public String toString() {
return "custom LinkageError: expected to be logged";
}
};
@Test
public void bubble() throws Exception {
Throwable t = new Exception("test");
Throwable w = Exceptions.bubble(Exceptions.propagate(t));
assertThat(Exceptions.unwrap(w)).isSameAs(t);
}
@Test
public void nullBubble() throws Exception {
Throwable w = Exceptions.bubble(null);
assertThat(Exceptions.unwrap(w)).isSameAs(w);
}
@Test
public void duplicateOnSubscribeReferencesSpec() {
IllegalStateException error = duplicateOnSubscribeException();
assertThat(error).hasMessageContaining("Rule 2.12");
}
@Test
public void duplicateOnSubscribeCreatesNewInstances() {
IllegalStateException error1 = duplicateOnSubscribeException();
IllegalStateException error2 = duplicateOnSubscribeException();
assertThat(error1).isNotSameAs(error2);
}
@Test
public void errorCallbackNotImplementedRejectsNull() {
//noinspection ThrowableNotThrown,ConstantConditions
assertThatNullPointerException().isThrownBy(() -> Exceptions.errorCallbackNotImplemented(null));
}
@Test
public void isErrorCallbackNotImplemented() {
UnsupportedOperationException vanillaUnsupported = new UnsupportedOperationException("not error callback");
UnsupportedOperationException t = errorCallbackNotImplemented(new IllegalStateException("in error callback"));
assertThat(Exceptions.isErrorCallbackNotImplemented(vanillaUnsupported))
.as("not error callback")
.isFalse();
assertThat(Exceptions.isErrorCallbackNotImplemented(t))
.as("error callback")
.isTrue();
}
@Test
public void allOverflowIsIllegalState() {
IllegalStateException overflow1 = Exceptions.failWithOverflow();
IllegalStateException overflow2 = Exceptions.failWithOverflow("foo");
assertThat(Exceptions.isOverflow(overflow1)).isTrue();
assertThat(Exceptions.isOverflow(overflow2)).isTrue();
}
@Test
public void allIllegalStateIsntOverflow() {
IllegalStateException ise = new IllegalStateException("foo");
assertThat(Exceptions.isOverflow(ise)).isFalse();
}
@Test
public void failWithRejectedIsSingleton() {
assertThat(Exceptions.failWithRejected())
.isSameAs(Exceptions.failWithRejected())
.isNotSameAs(Exceptions.failWithRejectedNotTimeCapable());
}
@Test
public void failWithRejectedNotTimeCapableIsSingleton() {
assertThat(Exceptions.failWithRejectedNotTimeCapable())
.isSameAs(Exceptions.failWithRejectedNotTimeCapable())
.isNotSameAs(Exceptions.failWithRejected());
}
@Test
public void isBubbling() {
Throwable notBubbling = new ReactiveException("foo");
Throwable bubbling = new BubblingException("foo");
assertThat(Exceptions.isBubbling(notBubbling)).as("not bubbling").isFalse();
assertThat(Exceptions.isBubbling(bubbling)).as("bubbling").isTrue();
}
@Test
public void isCancelAndCancelIsBubbling() {
Throwable notCancel = new BubblingException("foo");
Throwable cancel = new CancelException();
assertThat(Exceptions.isCancel(notCancel)).as("not cancel").isFalse();
assertThat(Exceptions.isCancel(cancel)).as("cancel").isTrue();
assertThat(Exceptions.isBubbling(cancel)).as("cancel are bubbling").isTrue();
}
@Test
public void nullOrNegativeRequestReferencesSpec() {
assertThat(Exceptions.nullOrNegativeRequestException(-3))
.hasMessage("Spec. Rule 3.9 - Cannot request a non strictly positive number: -3");
}
@Test
public void propagateDoesntWrapRuntimeException() {
Throwable t = new RuntimeException("expected");
assertThat(Exceptions.propagate(t)).isSameAs(t);
}
//TODO test terminate
@Test
void bubblingExceptionIsFatalButNotJvmFatal() {
Throwable exception = new BubblingException("expected");
assertThat(Exceptions.isFatal(exception))
.as("isFatal(bubbling)")
.isTrue();
assertThat(Exceptions.isJvmFatal(exception))
.as("isJvmFatal(bubbling)")
.isFalse();
}
@Test
void errorCallbackNotImplementedIsFatalButNotJvmFatal() {
Throwable exception = new ErrorCallbackNotImplemented(new IllegalStateException("expected cause"));
assertThat(Exceptions.isFatal(exception))
.as("isFatal(ErrorCallbackNotImplemented)")
.isTrue();
assertThat(Exceptions.isJvmFatal(exception))
.as("isJvmFatal(ErrorCallbackNotImplemented)")
.isFalse();
}
@Test
void virtualMachineErrorIsFatalAndJvmFatal() {
assertThat(Exceptions.isFatal(JVM_FATAL_VIRTUAL_MACHINE_ERROR))
.as("isFatal(VirtualMachineError)")
.isTrue();
assertThat(Exceptions.isJvmFatal(JVM_FATAL_VIRTUAL_MACHINE_ERROR))
.as("isJvmFatal(VirtualMachineError)")
.isTrue();
}
@Test
void linkageErrorIsFatalAndJvmFatal() {
assertThat(Exceptions.isFatal(JVM_FATAL_LINKAGE_ERROR))
.as("isFatal(LinkageError)")
.isTrue();
assertThat(Exceptions.isJvmFatal(JVM_FATAL_LINKAGE_ERROR))
.as("isJvmFatal(LinkageError)")
.isTrue();
}
@Test
void threadDeathIsFatalAndJvmFatal() {
assertThat(Exceptions.isFatal(JVM_FATAL_THREAD_DEATH))
.as("isFatal(ThreadDeath)")
.isTrue();
assertThat(Exceptions.isJvmFatal(JVM_FATAL_THREAD_DEATH))
.as("isJvmFatal(ThreadDeath)")
.isTrue();
}
@Test
@TestLoggerExtension.Redirect
void throwIfFatalThrowsAndLogsBubbling(TestLogger testLogger) {
BubblingException expected = new BubblingException("expected to be logged");
assertThatExceptionOfType(BubblingException.class)
.isThrownBy(() -> Exceptions.throwIfFatal(expected))
.isSameAs(expected);
assertThat(testLogger.getErrContent())
.startsWith("[ WARN] throwIfFatal detected a fatal exception, which is thrown and logged below: - reactor.core.Exceptions$BubblingException: expected to be logged");
}
@Test
@TestLoggerExtension.Redirect
void throwIfFatalThrowsAndLogsErrorCallbackNotImplemented(TestLogger testLogger) {
ErrorCallbackNotImplemented expected = new ErrorCallbackNotImplemented(new IllegalStateException("expected to be logged"));
assertThatExceptionOfType(ErrorCallbackNotImplemented.class)
.isThrownBy(() -> Exceptions.throwIfFatal(expected))
.isSameAs(expected)
.withCause(expected.getCause());
assertThat(testLogger.getErrContent())
.startsWith("[ WARN] throwIfFatal detected a fatal exception, which is thrown and logged below: - reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalStateException: expected to be logged");
}
@Test
@TestLoggerExtension.Redirect
void throwIfFatalWithJvmFatalErrorsDoesThrowAndLog(TestLogger testLogger) {
SoftAssertions.assertSoftly(softly -> {
softly.assertThatExceptionOfType(VirtualMachineError.class)
.as("VirtualMachineError")
.isThrownBy(() -> Exceptions.throwIfFatal(JVM_FATAL_VIRTUAL_MACHINE_ERROR))
.isSameAs(JVM_FATAL_VIRTUAL_MACHINE_ERROR);
softly.assertThatExceptionOfType(ThreadDeath.class)
.as("ThreadDeath")
.isThrownBy(() -> Exceptions.throwIfFatal(JVM_FATAL_THREAD_DEATH))
.isSameAs(JVM_FATAL_THREAD_DEATH);
softly.assertThatExceptionOfType(LinkageError.class)
.as("LinkageError")
.isThrownBy(() -> Exceptions.throwIfFatal(JVM_FATAL_LINKAGE_ERROR))
.isSameAs(JVM_FATAL_LINKAGE_ERROR);
softly.assertThat(testLogger.getErrContent())
.startsWith("[ WARN] throwIfFatal detected a jvm fatal exception, which is thrown and logged below: - custom VirtualMachineError: expected to be logged")
.contains("[ WARN] throwIfFatal detected a jvm fatal exception, which is thrown and logged below: - custom ThreadDeath: expected to be logged")
.contains("[ WARN] throwIfFatal detected a jvm fatal exception, which is thrown and logged below: - custom LinkageError: expected to be logged");
});
}
@Test
@TestLoggerExtension.Redirect
void throwIfJvmFatalDoesThrowAndLog(TestLogger testLogger) {
assertThatExceptionOfType(VirtualMachineError.class)
.as("VirtualMachineError")
.isThrownBy(() -> Exceptions.throwIfJvmFatal(JVM_FATAL_VIRTUAL_MACHINE_ERROR))
.isSameAs(JVM_FATAL_VIRTUAL_MACHINE_ERROR);
assertThatExceptionOfType(ThreadDeath.class)
.as("ThreadDeath")
.isThrownBy(() -> Exceptions.throwIfJvmFatal(JVM_FATAL_THREAD_DEATH))
.isSameAs(JVM_FATAL_THREAD_DEATH);
assertThatExceptionOfType(LinkageError.class)
.as("LinkageError")
.isThrownBy(() -> Exceptions.throwIfJvmFatal(JVM_FATAL_LINKAGE_ERROR))
.isSameAs(JVM_FATAL_LINKAGE_ERROR);
assertThat(testLogger.getErrContent())
.startsWith("[ WARN] throwIfJvmFatal detected a jvm fatal exception, which is thrown and logged below: - custom VirtualMachineError: expected to be logged")
.contains("[ WARN] throwIfJvmFatal detected a jvm fatal exception, which is thrown and logged below: - custom ThreadDeath: expected to be logged")
.contains("[ WARN] throwIfJvmFatal detected a jvm fatal exception, which is thrown and logged below: - custom LinkageError: expected to be logged");
};
@Test
@TestLoggerExtension.Redirect
void throwIfJvmFatalDoesntThrowNorLogsOnSimplyFatalExceptions(TestLogger testLogger) {
SoftAssertions.assertSoftly(softly -> {
softly.assertThatCode(() -> Exceptions.throwIfJvmFatal(new BubblingException("not thrown")))
.doesNotThrowAnyException();
softly.assertThatCode(() -> Exceptions.throwIfJvmFatal(new ErrorCallbackNotImplemented(new RuntimeException("not thrown"))))
.doesNotThrowAnyException();
});
assertThat(testLogger.getErrContent()).isEmpty();
}
@Test
public void multipleWithNullVararg() {
//noinspection ConstantConditions
assertThat(Exceptions.multiple((Throwable[]) null))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasNoSuppressedExceptions();
}
@Test
public void multipleWithOneVararg() {
IOException e1 = new IOException("boom");
assertThat(Exceptions.multiple(e1))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasSuppressedException(e1);
}
@Test
public void multipleWithTwoVararg() {
IOException e1 = new IOException("boom");
IllegalArgumentException e2 = new IllegalArgumentException("boom");
assertThat(Exceptions.multiple(e1, e2))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasSuppressedException(e1)
.hasSuppressedException(e2);
}
@Test
public void multipleWithNullIterable() {
//noinspection ConstantConditions
assertThat(Exceptions.multiple((Iterable<Throwable>) null))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasNoSuppressedExceptions();
}
@Test
public void multipleWithEmptyIterable() {
assertThat(Exceptions.multiple(Collections.emptyList()))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasNoSuppressedExceptions();
}
@Test
public void multipleWithIterable() {
IOException e1 = new IOException("boom");
IllegalArgumentException e2 = new IllegalArgumentException("boom");
assertThat(Exceptions.multiple(Arrays.asList(e1, e2)))
.isInstanceOf(RuntimeException.class)
.isExactlyInstanceOf(CompositeException.class)
.hasMessage("Multiple exceptions")
.hasSuppressedException(e1)
.hasSuppressedException(e2);
}
@Test
public void isMultiple() {
Exception e1 = new IllegalStateException("1");
Exception e2 = new IllegalArgumentException("2");
Exception composite = Exceptions.multiple(e1, e2);
assertThat(Exceptions.isMultiple(composite)).isTrue();
assertThat(Exceptions.isMultiple(Exceptions.failWithCancel())).isFalse();
assertThat(Exceptions.isMultiple(null)).isFalse();
}
@Test
public void unwrapMultipleNull() {
assertThat(Exceptions.unwrapMultiple(null))
.isEmpty();
}
@Test
public void unwrapMultipleNotComposite() {
RuntimeException e1 = Exceptions.failWithCancel();
assertThat(Exceptions.unwrapMultiple(e1)).containsExactly(e1);
}
@Test
public void addThrowable() {
Throwable e1 = new IllegalStateException("add1");
Throwable e2 = new IllegalArgumentException("add2");
Throwable e3 = new OutOfMemoryError("add3");
assertThat(addThrowable).isNull();
Exceptions.addThrowable(ADD_THROWABLE, this, e1);
assertThat(addThrowable).isSameAs(e1);
Exceptions.addThrowable(ADD_THROWABLE, this, e2);
assertThat(Exceptions.isMultiple(addThrowable)).isTrue();
assertThat(addThrowable)
.hasSuppressedException(e1)
.hasSuppressedException(e2);
Exceptions.addThrowable(ADD_THROWABLE, this, e3);
assertThat(Exceptions.isMultiple(addThrowable)).isTrue();
assertThat(addThrowable)
.hasSuppressedException(e1)
.hasSuppressedException(e2)
.hasSuppressedException(e3);
}
@Test
public void addThrowableRace() throws Exception {
for (int i = 0; i < 10; i++) {
final int idx = i;
RaceTestUtils.race(
() -> Exceptions.addThrowable(ADD_THROWABLE, ExceptionsTest.this, new IllegalStateException("boomState" + idx)),
() -> Exceptions.addThrowable(ADD_THROWABLE, ExceptionsTest.this, new IllegalArgumentException("boomArg" + idx))
);
}
assertThat(addThrowable.getSuppressed())
.hasSize(20);
}
@Test
public void addSuppressedToNormal() {
Exception original = new Exception("foo");
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isSameAs(original)
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedToRejectedInstance() {
Throwable original = new RejectedExecutionException("foo");
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isSameAs(original)
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedToSame() {
Throwable original = new Exception("foo");
assertThat(Exceptions.addSuppressed(original, original))
.isSameAs(original)
.hasNoSuppressedExceptions();
}
@Test
public void addSuppressedToRejectedSingleton1() {
Throwable original = REJECTED_EXECUTION;
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isNotSameAs(original)
.hasMessage(original.getMessage())
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedToRejectedSingleton2() {
Throwable original = NOT_TIME_CAPABLE_REJECTED_EXECUTION;
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isNotSameAs(original)
.hasMessage(original.getMessage())
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedToTERMINATED() {
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(TERMINATED, suppressed))
.hasNoSuppressedExceptions()
.isSameAs(TERMINATED);
}
@Test
public void addSuppressedRuntimeToNormal() {
RuntimeException original = new RuntimeException("foo");
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isSameAs(original)
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedRuntimeToRejectedInstance() {
RuntimeException original = new RejectedExecutionException("foo");
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isSameAs(original)
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedRuntimeToSame() {
RuntimeException original = new RuntimeException("foo");
assertThat(Exceptions.addSuppressed(original, original))
.isSameAs(original)
.hasNoSuppressedExceptions();
}
@Test
public void addSuppressedRuntimeToRejectedSingleton1() {
RuntimeException original = REJECTED_EXECUTION;
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isNotSameAs(original)
.hasMessage(original.getMessage())
.hasSuppressedException(suppressed);
}
@Test
public void addSuppressedRuntimeToRejectedSingleton2() {
RuntimeException original = NOT_TIME_CAPABLE_REJECTED_EXECUTION;
Exception suppressed = new IllegalStateException("boom");
assertThat(Exceptions.addSuppressed(original, suppressed))
.isNotSameAs(original)
.hasMessage(original.getMessage())
.hasSuppressedException(suppressed);
}
@Test
public void failWithRejectedNormalWraps() {
Throwable test = new IllegalStateException("boom");
assertThat(Exceptions.failWithRejected(test))
.isInstanceOf(Exceptions.ReactorRejectedExecutionException.class)
.hasMessage("Scheduler unavailable")
.hasCause(test);
}
@Test
public void failWithRejectedSingletonREEWraps() {
Throwable test = REJECTED_EXECUTION;
assertThat(Exceptions.failWithRejected(test))
.isInstanceOf(Exceptions.ReactorRejectedExecutionException.class)
.hasMessage("Scheduler unavailable")
.hasCause(test);
}
@Test
public void failWithRejectedNormalREEWraps() {
Throwable test = new RejectedExecutionException("boom");
assertThat(Exceptions.failWithRejected(test))
.isInstanceOf(Exceptions.ReactorRejectedExecutionException.class)
.hasMessage("Scheduler unavailable")
.hasCause(test);
}
@Test
public void failWithRejectedReactorREENoOp() {
Throwable test = new Exceptions.ReactorRejectedExecutionException("boom", REJECTED_EXECUTION);
assertThat(Exceptions.failWithRejected(test))
.isSameAs(test)
.hasCause(REJECTED_EXECUTION);
}
@Test
public void unwrapMultipleExcludingTraceback() {
Mono<String> errorMono1 = Mono.error(new IllegalStateException("expected1"));
Mono<String> errorMono2 = Mono.error(new IllegalStateException("expected2"));
Mono<Throwable> mono = Mono.zipDelayError(errorMono1, errorMono2)
.checkpoint("checkpoint")
.<Throwable>map(tuple -> new IllegalStateException("should have failed: " + tuple))
.onErrorResume(Mono::just);
Throwable compositeException = mono.block();
List<Throwable> exceptions = Exceptions.unwrapMultiple(compositeException);
List<Throwable> filteredExceptions = Exceptions.unwrapMultipleExcludingTracebacks(compositeException);
assertThat(exceptions).as("unfiltered composite has traceback")
.hasSize(3);
assertThat(exceptions).filteredOn(e -> !Exceptions.isTraceback(e))
.as("filtered out tracebacks")
.containsExactlyElementsOf(filteredExceptions)
.hasSize(2)
.hasOnlyElementsOfType(IllegalStateException.class);
}
@Test
public void isRetryExhausted() {
Throwable match1 = Exceptions.retryExhausted("only a message", null);
Throwable match2 = Exceptions.retryExhausted("message and cause", new RuntimeException("cause: boom"));
Throwable noMatch = new IllegalStateException("Retry exhausted: 10/10");
assertThat(Exceptions.isRetryExhausted(null)).as("null").isFalse();
assertThat(Exceptions.isRetryExhausted(match1)).as("match1").isTrue();
assertThat(Exceptions.isRetryExhausted(match2)).as("match2").isTrue();
assertThat(Exceptions.isRetryExhausted(noMatch)).as("noMatch").isFalse();
}
@Test
public void retryExhaustedMessageWithNoCause() {
Throwable retryExhausted = Exceptions.retryExhausted("message with no cause", null);
assertThat(retryExhausted).hasMessage("message with no cause")
.hasNoCause();
}
@Test
public void retryExhaustedMessageWithCause() {
Throwable retryExhausted = Exceptions.retryExhausted("message with cause", new RuntimeException("boom"));
assertThat(retryExhausted).hasMessage("message with cause")
.hasCause(new RuntimeException("boom"));
}
}
| ExceptionsTest |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditReplayMapper.java | {
"start": 3941,
"end": 5650
} | class ____ extends WorkloadMapper<LongWritable, Text,
UserCommandKey, CountTimeWritable> {
public static final String INPUT_PATH_KEY = "auditreplay.input-path";
public static final String OUTPUT_PATH_KEY = "auditreplay.output-path";
public static final String NUM_THREADS_KEY = "auditreplay.num-threads";
public static final int NUM_THREADS_DEFAULT = 1;
public static final String CREATE_BLOCKS_KEY = "auditreplay.create-blocks";
public static final boolean CREATE_BLOCKS_DEFAULT = true;
public static final String RATE_FACTOR_KEY = "auditreplay.rate-factor";
public static final double RATE_FACTOR_DEFAULT = 1.0;
public static final String COMMAND_PARSER_KEY =
"auditreplay.command-parser.class";
public static final Class<AuditLogDirectParser> COMMAND_PARSER_DEFAULT =
AuditLogDirectParser.class;
private static final Logger LOG =
LoggerFactory.getLogger(AuditReplayMapper.class);
// This is the maximum amount that the mapper should read ahead from the input
// as compared to the replay time. Setting this to one minute avoids reading
// too
// many entries into memory simultaneously but ensures that the replay threads
// should not ever run out of entries to replay.
private static final long MAX_READAHEAD_MS = 60000;
public static final String INDIVIDUAL_COMMANDS_COUNTER_GROUP =
"INDIVIDUAL_COMMANDS";
public static final String INDIVIDUAL_COMMANDS_LATENCY_SUFFIX = "_LATENCY";
public static final String INDIVIDUAL_COMMANDS_INVALID_SUFFIX = "_INVALID";
public static final String INDIVIDUAL_COMMANDS_COUNT_SUFFIX = "_COUNT";
/** {@link org.apache.hadoop.mapreduce.Counter} definitions for replay. */
public | AuditReplayMapper |
java | elastic__elasticsearch | x-pack/plugin/sql/sql-action/src/test/java/org/elasticsearch/xpack/sql/action/SqlRequestParsersTests.java | {
"start": 1753,
"end": 2000
} | enum ____ org.elasticsearch.xpack.sql.proto.Mode.VALUE",
SqlClearCursorRequest::fromXContent
);
assertParsingErrorMessageReason(
"""
{"cursor":"foo","mode" : "value"}""",
"No | constant |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/arrow/writers/VarBinaryWriter.java | {
"start": 2268,
"end": 2792
} | class ____ extends VarBinaryWriter<RowData> {
private VarBinaryWriterForRow(VarBinaryVector varBinaryVector) {
super(varBinaryVector);
}
@Override
boolean isNullAt(RowData in, int ordinal) {
return in.isNullAt(ordinal);
}
@Override
byte[] readBinary(RowData in, int ordinal) {
return in.getBinary(ordinal);
}
}
/** {@link VarBinaryWriter} for {@link ArrayData} input. */
public static final | VarBinaryWriterForRow |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/engine/EngineKey.java | {
"start": 365,
"end": 1299
} | class ____ implements Key {
private final Object model;
private final int width;
private final int height;
private final Class<?> resourceClass;
private final Class<?> transcodeClass;
private final Key signature;
private final Map<Class<?>, Transformation<?>> transformations;
private final Options options;
private int hashCode;
EngineKey(
Object model,
Key signature,
int width,
int height,
Map<Class<?>, Transformation<?>> transformations,
Class<?> resourceClass,
Class<?> transcodeClass,
Options options) {
this.model = Preconditions.checkNotNull(model);
this.signature = Preconditions.checkNotNull(signature, "Signature must not be null");
this.width = width;
this.height = height;
this.transformations = Preconditions.checkNotNull(transformations);
this.resourceClass =
Preconditions.checkNotNull(resourceClass, "Resource | EngineKey |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/JpaRepositoryTests.java | {
"start": 1920,
"end": 5603
} | class ____ {
@PersistenceContext EntityManager em;
private JpaRepository<SampleEntity, SampleEntityPK> repository;
private CrudRepository<PersistableWithIdClass, PersistableWithIdClassPK> idClassRepository;
@BeforeEach
void setUp() {
repository = new JpaRepositoryFactory(em).getRepository(SampleEntityRepository.class);
idClassRepository = new JpaRepositoryFactory(em).getRepository(SampleWithIdClassRepository.class);
}
@Test
void testCrudOperationsForCompoundKeyEntity() {
SampleEntity entity = new SampleEntity("foo", "bar");
repository.saveAndFlush(entity);
assertThat(repository.existsById(new SampleEntityPK("foo", "bar"))).isTrue();
assertThat(repository.count()).isOne();
assertThat(repository.findById(new SampleEntityPK("foo", "bar"))).contains(entity);
repository.deleteAll(Arrays.asList(entity));
repository.flush();
assertThat(repository.count()).isZero();
}
@Test // DATAJPA-50
void executesCrudOperationsForEntityWithIdClass() {
PersistableWithIdClass entity = new PersistableWithIdClass(1L, 1L);
idClassRepository.save(entity);
assertThat(entity.getFirst()).isNotNull();
assertThat(entity.getSecond()).isNotNull();
PersistableWithIdClassPK id = new PersistableWithIdClassPK(entity.getFirst(), entity.getSecond());
assertThat(idClassRepository.findById(id)).contains(entity);
}
@Test // DATAJPA-266
void testExistsForDomainObjectsWithCompositeKeys() {
PersistableWithIdClass s1 = idClassRepository.save(new PersistableWithIdClass(1L, 1L));
PersistableWithIdClass s2 = idClassRepository.save(new PersistableWithIdClass(2L, 2L));
assertThat(idClassRepository.existsById(s1.getId())).isTrue();
assertThat(idClassRepository.existsById(s2.getId())).isTrue();
assertThat(idClassRepository.existsById(new PersistableWithIdClassPK(1L, 2L))).isFalse();
}
@Test // DATAJPA-527
void executesExistsForEntityWithIdClass() {
PersistableWithIdClass entity = new PersistableWithIdClass(1L, 1L);
idClassRepository.save(entity);
assertThat(entity.getFirst()).isNotNull();
assertThat(entity.getSecond()).isNotNull();
PersistableWithIdClassPK id = new PersistableWithIdClassPK(entity.getFirst(), entity.getSecond());
assertThat(idClassRepository.existsById(id)).isTrue();
}
@Test // DATAJPA-1818
void deleteAllByIdInBatch() {
SampleEntity one = new SampleEntity("one", "eins");
SampleEntity two = new SampleEntity("two", "zwei");
SampleEntity three = new SampleEntity("three", "drei");
repository.saveAll(Arrays.asList(one, two, three));
repository.flush();
repository
.deleteAllByIdInBatch(Arrays.asList(new SampleEntityPK("one", "eins"), new SampleEntityPK("three", "drei")));
assertThat(repository.findAll()).containsExactly(two);
}
@Test // GH-2242
void deleteAllByIdInBatchShouldConvertAnIterableToACollection() {
SampleEntity one = new SampleEntity("one", "eins");
SampleEntity two = new SampleEntity("two", "zwei");
SampleEntity three = new SampleEntity("three", "drei");
repository.saveAll(Arrays.asList(one, two, three));
repository.flush();
/**
* Wrap a {@link List} inside an {@link Iterable} to verify that {@link SimpleJpaRepository} can properly convert a
* pure {@link Iterable} to a {@link Collection}.
*/
Iterable<SampleEntityPK> ids = new Iterable<SampleEntityPK>() {
private List<SampleEntityPK> ids = Arrays.asList(new SampleEntityPK("one", "eins"),
new SampleEntityPK("three", "drei"));
@Override
public Iterator<SampleEntityPK> iterator() {
return ids.iterator();
}
};
repository.deleteAllByIdInBatch(ids);
assertThat(repository.findAll()).containsExactly(two);
}
private | JpaRepositoryTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/AsmCircularImportDetectionTests.java | {
"start": 1201,
"end": 1713
} | class ____ extends AbstractCircularImportDetectionTests {
@Override
protected ConfigurationClassParser newParser() {
return new ConfigurationClassParser(
new CachingMetadataReaderFactory(),
new FailFastProblemReporter(),
new StandardEnvironment(),
new DefaultResourceLoader(),
new AnnotationBeanNameGenerator(),
new DefaultListableBeanFactory());
}
@Override
protected String loadAsConfigurationSource(Class<?> clazz) {
return clazz.getName();
}
}
| AsmCircularImportDetectionTests |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/io/parsing/Symbol.java | {
"start": 14316,
"end": 15350
} | class ____ extends Symbol {
public final Symbol[] symbols;
public final String[] labels;
private Alternative(Symbol[] symbols, String[] labels) {
super(Kind.ALTERNATIVE);
this.symbols = symbols;
this.labels = labels;
}
public Symbol getSymbol(int index) {
return symbols[index];
}
public String getLabel(int index) {
return labels[index];
}
public int size() {
return symbols.length;
}
public int findLabel(String label) {
if (label != null) {
for (int i = 0; i < labels.length; i++) {
if (label.equals(labels[i])) {
return i;
}
}
}
return -1;
}
@Override
public Alternative flatten(Map<Sequence, Sequence> map, Map<Sequence, List<Fixup>> map2) {
Symbol[] ss = new Symbol[symbols.length];
for (int i = 0; i < ss.length; i++) {
ss[i] = symbols[i].flatten(map, map2);
}
return new Alternative(ss, labels);
}
}
public static | Alternative |
java | netty__netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksAuthRequestTest.java | {
"start": 777,
"end": 3366
} | class ____ {
@Test
public void testConstructorParamsAreNotNull() {
try {
new SocksAuthRequest(null, "");
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
try {
new SocksAuthRequest("", null);
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testUsernameOrPasswordIsNotAscii() {
try {
new SocksAuthRequest("παράδειγμα.δοκιμή", "password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("username", "παράδειγμα.δοκιμή");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testUsernameOrPasswordLengthIsLessThan255Chars() {
try {
new SocksAuthRequest(
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword",
"password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("password",
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| SocksAuthRequestTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCommentStatement.java | {
"start": 1024,
"end": 2269
} | enum ____ {
TABLE, COLUMN, INDEX, VIEW
}
private SQLExprTableSource on;
private Type type;
private SQLExpr comment;
public SQLExpr getComment() {
return comment;
}
public void setComment(SQLExpr comment) {
this.comment = comment;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public SQLExprTableSource getOn() {
return on;
}
public void setOn(SQLExprTableSource on) {
if (on != null) {
on.setParent(this);
}
this.on = on;
}
public void setOn(SQLName on) {
this.setOn(new SQLExprTableSource(on));
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, on);
acceptChild(visitor, comment);
}
visitor.endVisit(this);
}
@Override
public List<SQLObject> getChildren() {
List<SQLObject> children = new ArrayList<SQLObject>();
if (on != null) {
children.add(on);
}
if (comment != null) {
children.add(comment);
}
return children;
}
}
| Type |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/servlet/context/WebListenerHandlerTests.java | {
"start": 1308,
"end": 2023
} | class ____ {
private final WebListenerHandler handler = new WebListenerHandler();
private final SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
@Test
void listener() throws IOException {
AnnotatedBeanDefinition definition = mock(AnnotatedBeanDefinition.class);
given(definition.getBeanClassName()).willReturn(TestListener.class.getName());
given(definition.getMetadata())
.willReturn(new SimpleMetadataReaderFactory().getMetadataReader(TestListener.class.getName())
.getAnnotationMetadata());
this.handler.handle(definition, this.registry);
this.registry.getBeanDefinition(TestListener.class.getName() + "Registrar");
}
@WebListener
static | WebListenerHandlerTests |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleZipArrayTest.java | {
"start": 1307,
"end": 7440
} | class ____ extends RxJavaTest {
final BiFunction<Object, Object, Object> addString = new BiFunction<Object, Object, Object>() {
@Override
public Object apply(Object a, Object b) throws Exception {
return "" + a + b;
}
};
final Function3<Object, Object, Object, Object> addString3 = new Function3<Object, Object, Object, Object>() {
@Override
public Object apply(Object a, Object b, Object c) throws Exception {
return "" + a + b + c;
}
};
@Test
public void firstError() {
Single.zip(Single.error(new TestException()), Single.just(1), addString)
.test()
.assertFailure(TestException.class);
}
@Test
public void secondError() {
Single.zip(Single.just(1), Single.<Integer>error(new TestException()), addString)
.test()
.assertFailure(TestException.class);
}
@Test
public void dispose() {
PublishProcessor<Integer> pp = PublishProcessor.create();
TestObserver<Object> to = Single.zip(pp.single(0), pp.single(0), addString)
.test();
assertTrue(pp.hasSubscribers());
to.dispose();
assertFalse(pp.hasSubscribers());
}
@Test
public void zipperThrows() {
Single.zip(Single.just(1), Single.just(2), new BiFunction<Integer, Integer, Object>() {
@Override
public Object apply(Integer a, Integer b) throws Exception {
throw new TestException();
}
})
.test()
.assertFailure(TestException.class);
}
@Test
public void zipperReturnsNull() {
Single.zip(Single.just(1), Single.just(2), new BiFunction<Integer, Integer, Object>() {
@Override
public Object apply(Integer a, Integer b) throws Exception {
return null;
}
})
.test()
.assertFailure(NullPointerException.class);
}
@Test
public void middleError() {
PublishProcessor<Integer> pp0 = PublishProcessor.create();
PublishProcessor<Integer> pp1 = PublishProcessor.create();
TestObserver<Object> to = Single.zip(pp0.single(0), pp1.single(0), pp0.single(0), addString3)
.test();
pp1.onError(new TestException());
assertFalse(pp0.hasSubscribers());
to.assertFailure(TestException.class);
}
@Test
public void innerErrorRace() {
for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
final PublishProcessor<Integer> pp0 = PublishProcessor.create();
final PublishProcessor<Integer> pp1 = PublishProcessor.create();
final TestObserver<Object> to = Single.zip(pp0.single(0), pp1.single(0), addString)
.test();
final TestException ex = new TestException();
Runnable r1 = new Runnable() {
@Override
public void run() {
pp0.onError(ex);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
pp1.onError(ex);
}
};
TestHelper.race(r1, r2);
to.assertFailure(TestException.class);
if (!errors.isEmpty()) {
TestHelper.assertUndeliverable(errors, 0, TestException.class);
}
} finally {
RxJavaPlugins.reset();
}
}
}
@Test(expected = NullPointerException.class)
public void zipArrayOneIsNull() {
Single.zipArray(new Function<Object[], Object>() {
@Override
public Object apply(Object[] v) {
return 1;
}
}, Single.just(1), null)
.blockingGet();
}
@SuppressWarnings("unchecked")
@Test
public void emptyArray() {
Single.zipArray(new Function<Object[], Object[]>() {
@Override
public Object[] apply(Object[] a) throws Exception {
return a;
}
}, new SingleSource[0])
.test()
.assertFailure(NoSuchElementException.class);
}
@Test
public void oneArray() {
Single.zipArray(new Function<Object[], Object>() {
@Override
public Object apply(Object[] a) throws Exception {
return (Integer)a[0] + 1;
}
}, Single.just(1))
.test()
.assertResult(2);
}
@Test
public void singleSourceZipperReturnsNull() {
Single.zipArray(Functions.justFunction(null), Single.just(1))
.to(TestHelper.<Object>testConsumer())
.assertFailureAndMessage(NullPointerException.class, "The zipper returned a null value");
}
@Test
public void singleSourceZipperReturnsNull2() {
Single.zipArray(Functions.justFunction(null), Single.just(1), Single.just(2))
.to(TestHelper.<Object>testConsumer())
.assertFailureAndMessage(NullPointerException.class, "The zipper returned a null value");
}
@Test
public void dispose2() {
TestHelper.checkDisposed(Single.zipArray(Functions.justFunction(1), SingleSubject.create(), SingleSubject.create()));
}
@Test
public void bothSucceed() {
Single.zipArray(a -> Arrays.asList(a), Single.just(1), Single.just(2))
.test()
.assertResult(Arrays.asList(1, 2));
}
@Test
public void onSuccessAfterDispose() {
AtomicReference<SingleObserver<? super Integer>> emitter = new AtomicReference<>();
TestObserver<List<Object>> to = Single.zipArray(Arrays::asList,
(SingleSource<Integer>)o -> emitter.set(o), Single.<Integer>never())
.test();
emitter.get().onSubscribe(Disposable.empty());
to.dispose();
emitter.get().onSuccess(1);
to.assertEmpty();
}
}
| SingleZipArrayTest |
java | apache__camel | components/camel-huawei/camel-huaweicloud-obs/src/generated/java/org/apache/camel/component/huaweicloud/obs/OBSEndpointUriFactory.java | {
"start": 525,
"end": 3969
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":operation";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(42);
props.add("accessKey");
props.add("backoffErrorThreshold");
props.add("backoffIdleThreshold");
props.add("backoffMultiplier");
props.add("bridgeErrorHandler");
props.add("bucketLocation");
props.add("bucketName");
props.add("delay");
props.add("deleteAfterRead");
props.add("delimiter");
props.add("destinationBucket");
props.add("endpoint");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("fileName");
props.add("greedy");
props.add("ignoreSslVerification");
props.add("includeFolders");
props.add("initialDelay");
props.add("lazyStartProducer");
props.add("maxMessagesPerPoll");
props.add("moveAfterRead");
props.add("objectName");
props.add("operation");
props.add("pollStrategy");
props.add("prefix");
props.add("proxyHost");
props.add("proxyPassword");
props.add("proxyPort");
props.add("proxyUser");
props.add("region");
props.add("repeatCount");
props.add("runLoggingLevel");
props.add("scheduledExecutorService");
props.add("scheduler");
props.add("schedulerProperties");
props.add("secretKey");
props.add("sendEmptyMessageWhenIdle");
props.add("serviceKeys");
props.add("startScheduler");
props.add("timeUnit");
props.add("useFixedDelay");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(5);
secretProps.add("accessKey");
secretProps.add("proxyPassword");
secretProps.add("proxyUser");
secretProps.add("secretKey");
secretProps.add("serviceKeys");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
Map<String, String> prefixes = new HashMap<>(1);
prefixes.put("schedulerProperties", "scheduler.");
MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes);
}
@Override
public boolean isEnabled(String scheme) {
return "hwcloud-obs".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "operation", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| OBSEndpointUriFactory |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/exchange/ExchangeBufferTests.java | {
"start": 1112,
"end": 4049
} | class ____ extends ESTestCase {
public void testDrainPages() throws Exception {
ExchangeBuffer buffer = new ExchangeBuffer(randomIntBetween(10, 1000));
var blockFactory = blockFactory();
CountDownLatch latch = new CountDownLatch(1);
Thread[] producers = new Thread[between(1, 4)];
AtomicBoolean stopped = new AtomicBoolean();
AtomicInteger addedPages = new AtomicInteger();
for (int t = 0; t < producers.length; t++) {
producers[t] = new Thread(() -> {
safeAwait(latch);
while (stopped.get() == false && addedPages.incrementAndGet() < 10_000) {
buffer.addPage(randomPage(blockFactory));
}
});
producers[t].start();
}
latch.countDown();
try {
int minPage = between(10, 100);
int receivedPage = 0;
while (receivedPage < minPage) {
Page p = buffer.pollPage();
if (p != null) {
p.releaseBlocks();
++receivedPage;
}
}
} finally {
buffer.finish(true);
stopped.set(true);
}
for (Thread t : producers) {
t.join();
}
assertThat(buffer.size(), equalTo(0));
blockFactory.ensureAllBlocksAreReleased();
}
public void testOutstandingPages() throws Exception {
ExchangeBuffer buffer = new ExchangeBuffer(randomIntBetween(1000, 10000));
var blockFactory = blockFactory();
Page p1 = randomPage(blockFactory);
Page p2 = randomPage(blockFactory);
buffer.addPage(p1);
buffer.addPage(p2);
buffer.finish(false);
buffer.addPage(randomPage(blockFactory));
assertThat(buffer.size(), equalTo(2));
assertSame(buffer.pollPage(), p1);
p1.releaseBlocks();
assertSame(buffer.pollPage(), p2);
p2.releaseBlocks();
assertNull(buffer.pollPage());
assertTrue(buffer.isFinished());
blockFactory.ensureAllBlocksAreReleased();
}
private static MockBlockFactory blockFactory() {
BigArrays bigArrays = new MockBigArrays(PageCacheRecycler.NON_RECYCLING_INSTANCE, ByteSizeValue.ofGb(1)).withCircuitBreaking();
CircuitBreaker breaker = bigArrays.breakerService().getBreaker(CircuitBreaker.REQUEST);
return new MockBlockFactory(breaker, bigArrays);
}
private static Page randomPage(BlockFactory blockFactory) {
Block block = RandomBlock.randomBlock(
blockFactory,
randomFrom(ElementType.LONG, ElementType.BYTES_REF, ElementType.BOOLEAN),
randomIntBetween(1, 100),
randomBoolean(),
0,
between(1, 2),
0,
between(1, 2)
).block();
return new Page(block);
}
}
| ExchangeBufferTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/InjectOnFinalFieldTest.java | {
"start": 2737,
"end": 2930
} | class ____ {
public final int n = 0;
}
/** Class has an injectable(com.google.inject.Inject) field that is not final. */
public | TestClass2 |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/ApplicationSubmissionContextInfo.java | {
"start": 1236,
"end": 1481
} | class ____ allow users to send information required to create an
* ApplicationSubmissionContext which can then be used to submit an app
*
*/
@XmlRootElement(name = "application-submission-context")
@XmlAccessorType(XmlAccessType.FIELD)
public | to |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/TcpHealthCheckProcessor.java | {
"start": 2120,
"end": 5841
} | class ____ implements HealthCheckProcessorV2, Runnable {
public static final String TYPE = HealthCheckType.TCP.name();
public static final int CONNECT_TIMEOUT_MS = 500;
/**
* this value has been carefully tuned, do not modify unless you're confident.
*/
private static final int NIO_THREAD_COUNT = EnvUtil.getAvailableProcessors(0.5);
/**
* because some hosts doesn't support keep-alive connections, disabled temporarily.
*/
private static final long TCP_KEEP_ALIVE_MILLIS = 0;
private final HealthCheckCommonV2 healthCheckCommon;
private final SwitchDomain switchDomain;
private final Map<String, BeatKey> keyMap = new ConcurrentHashMap<>();
private final BlockingQueue<Beat> taskQueue = new LinkedBlockingQueue<>();
private final Selector selector;
public TcpHealthCheckProcessor(HealthCheckCommonV2 healthCheckCommon, SwitchDomain switchDomain) {
this.healthCheckCommon = healthCheckCommon;
this.switchDomain = switchDomain;
try {
selector = Selector.open();
GlobalExecutor.submitTcpCheck(this);
} catch (Exception e) {
throw new IllegalStateException("Error while initializing SuperSense(TM).");
}
}
@Override
public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {
HealthCheckInstancePublishInfo instance = (HealthCheckInstancePublishInfo) task.getClient()
.getInstancePublishInfo(service);
if (null == instance) {
return;
}
// TODO handle marked(white list) logic like v1.x.
if (!instance.tryStartCheck()) {
SRV_LOG.warn("[HEALTH-CHECK-V2] tcp check started before last one finished, service: {} : {} : {}:{}",
service.getNameSpaceGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort());
healthCheckCommon
.reEvaluateCheckRt(task.getCheckRtNormalized() * 2, task, switchDomain.getTcpHealthParams());
return;
}
taskQueue.add(new Beat(task, service, metadata, instance));
MetricsMonitor.getTcpHealthCheckMonitor().incrementAndGet();
}
@Override
public String getType() {
return TYPE;
}
private void processTask() throws Exception {
Collection<Callable<Void>> tasks = new LinkedList<>();
do {
Beat beat = taskQueue.poll(CONNECT_TIMEOUT_MS / 2, TimeUnit.MILLISECONDS);
if (beat == null) {
return;
}
tasks.add(new TaskProcessor(beat));
} while (taskQueue.size() > 0 && tasks.size() < NIO_THREAD_COUNT * 64);
for (Future<?> f : GlobalExecutor.invokeAllTcpSuperSenseTask(tasks)) {
f.get();
}
}
@Override
public void run() {
while (true) {
try {
processTask();
int readyCount = selector.selectNow();
if (readyCount <= 0) {
continue;
}
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
GlobalExecutor.executeTcpSuperSense(new PostProcessor(key));
}
} catch (Throwable e) {
SRV_LOG.error("[HEALTH-CHECK-V2] error while processing NIO task", e);
}
}
}
public | TcpHealthCheckProcessor |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/DefaultExecutionGraphBuilder.java | {
"start": 3751,
"end": 17353
} | class ____ {
public static DefaultExecutionGraph buildGraph(
JobGraph jobGraph,
Configuration jobManagerConfig,
ScheduledExecutorService futureExecutor,
Executor ioExecutor,
ClassLoader classLoader,
CompletedCheckpointStore completedCheckpointStore,
CheckpointsCleaner checkpointsCleaner,
CheckpointIDCounter checkpointIdCounter,
Duration rpcTimeout,
BlobWriter blobWriter,
Logger log,
ShuffleMaster<?> shuffleMaster,
JobMasterPartitionTracker partitionTracker,
TaskDeploymentDescriptorFactory.PartitionLocationConstraint partitionLocationConstraint,
ExecutionDeploymentListener executionDeploymentListener,
ExecutionStateUpdateListener executionStateUpdateListener,
long initializationTimestamp,
VertexAttemptNumberStore vertexAttemptNumberStore,
VertexParallelismStore vertexParallelismStore,
CheckpointStatsTracker checkpointStatsTracker,
boolean isDynamicGraph,
ExecutionJobVertex.Factory executionJobVertexFactory,
MarkPartitionFinishedStrategy markPartitionFinishedStrategy,
boolean nonFinishedHybridPartitionShouldBeUnknown,
JobManagerJobMetricGroup jobManagerJobMetricGroup,
ExecutionPlanSchedulingContext executionPlanSchedulingContext)
throws JobExecutionException, JobException {
checkNotNull(jobGraph, "job graph cannot be null");
final String jobName = jobGraph.getName();
final JobID jobId = jobGraph.getJobID();
final JobInformation jobInformation =
new JobInformation(
jobId,
jobGraph.getJobType(),
jobName,
jobGraph.getSerializedExecutionConfig(),
jobGraph.getJobConfiguration(),
jobGraph.getUserJarBlobKeys(),
jobGraph.getClasspaths());
final int executionHistorySizeLimit =
jobManagerConfig.get(JobManagerOptions.MAX_ATTEMPTS_HISTORY_SIZE);
final PartitionGroupReleaseStrategy.Factory partitionGroupReleaseStrategyFactory =
PartitionGroupReleaseStrategyFactoryLoader.loadPartitionGroupReleaseStrategyFactory(
jobManagerConfig);
final int offloadShuffleDescriptorsThreshold =
jobManagerConfig.get(
TaskDeploymentDescriptorFactory.OFFLOAD_SHUFFLE_DESCRIPTORS_THRESHOLD);
final TaskDeploymentDescriptorFactory taskDeploymentDescriptorFactory;
try {
taskDeploymentDescriptorFactory =
new TaskDeploymentDescriptorFactory(
BlobWriter.serializeAndTryOffload(jobInformation, jobId, blobWriter),
jobId,
partitionLocationConstraint,
blobWriter,
nonFinishedHybridPartitionShouldBeUnknown,
offloadShuffleDescriptorsThreshold);
} catch (IOException e) {
throw new JobException("Could not create the TaskDeploymentDescriptorFactory.", e);
}
final List<JobStatusChangedListener> jobStatusChangedListeners =
JobStatusChangedListenerUtils.createJobStatusChangedListeners(
classLoader, jobManagerConfig, ioExecutor);
// create a new execution graph, if none exists so far
final DefaultExecutionGraph executionGraph =
new DefaultExecutionGraph(
jobInformation,
futureExecutor,
ioExecutor,
rpcTimeout,
executionHistorySizeLimit,
classLoader,
blobWriter,
partitionGroupReleaseStrategyFactory,
shuffleMaster,
partitionTracker,
executionDeploymentListener,
executionStateUpdateListener,
initializationTimestamp,
vertexAttemptNumberStore,
vertexParallelismStore,
isDynamicGraph,
executionJobVertexFactory,
jobGraph.getJobStatusHooks(),
markPartitionFinishedStrategy,
taskDeploymentDescriptorFactory,
jobStatusChangedListeners,
executionPlanSchedulingContext);
// set the basic properties
try {
executionGraph.setPlan(JsonPlanGenerator.generatePlan(jobGraph));
} catch (Throwable t) {
log.warn("Cannot create plan for job", t);
// give the graph an empty plan
executionGraph.setPlan(new JobPlanInfo.Plan("", "", "", new ArrayList<>()));
}
initJobVerticesOnMaster(
jobGraph.getVertices(), classLoader, log, vertexParallelismStore, jobName, jobId);
// topologically sort the job vertices and attach the graph to the existing one
List<JobVertex> sortedTopology = jobGraph.getVerticesSortedTopologicallyFromSources();
if (log.isDebugEnabled()) {
log.debug(
"Adding {} vertices from job graph {} ({}).",
sortedTopology.size(),
jobName,
jobId);
}
executionGraph.attachJobGraph(sortedTopology, jobManagerJobMetricGroup);
if (log.isDebugEnabled()) {
log.debug(
"Successfully created execution graph from job graph {} ({}).", jobName, jobId);
}
// configure the state checkpointing
if (isDynamicGraph) {
// dynamic graph does not support checkpointing so we skip it
log.warn("Skip setting up checkpointing for a job with dynamic graph.");
} else if (isCheckpointingEnabled(jobGraph)) {
JobCheckpointingSettings snapshotSettings = jobGraph.getCheckpointingSettings();
// load the state backend from the application settings
final StateBackend applicationConfiguredBackend;
final SerializedValue<StateBackend> serializedAppConfigured =
snapshotSettings.getDefaultStateBackend();
if (serializedAppConfigured == null) {
applicationConfiguredBackend = null;
} else {
try {
applicationConfiguredBackend =
serializedAppConfigured.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId, "Could not deserialize application-defined state backend.", e);
}
}
final StateBackend rootBackend;
try {
rootBackend =
StateBackendLoader.fromApplicationOrConfigOrDefault(
applicationConfiguredBackend,
jobGraph.getJobConfiguration(),
jobManagerConfig,
classLoader,
log);
} catch (IllegalConfigurationException | IOException | DynamicCodeLoadingException e) {
throw new JobExecutionException(
jobId, "Could not instantiate configured state backend", e);
}
// load the checkpoint storage from the application settings
final CheckpointStorage applicationConfiguredStorage;
final SerializedValue<CheckpointStorage> serializedAppConfiguredStorage =
snapshotSettings.getDefaultCheckpointStorage();
if (serializedAppConfiguredStorage == null) {
applicationConfiguredStorage = null;
} else {
try {
applicationConfiguredStorage =
serializedAppConfiguredStorage.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId,
"Could not deserialize application-defined checkpoint storage.",
e);
}
}
final CheckpointStorage rootStorage;
try {
rootStorage =
CheckpointStorageLoader.load(
applicationConfiguredStorage,
rootBackend,
jobGraph.getJobConfiguration(),
jobManagerConfig,
classLoader,
log);
} catch (IllegalConfigurationException | DynamicCodeLoadingException e) {
throw new JobExecutionException(
jobId, "Could not instantiate configured checkpoint storage", e);
}
// instantiate the user-defined checkpoint hooks
final SerializedValue<MasterTriggerRestoreHook.Factory[]> serializedHooks =
snapshotSettings.getMasterHooks();
final List<MasterTriggerRestoreHook<?>> hooks;
if (serializedHooks == null) {
hooks = Collections.emptyList();
} else {
final MasterTriggerRestoreHook.Factory[] hookFactories;
try {
hookFactories = serializedHooks.deserializeValue(classLoader);
} catch (IOException | ClassNotFoundException e) {
throw new JobExecutionException(
jobId, "Could not instantiate user-defined checkpoint hooks", e);
}
final Thread thread = Thread.currentThread();
final ClassLoader originalClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(classLoader);
try {
hooks = new ArrayList<>(hookFactories.length);
for (MasterTriggerRestoreHook.Factory factory : hookFactories) {
hooks.add(MasterHooks.wrapHook(factory.create(), classLoader));
}
} finally {
thread.setContextClassLoader(originalClassLoader);
}
}
final CheckpointCoordinatorConfiguration chkConfig =
snapshotSettings.getCheckpointCoordinatorConfiguration();
executionGraph.enableCheckpointing(
chkConfig,
hooks,
checkpointIdCounter,
completedCheckpointStore,
rootBackend,
rootStorage,
checkpointStatsTracker,
checkpointsCleaner,
jobManagerConfig.get(STATE_CHANGE_LOG_STORAGE));
}
return executionGraph;
}
public static void initJobVerticesOnMaster(
Iterable<JobVertex> jobVertices,
ClassLoader classLoader,
Logger log,
VertexParallelismStore vertexParallelismStore,
String jobName,
JobID jobId)
throws JobExecutionException {
// initialize the vertices that have a master initialization hook
// file output formats create directories here, input formats create splits
final long initMasterStart = System.nanoTime();
log.info("Running initialization on master for job {} ({}).", jobName, jobId);
for (JobVertex vertex : jobVertices) {
String executableClass = vertex.getInvokableClassName();
if (executableClass == null || executableClass.isEmpty()) {
throw new JobSubmissionException(
jobId,
"The vertex "
+ vertex.getID()
+ " ("
+ vertex.getName()
+ ") has no invokable class.");
}
try {
vertex.initializeOnMaster(
new SimpleInitializeOnMasterContext(
classLoader,
vertexParallelismStore
.getParallelismInfo(vertex.getID())
.getParallelism()));
} catch (Throwable t) {
throw new JobExecutionException(
jobId,
"Cannot initialize task '" + vertex.getName() + "': " + t.getMessage(),
t);
}
}
log.info(
"Successfully ran initialization on master in {} ms.",
(System.nanoTime() - initMasterStart) / 1_000_000);
}
public static boolean isCheckpointingEnabled(JobGraph jobGraph) {
return jobGraph.getCheckpointingSettings() != null;
}
// ------------------------------------------------------------------------
/** This | DefaultExecutionGraphBuilder |
java | apache__camel | components/camel-jackson-protobuf/src/main/java/org/apache/camel/component/jackson/protobuf/transform/ProtobufBinaryDataTypeTransformer.java | {
"start": 1991,
"end": 4536
} | class ____ extends Transformer {
@Override
public void transform(Message message, DataType fromType, DataType toType) {
ProtobufSchema schema = message.getExchange().getProperty(SchemaHelper.CONTENT_SCHEMA, ProtobufSchema.class);
if (schema == null) {
throw new CamelExecutionException("Missing proper Protobuf schema for data type processing", message.getExchange());
}
try {
byte[] marshalled;
String contentClass = SchemaHelper.resolveContentClass(message.getExchange(), null);
if (contentClass != null) {
Class<?> contentType
= message.getExchange().getContext().getClassResolver().resolveMandatoryClass(contentClass);
marshalled = Protobuf.mapper().writer().forType(contentType).with(schema)
.writeValueAsBytes(message.getBody());
} else {
marshalled = Protobuf.mapper().writer().forType(JsonNode.class).with(schema)
.writeValueAsBytes(getBodyAsJsonNode(message, schema));
}
message.setBody(marshalled);
message.setHeader(Exchange.CONTENT_TYPE, MimeType.PROTOBUF_BINARY.type());
message.setHeader(SchemaHelper.CONTENT_SCHEMA, schema.getSource().toString());
} catch (InvalidPayloadException | IOException | ClassNotFoundException e) {
throw new CamelExecutionException(
"Failed to apply Protobuf binary data type on exchange", message.getExchange(), e);
}
}
private JsonNode getBodyAsJsonNode(Message message, ProtobufSchema schema)
throws InvalidPayloadException, IOException, ClassNotFoundException {
if (message.getBody() instanceof JsonNode) {
return (JsonNode) message.getBody();
}
if (message.getBody() instanceof String jsonString && Json.isJson(jsonString)) {
return Json.mapper().readerFor(JsonNode.class).readTree(jsonString);
}
return Protobuf.mapper().reader().forType(JsonNode.class).with(schema)
.readValue(getBodyAsStream(message));
}
private InputStream getBodyAsStream(Message message) throws InvalidPayloadException {
InputStream bodyStream = message.getBody(InputStream.class);
if (bodyStream == null) {
bodyStream = new ByteArrayInputStream(message.getMandatoryBody(byte[].class));
}
return bodyStream;
}
}
| ProtobufBinaryDataTypeTransformer |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openai/OpenAiRateLimitServiceSettings.java | {
"start": 514,
"end": 671
} | interface ____ {
String modelId();
URI uri();
String organizationId();
RateLimitSettings rateLimitSettings();
}
| OpenAiRateLimitServiceSettings |
java | apache__dubbo | dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/MetadataInfo.java | {
"start": 18580,
"end": 18855
} | class ____ implements Serializable {
private String name;
private String group;
private String version;
private String protocol;
private int port = -1;
private String path; // most of the time, path is the same with the | ServiceInfo |
java | resilience4j__resilience4j | resilience4j-rxjava3/src/test/java/io/github/resilience4j/rxjava3/ratelimiter/operator/CompletableRateLimiterTest.java | {
"start": 739,
"end": 3720
} | class ____ {
@Test
public void shouldEmitCompleted() {
RateLimiter rateLimiter = mock(RateLimiter.class, RETURNS_DEEP_STUBS);
given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());
Completable.complete()
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.assertComplete();
}
@Test
public void shouldDelaySubscription() {
RateLimiter rateLimiter = mock(RateLimiter.class, RETURNS_DEEP_STUBS);
given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(1).toNanos());
Completable.complete()
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.awaitDone(1, TimeUnit.SECONDS);
}
@Test
public void shouldPropagateError() {
RateLimiter rateLimiter = mock(RateLimiter.class, RETURNS_DEEP_STUBS);
given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());
Completable.error(new IOException("BAM!"))
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.assertError(IOException.class)
.assertNotComplete();
}
@Test
public void shouldEmitErrorWithRequestNotPermittedException() {
RateLimiter rateLimiter = mock(RateLimiter.class, RETURNS_DEEP_STUBS);
given(rateLimiter.reservePermission()).willReturn(-1L);
Completable.complete()
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.assertError(RequestNotPermitted.class)
.assertNotComplete();
}
@Test
public void shouldDrainRateLimiterInConditionMetOnFailedCall() {
RateLimiter rateLimiter = RateLimiter.of("someLimiter", RateLimiterConfig.custom()
.limitForPeriod(5)
.limitRefreshPeriod(Duration.ofHours(1))
.drainPermissionsOnResult(
callsResult -> isFailedAndThrown(callsResult, OverloadException.class))
.build());
Completable.error(new OverloadException.SpecificOverloadException())
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.assertError(OverloadException.SpecificOverloadException.class)
.awaitDone(1, TimeUnit.SECONDS);
assertThat(rateLimiter.getMetrics().getAvailablePermissions()).isZero();
}
@Test
public void shouldNotDrainRateLimiterOnCompletion() {
RateLimiter rateLimiter = RateLimiter.of("someLimiter", RateLimiterConfig.custom()
.limitForPeriod(5)
.limitRefreshPeriod(Duration.ofHours(1))
.drainPermissionsOnResult(callsResult -> true)
.build());
Completable.complete()
.compose(RateLimiterOperator.of(rateLimiter))
.test()
.assertComplete();
assertThat(rateLimiter.getMetrics().getAvailablePermissions()).isEqualTo(4);
}
}
| CompletableRateLimiterTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/ImplicitPropertyList.java | {
"start": 815,
"end": 2490
} | class ____<T extends Property> {
private Integer id;
private String name;
private T someProperty;
private List<T> generalProperties = new ArrayList<T>();
public ImplicitPropertyList() {
super();
}
public ImplicitPropertyList(String name) {
this.name = name;
}
@ManyToAny
@Column(name = "property_type")
@AnyKeyJavaClass( Integer.class )
@Cascade( CascadeType.ALL )
@JoinTable(name = "list_properties",
joinColumns = @JoinColumn(name = "obj_id"),
inverseJoinColumns = @JoinColumn(name = "property_id")
)
@OrderColumn(name = "prop_index")
public List<T> getGeneralProperties() {
return generalProperties;
}
public void setGeneralProperties(List<T> generalProperties) {
this.generalProperties = generalProperties;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Any
@Column(name = "property_type")
@JoinColumn(name = "property_id")
@AnyKeyJavaClass( Integer.class )
@AnyDiscriminatorValue( discriminator = "C", entity = CharProperty.class )
@AnyDiscriminatorValue( discriminator = "I", entity = IntegerProperty.class)
@AnyDiscriminatorValue( discriminator = "S", entity = StringProperty.class)
@AnyDiscriminatorValue( discriminator = "L", entity = LongProperty.class)
@Cascade( CascadeType.ALL )
public T getSomeProperty() {
return someProperty;
}
public void setSomeProperty(T someProperty) {
this.someProperty = someProperty;
}
public void addGeneralProperty(T property) {
this.generalProperties.add( property );
}
}
| ImplicitPropertyList |
java | quarkusio__quarkus | extensions/jdbc/jdbc-mariadb/runtime/src/main/java/io/quarkus/jdbc/mariadb/runtime/graal/SendPamAuthPacketFactory_Substitutions.java | {
"start": 390,
"end": 718
} | class ____ {
@Substitute
public AuthenticationPlugin initialize(String authenticationData, byte[] seed, Configuration conf,
HostAddress hostAddress) {
throw new UnsupportedOperationException("Authentication strategy 'dialog' is not supported in GraalVM");
}
}
| SendPamAuthPacketFactory_Substitutions |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/support/AbstractCdiBean.java | {
"start": 556,
"end": 2402
} | class ____<T> implements Bean<T> {
protected final Bean<RedisURI> redisURIBean;
protected final Bean<ClientResources> clientResourcesBean;
protected final BeanManager beanManager;
protected final Set<Annotation> qualifiers;
protected final String name;
public AbstractCdiBean(Bean<RedisURI> redisURIBean, Bean<ClientResources> clientResourcesBean, BeanManager beanManager,
Set<Annotation> qualifiers, String name) {
this.redisURIBean = redisURIBean;
this.clientResourcesBean = clientResourcesBean;
this.beanManager = beanManager;
this.qualifiers = qualifiers;
this.name = name;
}
@Override
@SuppressWarnings("unchecked")
public Set<Type> getTypes() {
return Collections.singleton(getBeanClass());
}
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
}
@Override
public String getName() {
return name;
}
@Override
public Class<? extends Annotation> getScope() {
return ApplicationScoped.class;
}
@Override
public Set<Class<? extends Annotation>> getStereotypes() {
Set<Class<? extends Annotation>> stereotypes = new HashSet<>();
for (Annotation annotation : getQualifiers()) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.isAnnotationPresent(Stereotype.class)) {
stereotypes.add(annotationType);
}
}
return stereotypes;
}
@Override
public boolean isAlternative() {
return false;
}
@Override
public boolean isNullable() {
return false;
}
@Override
public Set<InjectionPoint> getInjectionPoints() {
return Collections.emptySet();
}
}
| AbstractCdiBean |
java | elastic__elasticsearch | x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/action/StopWatch.java | {
"start": 372,
"end": 954
} | class ____ {
private final String name;
private final long start;
public StopWatch(String name) {
this.name = name;
start = System.nanoTime();
}
/**
* Return a textual report including the name and the number of elapsed milliseconds since object creation.
*/
public String report() {
return name + " took [" + millis() + " ms].";
}
/**
* Return number of elapsed milliseconds since object creation.
*/
public double millis() {
return (System.nanoTime() - start) / 1_000_000.0d;
}
}
| StopWatch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.