language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__camel | components/camel-docker/src/main/java/org/apache/camel/component/docker/DockerConstants.java | {
"start": 986,
"end": 3233
} | class ____ {
public static final String DOCKER_PREFIX = "CamelDocker";
public static final Map<String, Class<?>> DOCKER_DEFAULT_PARAMETERS = new HashMap<>();
/**
* Endpoint configuration defaults
*/
public static final String DEFAULT_CMD_EXEC_FACTORY = "com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory";
/**
* Connectivity *
*/
public static final String DOCKER_CLIENT_PROFILE = "CamelDockerClientProfile";
/**
* Connectivity *
*/
@Metadata(description = "The request timeout for response (in seconds)", javaType = "Integer")
public static final String DOCKER_API_REQUEST_TIMEOUT = "CamelDockerRequestTimeout";
@Metadata(description = "The location containing the SSL certificate chain", javaType = "String")
public static final String DOCKER_CERT_PATH = "CamelDockerCertPath";
@Metadata(description = "The docker host", javaType = "String")
public static final String DOCKER_HOST = "CamelDockerHost";
@Metadata(description = "The docker port", javaType = "Integer")
public static final String DOCKER_PORT = "CamelDockerPort";
@Metadata(description = "The maximum route connections", javaType = "Integer")
public static final String DOCKER_MAX_PER_ROUTE_CONNECTIONS = "CamelDockerMaxPerRouteConnections";
@Metadata(description = "The maximum total connections", javaType = "Integer")
public static final String DOCKER_MAX_TOTAL_CONNECTIONS = "CamelDockerMaxTotalConnections";
@Metadata(description = "Use HTTPS communication", javaType = "Boolean", defaultValue = "false")
public static final String DOCKER_SECURE = "CamelDockerSecure";
public static final String DOCKER_FOLLOW_REDIRECT_FILTER = "CamelDockerFollowRedirectFilter";
public static final String DOCKER_LOGGING_FILTER = "CamelDockerLoggingFilter";
@Metadata(description = "Check TLS", javaType = "Boolean", defaultValue = "false")
public static final String DOCKER_TLSVERIFY = "CamelDockerTlsVerify";
@Metadata(description = "Socket connection mode", javaType = "Boolean", defaultValue = "true")
public static final String DOCKER_SOCKET_ENABLED = "CamelDockerSocketEnabled";
@Metadata(description = "The fully qualified | DockerConstants |
java | quarkusio__quarkus | test-framework/junit5/src/main/java/io/quarkus/test/junit/buildchain/TestBuildChainCustomizerProducer.java | {
"start": 241,
"end": 354
} | interface ____ {
Consumer<BuildChainBuilder> produce(Index testClassesIndex);
}
| TestBuildChainCustomizerProducer |
java | spring-projects__spring-boot | module/spring-boot-freemarker/src/test/java/org/springframework/boot/freemarker/autoconfigure/FreeMarkerAutoConfigurationTests.java | {
"start": 4224,
"end": 4359
} | class ____ {
public String getGreeting() {
return "Hello World";
}
}
@Configuration(proxyBeanMethods = false)
static | DataModel |
java | elastic__elasticsearch | test/test-clusters/src/main/java/org/elasticsearch/test/cluster/ElasticsearchCluster.java | {
"start": 1179,
"end": 2375
} | interface ____ extends TestRule, LocalClusterHandle {
/**
* Creates a new {@link LocalClusterSpecBuilder} for defining a locally orchestrated cluster. Local clusters use a locally built
* Elasticsearch distribution.
*
* @return a builder for a local cluster
*/
static LocalClusterSpecBuilder<ElasticsearchCluster> local() {
return locateBuilderImpl();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static LocalClusterSpecBuilder<ElasticsearchCluster> locateBuilderImpl() {
ServiceLoader<LocalClusterSpecBuilder> loader = ServiceLoader.load(LocalClusterSpecBuilder.class);
List<ServiceLoader.Provider<LocalClusterSpecBuilder>> providers = loader.stream().toList();
if (providers.isEmpty()) {
return new DefaultLocalClusterSpecBuilder();
} else if (providers.size() > 1) {
String providerTypes = providers.stream().map(p -> p.type().getName()).collect(Collectors.joining(","));
throw new IllegalStateException("Located multiple LocalClusterSpecBuilder providers [" + providerTypes + "]");
}
return providers.get(0).get();
}
}
| ElasticsearchCluster |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/sequencedmultisetstate/SequencedMultiSetStateContext.java | {
"start": 1253,
"end": 1736
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
public final SequencedMultiSetStateConfig config;
public final TypeSerializer<RowData> keySerializer;
public final GeneratedRecordEqualiser generatedKeyEqualiser;
public final GeneratedHashFunction generatedKeyHashFunction;
public final TypeSerializer<RowData> recordSerializer;
public final KeyExtractor keyExtractor;
/** */
public | SequencedMultiSetStateContext |
java | apache__camel | components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/CXFGreeterEnrichTest.java | {
"start": 1163,
"end": 1885
} | class ____ extends AbstractCXFGreeterRouterTest {
protected static Endpoint endpoint;
@AfterAll
public static void stopService() {
if (endpoint != null) {
endpoint.stop();
}
}
@BeforeAll
public static void startService() {
Object implementor = new GreeterImpl();
String address = "http://localhost:" + getPort1() + "/CXFGreeterEnrichTest/SoapContext/SoapPort";
endpoint = Endpoint.publish(address, implementor);
}
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/GreeterEnrichRouterContext.xml");
}
}
| CXFGreeterEnrichTest |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java | {
"start": 4591,
"end": 5206
} | class ____<T> {
private String url;
private Map<String, String> params;
private CompletionService<T> completionService;
private ServerMemberManager serverMemberManager;
ClusterJob(String url, Map<String, String> params, CompletionService<T> completionService,
ServerMemberManager serverMemberManager) {
this.url = url;
this.params = params;
this.completionService = completionService;
this.serverMemberManager = serverMemberManager;
}
| ClusterJob |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/introspect/MemberKey.java | {
"start": 130,
"end": 292
} | class ____ to be able to efficiently access class
* member functions ({@link Method}s and {@link Constructor}s)
* in {@link java.util.Map}s.
*/
public final | needed |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson/OAuth2AuthorizedClientMixin.java | {
"start": 1648,
"end": 1996
} | class ____ {
@JsonCreator
OAuth2AuthorizedClientMixin(@JsonProperty("clientRegistration") ClientRegistration clientRegistration,
@JsonProperty("principalName") String principalName,
@JsonProperty("accessToken") OAuth2AccessToken accessToken,
@JsonProperty("refreshToken") OAuth2RefreshToken refreshToken) {
}
}
| OAuth2AuthorizedClientMixin |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmJsonNullBehavior.java | {
"start": 671,
"end": 1675
} | enum ____ implements SqmTypedNode<Object> {
/**
* {@code null} values are removed.
*/
ABSENT,
/**
* {@code null} values are retained as JSON {@code null} literals.
*/
NULL;
@Override
public @Nullable SqmBindableType<Object> getNodeType() {
return null;
}
@Override
public NodeBuilder nodeBuilder() {
throw new UnsupportedOperationException();
}
@Override
public SqmJsonNullBehavior copy(SqmCopyContext context) {
return this;
}
@Override
public <X> X accept(SemanticQueryWalker<X> walker) {
//noinspection unchecked
return (X) (this == NULL ? JsonNullBehavior.NULL : JsonNullBehavior.ABSENT);
}
@Override
public void appendHqlString(StringBuilder hql, SqmRenderContext context) {
if ( this == NULL ) {
hql.append( " null on null" );
}
else {
hql.append( " absent on null" );
}
}
@Override
public boolean isCompatible(Object object) {
return this == object;
}
@Override
public int cacheHashCode() {
return hashCode();
}
}
| SqmJsonNullBehavior |
java | square__retrofit | samples/src/main/java/com/example/retrofit/JsonAndXmlConverters.java | {
"start": 1909,
"end": 3454
} | class ____ extends Converter.Factory {
private final Converter.Factory jsonFactory;
private final Converter.Factory xmlFactory;
QualifiedTypeConverterFactory(Converter.Factory jsonFactory, Converter.Factory xmlFactory) {
this.jsonFactory = jsonFactory;
this.xmlFactory = xmlFactory;
}
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
for (Annotation annotation : annotations) {
if (annotation instanceof Json) {
return jsonFactory.responseBodyConverter(type, annotations, retrofit);
}
if (annotation instanceof Xml) {
return xmlFactory.responseBodyConverter(type, annotations, retrofit);
}
}
return null;
}
@Override
public @Nullable Converter<?, RequestBody> requestBodyConverter(
Type type,
Annotation[] parameterAnnotations,
Annotation[] methodAnnotations,
Retrofit retrofit) {
for (Annotation annotation : parameterAnnotations) {
if (annotation instanceof Json) {
return jsonFactory.requestBodyConverter(
type, parameterAnnotations, methodAnnotations, retrofit);
}
if (annotation instanceof Xml) {
return xmlFactory.requestBodyConverter(
type, parameterAnnotations, methodAnnotations, retrofit);
}
}
return null;
}
}
@Default(value = DefaultType.FIELD)
static | QualifiedTypeConverterFactory |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/common/http/SizeLimitInputStream.java | {
"start": 782,
"end": 2310
} | class ____ extends FilterInputStream {
private final int maxByteSize;
private final AtomicInteger byteCounter = new AtomicInteger(0);
/**
* Creates a new input stream, that throws an exception when a certain number of bytes is read
* @param maxByteSize The maximum data to read, before throwing an exception
* @param in The underlying inputstream containing the data
*/
SizeLimitInputStream(ByteSizeValue maxByteSize, InputStream in) {
super(in);
this.maxByteSize = maxByteSize.bytesAsInt();
}
@Override
public int read() throws IOException {
byteCounter.incrementAndGet();
checkMaximumLengthReached();
return super.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
byteCounter.addAndGet(len);
checkMaximumLengthReached();
return super.read(b, off, len);
}
@Override
public synchronized void mark(int readlimit) {
throw new UnsupportedOperationException("mark not supported");
}
@Override
public synchronized void reset() throws IOException {
throw new IOException("reset not supported");
}
@Override
public boolean markSupported() {
return false;
}
private void checkMaximumLengthReached() throws IOException {
if (byteCounter.get() > maxByteSize) {
throw new IOException("Maximum limit of [" + maxByteSize + "] bytes reached");
}
}
}
| SizeLimitInputStream |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/client/BaseTestHttpFSWith.java | {
"start": 44465,
"end": 61363
} | enum ____ {
GET, OPEN, CREATE, APPEND, TRUNCATE, CONCAT, RENAME, DELETE, LIST_STATUS,
WORKING_DIRECTORY, MKDIRS, SET_TIMES, SET_PERMISSION, SET_OWNER,
SET_REPLICATION, CHECKSUM, CONTENT_SUMMARY, QUOTA_USAGE, FILEACLS, DIRACLS,
SET_XATTR, GET_XATTRS, REMOVE_XATTR, LIST_XATTRS, ENCRYPTION,
LIST_STATUS_BATCH, GETTRASHROOT, STORAGEPOLICY, ERASURE_CODING,
CREATE_SNAPSHOT, RENAME_SNAPSHOT, DELETE_SNAPSHOT,
ALLOW_SNAPSHOT, DISALLOW_SNAPSHOT, DISALLOW_SNAPSHOT_EXCEPTION,
FILE_STATUS_ATTR, GET_SNAPSHOT_DIFF, GET_SNAPSHOTTABLE_DIRECTORY_LIST,
GET_SNAPSHOT_LIST, GET_SERVERDEFAULTS, CHECKACCESS, SETECPOLICY,
SATISFYSTORAGEPOLICY, GET_SNAPSHOT_DIFF_LISTING, GETFILEBLOCKLOCATIONS,
GETFILELINKSTATUS, GETSTATUS, GETECPOLICIES, GETECCODECS, GETTRASHROOTS
}
@SuppressWarnings("methodlength")
private void operation(Operation op) throws Exception {
switch (op) {
case GET:
testGet();
break;
case OPEN:
testOpen();
break;
case CREATE:
testCreate();
break;
case APPEND:
testAppend();
break;
case TRUNCATE:
testTruncate();
break;
case CONCAT:
testConcat();
break;
case RENAME:
testRename();
break;
case DELETE:
testDelete();
break;
case LIST_STATUS:
testListStatus();
testListSymLinkStatus();
break;
case WORKING_DIRECTORY:
testWorkingdirectory();
break;
case MKDIRS:
testMkdirs();
break;
case SET_TIMES:
testSetTimes();
break;
case SET_PERMISSION:
testSetPermission();
break;
case SET_OWNER:
testSetOwner();
break;
case SET_REPLICATION:
testSetReplication();
break;
case CHECKSUM:
testChecksum();
break;
case CONTENT_SUMMARY:
testContentSummary();
break;
case QUOTA_USAGE:
testQuotaUsage();
break;
case FILEACLS:
testFileAclsCustomizedUserAndGroupNames();
testFileAcls();
break;
case DIRACLS:
testDirAcls();
break;
case SET_XATTR:
testSetXAttr();
break;
case REMOVE_XATTR:
testRemoveXAttr();
break;
case GET_XATTRS:
testGetXAttrs();
break;
case LIST_XATTRS:
testListXAttrs();
break;
case ENCRYPTION:
testEncryption();
break;
case LIST_STATUS_BATCH:
testListStatusBatch();
break;
case GETTRASHROOT:
testTrashRoot();
break;
case STORAGEPOLICY:
testStoragePolicy();
break;
case ERASURE_CODING:
testErasureCoding();
break;
case CREATE_SNAPSHOT:
testCreateSnapshot();
break;
case RENAME_SNAPSHOT:
testRenameSnapshot();
break;
case DELETE_SNAPSHOT:
testDeleteSnapshot();
break;
case ALLOW_SNAPSHOT:
testAllowSnapshot();
break;
case DISALLOW_SNAPSHOT:
testDisallowSnapshot();
break;
case DISALLOW_SNAPSHOT_EXCEPTION:
testDisallowSnapshotException();
break;
case FILE_STATUS_ATTR:
testFileStatusAttr();
break;
case GET_SNAPSHOT_DIFF:
testGetSnapshotDiff();
testGetSnapshotDiffIllegalParam();
break;
case GET_SNAPSHOTTABLE_DIRECTORY_LIST:
testGetSnapshottableDirListing();
break;
case GET_SNAPSHOT_LIST:
testGetSnapshotListing();
break;
case GET_SERVERDEFAULTS:
testGetServerDefaults();
break;
case CHECKACCESS:
testAccess();
break;
case SETECPOLICY:
testErasureCodingPolicy();
break;
case SATISFYSTORAGEPOLICY:
testStoragePolicySatisfier();
break;
case GET_SNAPSHOT_DIFF_LISTING:
testGetSnapshotDiffListing();
break;
case GETFILEBLOCKLOCATIONS:
testGetFileBlockLocations();
break;
case GETFILELINKSTATUS:
testGetFileLinkStatus();
break;
case GETSTATUS:
testGetStatus();
break;
case GETECPOLICIES:
testGetAllEEPolicies();
break;
case GETECCODECS:
testGetECCodecs();
break;
case GETTRASHROOTS:
testGetTrashRoots();
break;
}
}
public static Collection operations() {
Object[][] ops = new Object[Operation.values().length][];
for (int i = 0; i < Operation.values().length; i++) {
ops[i] = new Object[]{Operation.values()[i]};
}
//To test one or a subset of operations do:
//return Arrays.asList(new Object[][]{ new Object[]{Operation.APPEND}});
return Arrays.asList(ops);
}
private Operation operation;
public void initBaseTestHttpFSWith(Operation pOperation) {
this.operation = pOperation;
}
@MethodSource("operations")
@ParameterizedTest
@TestDir
@TestJetty
@TestHdfs
public void testOperation(Operation pOperation) throws Exception {
initBaseTestHttpFSWith(pOperation);
createHttpFSServer();
operation(operation);
}
@MethodSource("operations")
@ParameterizedTest
@TestDir
@TestJetty
@TestHdfs
public void testOperationDoAs(Operation pOperation) throws Exception {
initBaseTestHttpFSWith(pOperation);
createHttpFSServer();
UserGroupInformation ugi = UserGroupInformation.createProxyUser(HadoopUsersConfTestHelper.getHadoopUsers()[0],
UserGroupInformation.getCurrentUser());
ugi.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
operation(operation);
return null;
}
});
}
private void testCreateSnapshot(String snapshotName) throws Exception {
if (!this.isLocalFS()) {
Path snapshottablePath = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(snapshottablePath);
//Now get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
if (snapshotName == null) {
fs.createSnapshot(snapshottablePath);
} else {
fs.createSnapshot(snapshottablePath, snapshotName);
}
Path snapshotsDir = new Path("/tmp/tmp-snap-test/.snapshot");
FileStatus[] snapshotItems = fs.listStatus(snapshotsDir);
assertTrue(snapshotItems.length == 1,
"Should have exactly one snapshot.");
String resultingSnapName = snapshotItems[0].getPath().getName();
if (snapshotName == null) {
assertTrue(Pattern.matches("(s)(\\d{8})(-)(\\d{6})(\\.)(\\d{3})",
resultingSnapName), "Snapshot auto generated name not matching pattern");
} else {
assertTrue(snapshotName.equals(resultingSnapName),
"Snapshot name is not same as passed name.");
}
cleanSnapshotTests(snapshottablePath, resultingSnapName);
}
}
private void testCreateSnapshot() throws Exception {
testCreateSnapshot(null);
testCreateSnapshot("snap-with-name");
}
private void createSnapshotTestsPreconditions(Path snapshottablePath,
Boolean allowSnapshot) throws Exception {
//Needed to get a DistributedFileSystem instance, in order to
//call allowSnapshot on the newly created directory
DistributedFileSystem distributedFs = (DistributedFileSystem)
FileSystem.get(snapshottablePath.toUri(), this.getProxiedFSConf());
distributedFs.mkdirs(snapshottablePath);
if (allowSnapshot) {
distributedFs.allowSnapshot(snapshottablePath);
}
Path subdirPath = new Path("/tmp/tmp-snap-test/subdir");
distributedFs.mkdirs(subdirPath);
}
private void createSnapshotTestsPreconditions(Path snapshottablePath)
throws Exception {
// Allow snapshot by default for snapshot test
createSnapshotTestsPreconditions(snapshottablePath, true);
}
private void cleanSnapshotTests(Path snapshottablePath,
String resultingSnapName) throws Exception {
DistributedFileSystem distributedFs = (DistributedFileSystem)
FileSystem.get(snapshottablePath.toUri(), this.getProxiedFSConf());
distributedFs.deleteSnapshot(snapshottablePath, resultingSnapName);
distributedFs.delete(snapshottablePath, true);
}
private void testRenameSnapshot() throws Exception {
if (!this.isLocalFS()) {
Path snapshottablePath = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(snapshottablePath);
//Now get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
fs.createSnapshot(snapshottablePath, "snap-to-rename");
fs.renameSnapshot(snapshottablePath, "snap-to-rename",
"snap-new-name");
Path snapshotsDir = new Path("/tmp/tmp-snap-test/.snapshot");
FileStatus[] snapshotItems = fs.listStatus(snapshotsDir);
assertTrue(snapshotItems.length == 1,
"Should have exactly one snapshot.");
String resultingSnapName = snapshotItems[0].getPath().getName();
assertTrue("snap-new-name".equals(resultingSnapName),
"Snapshot name is not same as passed name.");
cleanSnapshotTests(snapshottablePath, resultingSnapName);
}
}
private void testDeleteSnapshot() throws Exception {
if (!this.isLocalFS()) {
Path snapshottablePath = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(snapshottablePath);
//Now get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
fs.createSnapshot(snapshottablePath, "snap-to-delete");
Path snapshotsDir = new Path("/tmp/tmp-snap-test/.snapshot");
FileStatus[] snapshotItems = fs.listStatus(snapshotsDir);
assertTrue(snapshotItems.length == 1,
"Should have exactly one snapshot.");
fs.deleteSnapshot(snapshottablePath, "snap-to-delete");
snapshotItems = fs.listStatus(snapshotsDir);
assertTrue(snapshotItems.length == 0,
"There should be no snapshot anymore.");
fs.delete(snapshottablePath, true);
}
}
private void testAllowSnapshot() throws Exception {
if (!this.isLocalFS()) {
// Create a directory with snapshot disallowed
Path path = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(path, false);
// Get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
// Check FileStatus
assertFalse(fs.getFileStatus(path).isSnapshotEnabled(),
"Snapshot should be disallowed by default");
// Allow snapshot
if (fs instanceof HttpFSFileSystem) {
HttpFSFileSystem httpFS = (HttpFSFileSystem) fs;
httpFS.allowSnapshot(path);
} else if (fs instanceof WebHdfsFileSystem) {
WebHdfsFileSystem webHdfsFileSystem = (WebHdfsFileSystem) fs;
webHdfsFileSystem.allowSnapshot(path);
} else {
fail(fs.getClass().getSimpleName() +
" doesn't support allowSnapshot");
}
// Check FileStatus
assertTrue(fs.getFileStatus(path).isSnapshotEnabled(),
"allowSnapshot failed");
// Cleanup
fs.delete(path, true);
}
}
private void testDisallowSnapshot() throws Exception {
if (!this.isLocalFS()) {
// Create a directory with snapshot allowed
Path path = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(path);
// Get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
// Check FileStatus
assertTrue(fs.getFileStatus(path).isSnapshotEnabled(),
"Snapshot should be allowed by DFS");
// Disallow snapshot
if (fs instanceof HttpFSFileSystem) {
HttpFSFileSystem httpFS = (HttpFSFileSystem) fs;
httpFS.disallowSnapshot(path);
} else if (fs instanceof WebHdfsFileSystem) {
WebHdfsFileSystem webHdfsFileSystem = (WebHdfsFileSystem) fs;
webHdfsFileSystem.disallowSnapshot(path);
} else {
fail(fs.getClass().getSimpleName() +
" doesn't support disallowSnapshot");
}
// Check FileStatus
assertFalse(fs.getFileStatus(path).isSnapshotEnabled(),
"disallowSnapshot failed");
// Cleanup
fs.delete(path, true);
}
}
private void testDisallowSnapshotException() throws Exception {
if (!this.isLocalFS()) {
// Create a directory with snapshot allowed
Path path = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(path);
// Get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
// Check FileStatus
assertTrue(fs.getFileStatus(path).isSnapshotEnabled(),
"Snapshot should be allowed by DFS");
// Create some snapshots
fs.createSnapshot(path, "snap-01");
fs.createSnapshot(path, "snap-02");
// Disallow snapshot
boolean disallowSuccess = false;
if (fs instanceof HttpFSFileSystem) {
HttpFSFileSystem httpFS = (HttpFSFileSystem) fs;
try {
httpFS.disallowSnapshot(path);
disallowSuccess = true;
} catch (SnapshotException e) {
// Expect SnapshotException
}
} else if (fs instanceof WebHdfsFileSystem) {
WebHdfsFileSystem webHdfsFileSystem = (WebHdfsFileSystem) fs;
try {
webHdfsFileSystem.disallowSnapshot(path);
disallowSuccess = true;
} catch (SnapshotException e) {
// Expect SnapshotException
}
} else {
fail(fs.getClass().getSimpleName() +
" doesn't support disallowSnapshot");
}
if (disallowSuccess) {
fail("disallowSnapshot doesn't throw SnapshotException when "
+ "disallowing snapshot on a directory with at least one snapshot");
}
// Check FileStatus, should still be enabled since
// disallow snapshot should fail
assertTrue(fs.getFileStatus(path).isSnapshotEnabled(),
"disallowSnapshot should not have succeeded");
// Cleanup
fs.deleteSnapshot(path, "snap-02");
fs.deleteSnapshot(path, "snap-01");
fs.delete(path, true);
}
}
private void testGetSnapshotDiff() throws Exception {
if (!this.isLocalFS()) {
// Create a directory with snapshot allowed
Path path = new Path("/tmp/tmp-snap-test");
createSnapshotTestsPreconditions(path);
// Get the FileSystem instance that's being tested
FileSystem fs = this.getHttpFSFileSystem();
// Check FileStatus
assertTrue(fs.getFileStatus(path).isSnapshotEnabled());
// Create a file and take a snapshot
Path file1 = new Path(path, "file1");
testCreate(file1, false);
fs.createSnapshot(path, "snap1");
// Create another file and take a snapshot
Path file2 = new Path(path, "file2");
testCreate(file2, false);
fs.createSnapshot(path, "snap2");
try {
// Get snapshot diff
SnapshotDiffReport diffReport = null;
if (fs instanceof HttpFSFileSystem) {
HttpFSFileSystem httpFS = (HttpFSFileSystem) fs;
diffReport = httpFS.getSnapshotDiffReport(path, "snap1", "snap2");
} else if (fs instanceof WebHdfsFileSystem) {
WebHdfsFileSystem webHdfsFileSystem = (WebHdfsFileSystem) fs;
diffReport = webHdfsFileSystem.getSnapshotDiffReport(path, "snap1", "snap2");
} else {
fail(fs.getClass().getSimpleName() + " doesn't support getSnapshotDiff");
}
// Verify result with DFS
DistributedFileSystem dfs =
(DistributedFileSystem) FileSystem.get(path.toUri(), this.getProxiedFSConf());
SnapshotDiffReport dfsDiffReport = dfs.getSnapshotDiffReport(path, "snap1", "snap2");
assertEquals(diffReport.toString(), dfsDiffReport.toString());
} finally {
// Cleanup
fs.deleteSnapshot(path, "snap2");
fs.deleteSnapshot(path, "snap1");
fs.delete(path, true);
}
}
}
private void testGetSnapshotDiffIllegalParamCase(FileSystem fs, Path path,
String oldsnapshotname, String snapshotname) throws IOException {
try {
if (fs instanceof HttpFSFileSystem) {
HttpFSFileSystem httpFS = (HttpFSFileSystem) fs;
httpFS.getSnapshotDiffReport(path, oldsnapshotname, snapshotname);
} else if (fs instanceof WebHdfsFileSystem) {
WebHdfsFileSystem webHdfsFileSystem = (WebHdfsFileSystem) fs;
webHdfsFileSystem.getSnapshotDiffReport(path, oldsnapshotname,
snapshotname);
} else {
fail(fs.getClass().getSimpleName() +
" doesn't support getSnapshotDiff");
}
} catch (SnapshotException|IllegalArgumentException|RemoteException e) {
// Expect SnapshotException, IllegalArgumentException
// or RemoteException(IllegalArgumentException)
if (e instanceof RemoteException) {
// Check RemoteException | Operation |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FactoryUtil.java | {
"start": 62015,
"end": 62975
} | class ____ implements CatalogStoreFactory.Context {
private Map<String, String> options;
private ReadableConfig configuration;
private ClassLoader classLoader;
public DefaultCatalogStoreContext(
Map<String, String> options,
ReadableConfig configuration,
ClassLoader classLoader) {
this.options = options;
this.configuration = configuration;
this.classLoader = classLoader;
}
@Override
public Map<String, String> getOptions() {
return options;
}
@Override
public ReadableConfig getConfiguration() {
return configuration;
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
}
/** Default implementation of {@link ModuleFactory.Context}. */
@Internal
public static | DefaultCatalogStoreContext |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/json/async/AsyncUnicodeHandlingTest.java | {
"start": 437,
"end": 3515
} | class ____ extends AsyncTestBase
{
private final JsonFactory JSON_F = new JsonFactory();
@Test
void shortUnicodeWithSurrogates() throws IOException
{
JsonFactory f = JSON_F;
// first, no buffer boundaries
_testUnicodeWithSurrogates(f, 28, 99);
_testUnicodeWithSurrogates(f, 53, 99);
// then small chunks
_testUnicodeWithSurrogates(f, 28, 3);
_testUnicodeWithSurrogates(f, 53, 5);
// and finally one-by-one
_testUnicodeWithSurrogates(f, 28, 1);
_testUnicodeWithSurrogates(f, 53, 1);
}
@Test
void longUnicodeWithSurrogates() throws IOException
{
JsonFactory f = JSON_F;
_testUnicodeWithSurrogates(f, 230, Integer.MAX_VALUE);
_testUnicodeWithSurrogates(f, 700, Integer.MAX_VALUE);
_testUnicodeWithSurrogates(f, 9600, Integer.MAX_VALUE);
_testUnicodeWithSurrogates(f, 230, 3);
_testUnicodeWithSurrogates(f, 700, 3);
_testUnicodeWithSurrogates(f, 9600, 3);
_testUnicodeWithSurrogates(f, 230, 1);
_testUnicodeWithSurrogates(f, 700, 1);
_testUnicodeWithSurrogates(f, 9600, 1);
}
private void _testUnicodeWithSurrogates(JsonFactory f,
int length, int readSize) throws IOException
{
final String SURROGATE_CHARS = "\ud834\udd1e";
StringBuilder sb = new StringBuilder(length+200);
while (sb.length() < length) {
sb.append(SURROGATE_CHARS);
sb.append(sb.length());
if ((sb.length() & 1) == 1) {
sb.append("\u00A3");
} else {
sb.append("\u3800");
}
}
final String TEXT = sb.toString();
final String quoted = q(TEXT);
byte[] data = _jsonDoc(quoted);
AsyncReaderWrapper r = asyncForBytes(f, readSize, data, 0);
assertToken(JsonToken.VALUE_STRING, r.nextToken());
assertEquals(TEXT, r.currentText());
assertNull(r.nextToken());
r.close();
// Then same but skipping
r = asyncForBytes(f, readSize, data, 0);
assertToken(JsonToken.VALUE_STRING, r.nextToken());
assertNull(r.nextToken());
r.close();
// Also, verify that it works as field name
data = _jsonDoc("{"+quoted+":true}");
r = asyncForBytes(f, readSize, data, 0);
assertToken(JsonToken.START_OBJECT, r.nextToken());
assertToken(JsonToken.PROPERTY_NAME, r.nextToken());
assertEquals(TEXT, r.currentName());
assertToken(JsonToken.VALUE_TRUE, r.nextToken());
assertToken(JsonToken.END_OBJECT, r.nextToken());
assertNull(r.nextToken());
r.close();
// and skipping
r = asyncForBytes(f, readSize, data, 0);
assertToken(JsonToken.START_OBJECT, r.nextToken());
assertToken(JsonToken.PROPERTY_NAME, r.nextToken());
assertToken(JsonToken.VALUE_TRUE, r.nextToken());
assertToken(JsonToken.END_OBJECT, r.nextToken());
r.close();
}
}
| AsyncUnicodeHandlingTest |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/jdk/EnumSetSerializer.java | {
"start": 2564,
"end": 2961
} | enum ____ that set knows)
for (Enum<?> en : value) {
if (enumSer == null) {
// 12-Jan-2010, tatu: Since enums cannot be polymorphic, let's
// not bother with typed serializer variant here
enumSer = _findAndAddDynamic(ctxt, en.getDeclaringClass());
}
enumSer.serialize(en, gen, ctxt);
}
}
}
| class |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3747PrefixedPathExpressionTest.java | {
"start": 1271,
"end": 1997
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testitMNG3747() throws Exception {
File testDir = extractResources("/mng-3747");
Verifier verifier = newVerifier(testDir.getCanonicalPath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/config.properties");
assertEquals(
"path is: " + new File(testDir, "relative").getCanonicalPath() + "/somepath",
props.getProperty("stringParam"));
}
}
| MavenITmng3747PrefixedPathExpressionTest |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/user/RestProfileHasPrivilegesAction.java | {
"start": 1382,
"end": 2877
} | class ____ extends SecurityBaseRestHandler {
public RestProfileHasPrivilegesAction(Settings settings, XPackLicenseState licenseState) {
super(settings, licenseState);
}
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_security/profile/_has_privileges"), new Route(POST, "/_security/profile/_has_privileges"));
}
@Override
public String getName() {
return "security_profile_has_privileges_action";
}
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
try (XContentParser parser = restRequest.contentOrSourceParamParser()) {
ProfileHasPrivilegesRequest request = ProfileHasPrivilegesRequest.PARSER.parse(parser, null);
final HttpChannel httpChannel = restRequest.getHttpChannel();
return channel -> new RestCancellableNodeClient(client, httpChannel).execute(
ProfileHasPrivilegesAction.INSTANCE,
request,
new RestToXContentListener<>(channel)
);
}
}
@Override
protected Exception innerCheckFeatureAvailable(RestRequest request) {
if (Security.USER_PROFILE_COLLABORATION_FEATURE.check(licenseState)) {
return null;
} else {
return LicenseUtils.newComplianceException(Security.USER_PROFILE_COLLABORATION_FEATURE.getName());
}
}
}
| RestProfileHasPrivilegesAction |
java | google__truth | core/src/test/java/com/google/common/truth/extension/FakeHrDatabaseTest.java | {
"start": 959,
"end": 2455
} | class ____ {
// Note: not real employee IDs :-)
private static final Employee KURT =
Employee.create("kak", 37802, "Kurt Alfred Kluever", Location.NYC, /* isCeo= */ false);
private static final Employee SUNDAR =
Employee.create("sundar", 5243, "Sundar Pichai", Location.MTV, /* isCeo= */ true);
// Notice that we static import two different assertThat methods.
// These assertions use the EmployeeSubject.assertThat(Employee) overload and the
// EmployeeSubject-specific methods.
@Test
public void relocatePresent() {
FakeHrDatabase db = new FakeHrDatabase();
db.put(KURT);
db.relocate(KURT.id(), Location.MTV);
Employee movedKurt = db.get(KURT.id());
assertThat(movedKurt).hasLocation(Location.MTV);
assertThat(movedKurt).hasUsername("kak");
}
// These assertions use the EmployeeSubject.assertThat(Employee) overload but the assertion
// methods inherited from Subject.
@Test
public void getPresent() {
FakeHrDatabase db = new FakeHrDatabase();
db.put(KURT);
assertThat(db.get(KURT.id())).isEqualTo(KURT);
}
@Test
public void getAbsent() {
FakeHrDatabase db = new FakeHrDatabase();
db.put(KURT);
assertThat(db.get(SUNDAR.id())).isNull();
}
// These assertions use Truth.assertThat() overloads
@Test
public void getByLocation() {
FakeHrDatabase db = new FakeHrDatabase();
db.put(KURT);
assertThat(db.getByLocation(Location.NYC)).containsExactly(KURT);
}
}
| FakeHrDatabaseTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/RelationalValueSource.java | {
"start": 626,
"end": 1043
} | enum ____ {
COLUMN( ColumnSource.class ),
DERIVED( DerivedValueSource.class );
private final Class<? extends RelationalValueSource> specificContractClass;
Nature(Class<? extends RelationalValueSource> specificContractClass) {
this.specificContractClass = specificContractClass;
}
public Class<? extends RelationalValueSource> getSpecificContractClass() {
return specificContractClass;
}
}
}
| Nature |
java | playframework__playframework | web/play-filters-helpers/src/main/java/play/filters/components/SecurityHeadersComponents.java | {
"start": 430,
"end": 760
} | interface ____ extends ConfigurationComponents {
default SecurityHeadersConfig securityHeadersConfig() {
return SecurityHeadersConfig.fromConfiguration(configuration());
}
default SecurityHeadersFilter securityHeadersFilter() {
return new SecurityHeadersFilter(securityHeadersConfig());
}
}
| SecurityHeadersComponents |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/validation/DiagnosticMessageGenerator.java | {
"start": 3381,
"end": 3507
} | class ____ {
/** Injectable factory for {@code DiagnosticMessageGenerator}. */
public static final | DiagnosticMessageGenerator |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/basic/WrongInstanceInvokerTest.java | {
"start": 1476,
"end": 1594
} | class ____ {
public String hello(String param) {
return "foobar_" + param;
}
}
}
| MyService |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/SearchResult.java | {
"start": 1093,
"end": 1718
} | class ____ extends AbstractDTOBase {
// WARNING: these fields have case sensitive names,
// the field name MUST match the field name used by Salesforce
// DO NOT change these field names to camel case!!!
private Attributes attributes;
private String Id;
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
@JsonProperty("Id")
public String getId() {
return Id;
}
@JsonProperty("Id")
public void setId(String id) {
this.Id = id;
}
}
| SearchResult |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java | {
"start": 6495,
"end": 6543
} | class ____ bean definition.
*/
private static | and |
java | google__guice | core/src/com/google/inject/matcher/Matchers.java | {
"start": 6651,
"end": 7493
} | class ____ extends AbstractMatcher<Object> implements Serializable {
private final Object value;
public Only(Object value) {
this.value = checkNotNull(value, "value");
}
@Override
public boolean matches(Object other) {
return value.equals(other);
}
@Override
public boolean equals(Object other) {
return other instanceof Only && ((Only) other).value.equals(value);
}
@Override
public int hashCode() {
return 37 * value.hashCode();
}
@Override
public String toString() {
return "only(" + value + ")";
}
private static final long serialVersionUID = 0;
}
/** Returns a matcher which matches only the given object. */
public static Matcher<Object> identicalTo(final Object value) {
return new IdenticalTo(value);
}
private static | Only |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslAuthenticatorTest.java | {
"start": 131966,
"end": 133281
} | class ____ implements AuthenticateCallbackHandler {
static final String USERNAME = "TestClientCallbackHandler-user";
static final String PASSWORD = "TestClientCallbackHandler-password";
private volatile boolean configured;
@Override
public void configure(Map<String, ?> configs, String mechanism, List<AppConfigurationEntry> jaasConfigEntries) {
if (configured)
throw new IllegalStateException("Client callback handler configured twice");
configured = true;
}
@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
if (!configured)
throw new IllegalStateException("Client callback handler not configured");
for (Callback callback : callbacks) {
if (callback instanceof NameCallback)
((NameCallback) callback).setName(USERNAME);
else if (callback instanceof PasswordCallback)
((PasswordCallback) callback).setPassword(PASSWORD.toCharArray());
else
throw new UnsupportedCallbackException(callback);
}
}
@Override
public void close() {
}
}
public static | TestClientCallbackHandler |
java | mapstruct__mapstruct | integrationtest/src/test/resources/autoValueBuilderTest/src/main/java/org/mapstruct/itest/auto/value/Person.java | {
"start": 529,
"end": 749
} | class ____ {
public abstract Builder name(String name);
public abstract Builder age(int age);
public abstract Builder address(Address address);
public abstract Person build();
}
}
| Builder |
java | alibaba__nacos | test/core-test/src/test/java/com/alibaba/nacos/test/client/ConfigIntegrationV1ServerNonCompatibilityCoreITCase.java | {
"start": 2539,
"end": 6019
} | class ____ {
public static AtomicInteger increment = new AtomicInteger(100);
@LocalServerPort
private int port;
@BeforeAll
static void beforeClass() throws IOException {
ConfigCleanUtils.changeToNewTestNacosHome(
ConfigIntegrationV1ServerNonCompatibilityCoreITCase.class.getSimpleName());
}
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
}
@Test
void testTlsServer() throws Exception {
RpcClient client = RpcClientFactory.createClient("testTlsServer", ConnectionType.GRPC,
Collections.singletonMap("labelKey", "labelValue"), null);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
Connection connection = client.connectToServer(serverInfo);
assertNull(connection);
}
@Test
void testServerTlsTrustAll() throws Exception {
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustAll(true);
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC,
Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequest = new ConfigPublishRequest();
String content = UUID.randomUUID().toString();
configPublishRequest.setContent(content);
configPublishRequest.setGroup("test-group" + increment.getAndIncrement());
configPublishRequest.setDataId("test-data" + increment.getAndIncrement());
Response response = connectionTrustCa.request(configPublishRequest, TimeUnit.SECONDS.toMillis(3));
assertTrue(response.isSuccess());
connectionTrustCa.close();
}
@Test
void testServerTlsTrustCa() throws Exception {
RpcClient.ServerInfo serverInfo = new RpcClient.ServerInfo();
serverInfo.setServerIp("127.0.0.1");
serverInfo.setServerPort(port);
RpcClientTlsConfig tlsConfig = new RpcClientTlsConfig();
tlsConfig.setEnableTls(true);
tlsConfig.setTrustCollectionCertFile("test-ca-cert.pem");
RpcClient clientTrustCa = RpcClientFactory.createClient("testServerTlsTrustCa", ConnectionType.GRPC,
Collections.singletonMap("labelKey", "labelValue"), tlsConfig);
Connection connectionTrustCa = clientTrustCa.connectToServer(serverInfo);
ConfigPublishRequest configPublishRequestCa = new ConfigPublishRequest();
String contentCa = UUID.randomUUID().toString();
configPublishRequestCa.setContent(contentCa);
configPublishRequestCa.setGroup("test-group" + increment.getAndIncrement());
configPublishRequestCa.setDataId("test-data" + increment.getAndIncrement());
Response responseCa = connectionTrustCa.request(configPublishRequestCa, TimeUnit.SECONDS.toMillis(3));
assertTrue(responseCa.isSuccess());
connectionTrustCa.close();
}
}
| ConfigIntegrationV1ServerNonCompatibilityCoreITCase |
java | spring-projects__spring-security | buildSrc/src/test/resources/samples/integrationtest/withpropdeps/src/integration-test/java/sample/TheTest.java | {
"start": 96,
"end": 193
} | class ____ {
@Test
public void compilesAndRuns() {
HttpServletRequest request = null;
}
} | TheTest |
java | apache__thrift | lib/java/src/test/java/org/apache/thrift/server/ServerTestBase.java | {
"start": 17848,
"end": 19608
} | class ____ extends TTransportFactory {
public int count = 0;
private final Factory factory;
public CallCountingTransportFactory(Factory factory) {
this.factory = factory;
}
@Override
public TTransport getTransport(TTransport trans) throws TTransportException {
count++;
return factory.getTransport(trans);
}
}
@Test
public void testTransportFactory() throws Exception {
for (TProtocolFactory protoFactory : getProtocols()) {
TestHandler handler = new TestHandler();
ThriftTest.Processor<TestHandler> processor = new ThriftTest.Processor<>(handler);
final CallCountingTransportFactory factory =
new CallCountingTransportFactory(new TFramedTransport.Factory());
startServer(processor, protoFactory, factory);
assertEquals(0, factory.count);
TSocket socket = new TSocket(HOST, PORT);
socket.setTimeout(SOCKET_TIMEOUT);
TTransport transport = getClientTransport(socket);
open(transport);
TProtocol protocol = protoFactory.getProtocol(transport);
ThriftTest.Client testClient = new ThriftTest.Client(protocol);
assertEquals(0, testClient.testByte((byte) 0));
assertEquals(2, factory.count);
socket.close();
stopServer();
}
}
private void testException(ThriftTest.Client testClient) throws TException {
try {
testClient.testException("Xception");
assert false;
} catch (Xception e) {
assertEquals(e.message, "Xception");
assertEquals(e.errorCode, 1001);
}
try {
testClient.testException("TException");
assert false;
} catch (TException e) {
}
testClient.testException("no Exception");
}
public static | CallCountingTransportFactory |
java | quarkusio__quarkus | extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/grpc/GrpcTracingServerInterceptor.java | {
"start": 7321,
"end": 8410
} | class ____<ReqT, RespT> extends SimpleForwardingServerCall<ReqT, RespT> {
private final Context spanContext;
private final Scope scope;
private final GrpcRequest grpcRequest;
public TracingServerCall(
final ServerCall<ReqT, RespT> delegate,
final Context spanContext,
final Scope scope,
final GrpcRequest grpcRequest) {
super(delegate);
this.spanContext = spanContext;
this.scope = scope;
this.grpcRequest = grpcRequest;
}
@Override
public void close(final Status status, final Metadata trailers) {
try {
super.close(status, trailers);
} catch (Exception e) {
try (scope) {
instrumenter.end(spanContext, grpcRequest, null, e);
}
throw e;
}
try (scope) {
instrumenter.end(spanContext, grpcRequest, status, status.getCause());
}
}
}
}
| TracingServerCall |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/test/java/org/apache/hadoop/yarn/server/router/secure/TestSecureLogins.java | {
"start": 2404,
"end": 6634
} | class ____ extends AbstractSecureRouterTest {
private static final Logger LOG = LoggerFactory.getLogger(TestSecureLogins.class);
@Test
public void testHasRealm() throws Throwable {
assertNotNull(getRealm());
LOG.info("Router principal = {}", getPrincipalAndRealm(ROUTER_LOCALHOST));
}
@Test
public void testRouterSecureLogin() throws Exception {
startSecureRouter();
List<Service> services = this.getRouter().getServices();
assertNotNull(services);
assertEquals(3, services.size());
stopSecureRouter();
}
@Test
public void testRouterClientRMService() throws Exception {
// Start the Router in Secure Mode
startSecureRouter();
// Start RM and RouterClientRMService in Secure mode
setupSecureMockRM();
initRouterClientRMService();
// Test the simple rpc call of the Router in the Secure environment
RouterClientRMService routerClientRMService = this.getRouter().getClientRMProxyService();
GetClusterMetricsRequest metricsRequest = GetClusterMetricsRequest.newInstance();
GetClusterMetricsResponse metricsResponse =
routerClientRMService.getClusterMetrics(metricsRequest);
assertNotNull(metricsResponse);
YarnClusterMetrics clusterMetrics = metricsResponse.getClusterMetrics();
assertEquals(4, clusterMetrics.getNumNodeManagers());
assertEquals(0, clusterMetrics.getNumLostNodeManagers());
// Stop the Router in Secure Mode
stopSecureRouter();
}
@Test
public void testRouterRMAdminService() throws Exception {
// Start the Router in Secure Mode
startSecureRouter();
// Start RM and RouterClientRMService in Secure mode
setupSecureMockRM();
initRouterRMAdminService();
// Test the simple rpc call of the Router in the Secure environment
RouterRMAdminService routerRMAdminService = this.getRouter().getRmAdminProxyService();
RefreshNodesRequest refreshNodesRequest = RefreshNodesRequest.newInstance();
RefreshNodesResponse refreshNodesResponse =
routerRMAdminService.refreshNodes(refreshNodesRequest);
assertNotNull(refreshNodesResponse);
// Stop the Router in Secure Mode
stopSecureRouter();
}
public static String getPrincipalAndRealm(String principal) {
return principal + "@" + getRealm();
}
protected static String getRealm() {
return getKdc().getRealm();
}
private void initRouterClientRMService() throws Exception {
Router router = this.getRouter();
Map<SubClusterId, MockRM> mockRMs = getMockRMs();
RouterClientRMService rmService = router.getClientRMProxyService();
RouterClientRMService.RequestInterceptorChainWrapper wrapper = rmService.getInterceptorChain();
FederationClientInterceptor interceptor =
(FederationClientInterceptor) wrapper.getRootInterceptor();
FederationStateStoreFacade stateStoreFacade = interceptor.getFederationFacade();
FederationStateStore stateStore = stateStoreFacade.getStateStore();
FederationStateStoreTestUtil stateStoreUtil = new FederationStateStoreTestUtil(stateStore);
Map<SubClusterId, ApplicationClientProtocol> clientRMProxies = interceptor.getClientRMProxies();
if (MapUtils.isNotEmpty(mockRMs)) {
for (Map.Entry<SubClusterId, MockRM> entry : mockRMs.entrySet()) {
SubClusterId sc = entry.getKey();
MockRM mockRM = entry.getValue();
stateStoreUtil.registerSubCluster(sc);
if (clientRMProxies.containsKey(sc)) {
continue;
}
clientRMProxies.put(sc, mockRM.getClientRMService());
}
}
}
private void initRouterRMAdminService() throws Exception {
Router router = this.getRouter();
Map<SubClusterId, MockRM> mockRMs = getMockRMs();
SubClusterId sc = SubClusterId.newInstance(0);
MockRM mockRM = mockRMs.get(sc);
RouterRMAdminService routerRMAdminService = router.getRmAdminProxyService();
RouterRMAdminService.RequestInterceptorChainWrapper rmAdminChainWrapper =
routerRMAdminService.getInterceptorChain();
DefaultRMAdminRequestInterceptor rmInterceptor =
(DefaultRMAdminRequestInterceptor) rmAdminChainWrapper.getRootInterceptor();
rmInterceptor.setRMAdmin(mockRM.getAdminService());
}
}
| TestSecureLogins |
java | lettuce-io__lettuce-core | src/test/java/io/redis/examples/async/ListExample.java | {
"start": 370,
"end": 22157
} | class ____ {
// REMOVE_START
@Test
// REMOVE_END
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
// REMOVE_START
asyncCommands.del("bikes:repairs", "bikes:finished", "new_bikes", "new_bikes_string").toCompletableFuture().join();
// REMOVE_END
// STEP_START queue
CompletableFuture<Void> queue = asyncCommands.lpush("bikes:repairs", "bike:1").thenCompose(res1 -> {
System.out.println(res1); // >>> 1
// REMOVE_START
assertThat(res1).isEqualTo(1);
// REMOVE_END
return asyncCommands.lpush("bikes:repairs", "bike:2");
}).thenCompose(res2 -> {
System.out.println(res2); // >>> 2
// REMOVE_START
assertThat(res2).isEqualTo(2);
// REMOVE_END
return asyncCommands.rpop("bikes:repairs");
}).thenCompose(res3 -> {
System.out.println(res3); // >>> bike:1
// REMOVE_START
assertThat(res3).isEqualTo("bike:1");
// REMOVE_END
return asyncCommands.rpop("bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isEqualTo("bike:2");
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> bike:2
.toCompletableFuture();
// STEP_END
queue.join();
// STEP_START stack
CompletableFuture<Void> stack = asyncCommands.lpush("bikes:repairs", "bike:1").thenCompose(res4 -> {
System.out.println(res4); // >>> 1
// REMOVE_START
assertThat(res4).isEqualTo(1);
// REMOVE_END
return asyncCommands.lpush("bikes:repairs", "bike:2");
}).thenCompose(res5 -> {
System.out.println(res5); // >>> 2
// REMOVE_START
assertThat(res5).isEqualTo(2);
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
}).thenCompose(res6 -> {
System.out.println(res6); // >>> bike:2
// REMOVE_START
assertThat(res6).isEqualTo("bike:2");
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isEqualTo("bike:1");
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> bike:1
.toCompletableFuture();
// STEP_END
stack.join();
// STEP_START llen
CompletableFuture<Void> llen = asyncCommands.llen("bikes:repairs")
// REMOVE_START
.thenApply(res -> {
assertThat(res).isZero();
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> 0
.toCompletableFuture();
// STEP_END
llen.join();
// STEP_START lmove_lrange
CompletableFuture<Void> lmovelrange = asyncCommands.lpush("bikes:repairs", "bike:1").thenCompose(res7 -> {
System.out.println(res7); // >>> 1
// REMOVE_START
assertThat(res7).isEqualTo(1);
// REMOVE_END
return asyncCommands.lpush("bikes:repairs", "bike:2");
}).thenCompose(res8 -> {
System.out.println(res8); // >>> 2
// REMOVE_START
assertThat(res8).isEqualTo(2);
// REMOVE_END
return asyncCommands.lmove("bikes:repairs", "bikes:finished", LMoveArgs.Builder.leftLeft());
}).thenCompose(res9 -> {
System.out.println(res9); // >>> bike:2
// REMOVE_START
assertThat(res9).isEqualTo("bike:2");
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
}).thenCompose(res10 -> {
System.out.println(res10); // >>> [bike:1]
// REMOVE_START
assertThat(res10.toString()).isEqualTo("[bike:1]");
// REMOVE_END
return asyncCommands.lrange("bikes:finished", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString()).isEqualTo("[bike:2]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> [bike:2]
.toCompletableFuture();
// STEP_END
lmovelrange.join();
// REMOVE_START
asyncCommands.del("bikes:repairs").toCompletableFuture().join();
// REMOVE_END
// STEP_START lpush_rpush
CompletableFuture<Void> lpushrpush = asyncCommands.rpush("bikes:repairs", "bike:1").thenCompose(res11 -> {
System.out.println(res11); // >>> 1
// REMOVE_START
assertThat(res11).isEqualTo(1);
// REMOVE_END
return asyncCommands.rpush("bikes:repairs", "bike:2");
}).thenCompose(res12 -> {
System.out.println(res12); // >>> 2
// REMOVE_START
assertThat(res12).isEqualTo(2);
// REMOVE_END
return asyncCommands.lpush("bikes:repairs", "bike:important_bike");
}).thenCompose(res13 -> {
System.out.println(res13); // >>> 3
// REMOVE_START
assertThat(res13).isEqualTo(3);
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString()).isEqualTo("[bike:important_bike, bike:1, bike:2]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> [bike:important_bike, bike:1, bike:2]
.toCompletableFuture();
// STEP_END
lpushrpush.join();
// REMOVE_START
asyncCommands.del("bikes:repairs").toCompletableFuture().join();
// REMOVE_END
// STEP_START variadic
CompletableFuture<Void> variadic = asyncCommands.rpush("bikes:repairs", "bike:1", "bike:2", "bike:3")
.thenCompose(res14 -> {
System.out.println(res14); // >>> 3
// REMOVE_START
assertThat(res14).isEqualTo(3);
// REMOVE_END
return asyncCommands.lpush("bikes:repairs", "bike:important_bike", "bike:very_important_bike");
}).thenCompose(res15 -> {
System.out.println(res15); // >>> 5
// REMOVE_START
assertThat(res15).isEqualTo(5);
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString())
.isEqualTo("[bike:very_important_bike, bike:important_bike, bike:1, bike:2, bike:3]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> [bike:very_important_bike, bike:important_bike, bike:1, bike:2, bike:3]
.toCompletableFuture();
// STEP_END
variadic.join();
// REMOVE_START
asyncCommands.del("bikes:repairs").toCompletableFuture().join();
// REMOVE_END
// STEP_START lpop_rpop
CompletableFuture<Void> lpoprpop = asyncCommands.rpush("bikes:repairs", "bike:1", "bike:2", "bike:3")
.thenCompose(res16 -> {
System.out.println(res16); // >>> 3
// REMOVE_START
assertThat(res16).isEqualTo(3);
// REMOVE_END
return asyncCommands.rpop("bikes:repairs");
}).thenCompose(res17 -> {
System.out.println(res17); // >>> bike:3
// REMOVE_START
assertThat(res17).isEqualTo("bike:3");
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
}).thenCompose(res18 -> {
System.out.println(res18); // >>> bike:1
// REMOVE_START
assertThat(res18).isEqualTo("bike:1");
// REMOVE_END
return asyncCommands.rpop("bikes:repairs");
}).thenCompose(res19 -> {
System.out.println(res19); // >>> bike:2
// REMOVE_START
assertThat(res19).isEqualTo("bike:2");
// REMOVE_END
return asyncCommands.rpop("bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isNull();
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> null
.toCompletableFuture();
// STEP_END
lpoprpop.join();
// STEP_START ltrim
CompletableFuture<Void> ltrim = asyncCommands
.lpush("bikes:repairs", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5").thenCompose(res20 -> {
System.out.println(res20); // >>> 5
// REMOVE_START
assertThat(res20).isEqualTo(5);
// REMOVE_END
return asyncCommands.ltrim("bikes:repairs", 0, 2);
}).thenCompose(res21 -> {
System.out.println(res21); // >>> OK
// REMOVE_START
assertThat(res21).isEqualTo("OK");
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString()).isEqualTo("[bike:5, bike:4, bike:3]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> [bike:5, bike:4, bike:3]
.toCompletableFuture();
// STEP_END
ltrim.join();
// REMOVE_START
asyncCommands.del("bikes:repairs");
// REMOVE_END
// STEP_START ltrim_end_of_list
CompletableFuture<Void> ltrimendoflist = asyncCommands
.rpush("bikes:repairs", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5").thenCompose(res22 -> {
System.out.println(res22); // >>> 5
// REMOVE_START
assertThat(res22).isEqualTo(5);
// REMOVE_END
return asyncCommands.ltrim("bikes:repairs", -3, -1);
}).thenCompose(res23 -> {
System.out.println(res23); // >>> OK
// REMOVE_START
assertThat(res23).isEqualTo("OK");
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString()).isEqualTo("[bike:3, bike:4, bike:5]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println)
// >>> [bike:3, bike:4, bike:5]
.toCompletableFuture();
// STEP_END
ltrimendoflist.join();
// REMOVE_START
asyncCommands.del("bikes:repairs");
// REMOVE_END
// STEP_START brpop
CompletableFuture<Void> brpop = asyncCommands.rpush("bikes:repairs", "bike:1", "bike:2").thenCompose(res24 -> {
System.out.println(res24); // >>> 2
// REMOVE_START
assertThat(res24).isEqualTo(2);
// REMOVE_END
return asyncCommands.brpop(1, "bikes:repairs");
}).thenCompose(res25 -> {
System.out.println(res25);
// >>> KeyValue[bikes:repairs, bike:2]
// REMOVE_START
assertThat(res25.toString()).isEqualTo("KeyValue[bikes:repairs, bike:2]");
// REMOVE_END
return asyncCommands.brpop(1, "bikes:repairs");
}).thenCompose(res26 -> {
System.out.println(res26);
// >>> KeyValue[bikes:repairs, bike:1]
// REMOVE_START
assertThat(res26.toString()).isEqualTo("KeyValue[bikes:repairs, bike:1]");
// REMOVE_END
return asyncCommands.brpop(1, "bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isNull();
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> null
.toCompletableFuture();
// STEP_END
brpop.join();
// STEP_START rule_1
CompletableFuture<Void> rule1 = asyncCommands.del("new_bikes").thenCompose(res27 -> {
System.out.println(res27); // >>> 0
return asyncCommands.lpush("new_bikes", "bike:1", "bike:2", "bike:3");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isEqualTo(3);
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> 3
.toCompletableFuture();
// STEP_END
rule1.join();
// STEP_START rule_1.1
CompletableFuture<Void> rule11 = asyncCommands.set("new_bikes_string", "bike:1").thenCompose(res28 -> {
System.out.println(res28); // >>> OK
// REMOVE_START
assertThat(res28).isEqualTo("OK");
// REMOVE_END
return asyncCommands.type("new_bikes_string");
}).thenCompose(res29 -> {
System.out.println(res29); // >>> string
// REMOVE_START
assertThat(res29).isEqualTo("string");
// REMOVE_END
return asyncCommands.lpush("new_bikes_string", "bike:2", "bike:3");
}).handle((res, ex) -> {
if (ex == null) {
return res;
} else {
System.out.println(ex);
// >>> java.util.concurrent.CompletionException:
// >>> io.lettuce.core.RedisCommandExecutionException:
// >>> WRONGTYPE Operation against a key holding the wrong
// >>> kind of value
// REMOVE_START
assertThat(ex.toString()).isEqualTo(
"java.util.concurrent.CompletionException: io.lettuce.core.RedisCommandExecutionException: WRONGTYPE Operation against a key holding the wrong kind of value");
// REMOVE_END
return -1L;
}
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isEqualTo(-1L);
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> -1
.toCompletableFuture();
// STEP_END
rule11.join();
// REMOVE_START
asyncCommands.del("bikes:repairs");
// REMOVE_END
// STEP_START rule_2
CompletableFuture<Void> rule2 = asyncCommands.lpush("bikes:repairs", "bike:1", "bike:2", "bike:3")
.thenCompose(res30 -> {
System.out.println(res30); // >>> 3
// REMOVE_START
assertThat(res30).isEqualTo(3);
// REMOVE_END
return asyncCommands.exists("bikes:repairs");
}).thenCompose(res31 -> {
System.out.println(res31); // >>> 1
// REMOVE_START
assertThat(res31).isEqualTo(1);
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
}).thenCompose(res32 -> {
System.out.println(res32); // >>> bike:3
// REMOVE_START
assertThat(res32).isEqualTo("bike:3");
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
}).thenCompose(res33 -> {
System.out.println(res33); // >>> bike:2
// REMOVE_START
assertThat(res33).isEqualTo("bike:2");
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
}).thenCompose(res34 -> {
System.out.println(res34); // >>> bike:1
// REMOVE_START
assertThat(res34).isEqualTo("bike:1");
// REMOVE_END
return asyncCommands.exists("bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isZero();
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> 0
.toCompletableFuture();
// STEP_END
rule2.join();
// STEP_START rule_3
CompletableFuture<Void> rule3 = asyncCommands.del("bikes:repairs").thenCompose(res35 -> {
System.out.println(res35); // >>> 0
return asyncCommands.llen("bikes:repairs");
}).thenCompose(res36 -> {
System.out.println(res36); // >>> 0
// REMOVE_START
assertThat(res36).isZero();
// REMOVE_END
return asyncCommands.lpop("bikes:repairs");
})
// REMOVE_START
.thenApply(res -> {
assertThat(res).isNull();
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> null
.toCompletableFuture();
// STEP_END
rule3.join();
// STEP_START ltrim.1
CompletableFuture<Void> ltrim1 = asyncCommands
.lpush("bikes:repairs", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5").thenCompose(res37 -> {
System.out.println(res37); // >>> 5
// REMOVE_START
assertThat(res37).isEqualTo(5);
// REMOVE_END
return asyncCommands.ltrim("bikes:repairs", 0, 2);
}).thenCompose(res38 -> {
System.out.println(res38); // >>> OK
// REMOVE_START
assertThat(res38).isEqualTo("OK");
// REMOVE_END
return asyncCommands.lrange("bikes:repairs", 0, -1);
})
// REMOVE_START
.thenApply(res -> {
assertThat(res.toString()).isEqualTo("[bike:5, bike:4, bike:3]");
return res;
})
// REMOVE_END
.thenAccept(System.out::println) // >>> [bike:5, bike:4, bike:3]
.toCompletableFuture();
// STEP_END
ltrim1.join();
// HIDE_START
} finally {
redisClient.shutdown();
}
}
}
// HIDE_END
| ListExample |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/results/graph/AssemblerCreationState.java | {
"start": 361,
"end": 910
} | interface ____ {
default boolean isDynamicInstantiation() {
return false;
}
default boolean containsMultipleCollectionFetches() {
return true;
}
int acquireInitializerId();
Initializer<?> resolveInitializer(
NavigablePath navigablePath,
ModelPart fetchedModelPart,
Supplier<Initializer<?>> producer);
<P extends FetchParent> Initializer<?> resolveInitializer(
P resultGraphNode,
InitializerParent<?> parent,
InitializerProducer<P> producer);
SqlAstCreationContext getSqlAstCreationContext();
}
| AssemblerCreationState |
java | apache__flink | flink-python/src/main/java/org/apache/flink/streaming/api/functions/python/DataStreamPythonFunction.java | {
"start": 1195,
"end": 1807
} | class ____ implements PythonFunction {
private static final long serialVersionUID = 1L;
private final byte[] serializedPythonFunction;
private final PythonEnv pythonEnv;
public DataStreamPythonFunction(byte[] serializedPythonFunction, PythonEnv pythonEnv) {
this.serializedPythonFunction = serializedPythonFunction;
this.pythonEnv = pythonEnv;
}
@Override
public byte[] getSerializedPythonFunction() {
return this.serializedPythonFunction;
}
@Override
public PythonEnv getPythonEnv() {
return this.pythonEnv;
}
}
| DataStreamPythonFunction |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IronMQEndpointBuilderFactory.java | {
"start": 49157,
"end": 51331
} | interface ____ {
/**
* IronMQ (camel-ironmq)
* Send and receive messages to/from IronMQ an elastic and durable
* hosted message queue as a service.
*
* Category: cloud,messaging
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ironmq
*
* @return the dsl builder for the headers' name.
*/
default IronMQHeaderNameBuilder ironmq() {
return IronMQHeaderNameBuilder.INSTANCE;
}
/**
* IronMQ (camel-ironmq)
* Send and receive messages to/from IronMQ an elastic and durable
* hosted message queue as a service.
*
* Category: cloud,messaging
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ironmq
*
* Syntax: <code>ironmq:queueName</code>
*
* Path parameter: queueName (required)
* The name of the IronMQ queue
*
* @param path queueName
* @return the dsl builder
*/
default IronMQEndpointBuilder ironmq(String path) {
return IronMQEndpointBuilderFactory.endpointBuilder("ironmq", path);
}
/**
* IronMQ (camel-ironmq)
* Send and receive messages to/from IronMQ an elastic and durable
* hosted message queue as a service.
*
* Category: cloud,messaging
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ironmq
*
* Syntax: <code>ironmq:queueName</code>
*
* Path parameter: queueName (required)
* The name of the IronMQ queue
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path queueName
* @return the dsl builder
*/
default IronMQEndpointBuilder ironmq(String componentName, String path) {
return IronMQEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the IronMQ component.
*/
public static | IronMQBuilders |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/TermsQueryBuilder.java | {
"start": 2130,
"end": 17477
} | class ____ extends AbstractQueryBuilder<TermsQueryBuilder> {
public static final String NAME = "terms";
private final String fieldName;
private final BinaryValues values;
private final TermsLookup termsLookup;
private final Supplier<List<?>> supplier;
public TermsQueryBuilder(String fieldName, TermsLookup termsLookup) {
this(fieldName, null, termsLookup);
}
/**
* constructor used internally for serialization of both value / termslookup variants
*/
private TermsQueryBuilder(String fieldName, List<Object> values, TermsLookup termsLookup) {
if (Strings.isEmpty(fieldName)) {
throw new IllegalArgumentException("field name cannot be null.");
}
if (values == null && termsLookup == null) {
throw new IllegalArgumentException("No value or termsLookup specified for terms query");
}
if (values != null && termsLookup != null) {
throw new IllegalArgumentException("Both values and termsLookup specified for terms query");
}
this.fieldName = fieldName;
// already converted in {@link fromXContent}
this.values = values == null ? null : new BinaryValues(values, false);
this.termsLookup = termsLookup;
this.supplier = null;
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, String... values) {
this(fieldName, values != null ? Arrays.asList(values) : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, int... values) {
this(fieldName, values != null ? Arrays.stream(values).boxed().toList() : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, long... values) {
this(fieldName, values != null ? Arrays.stream(values).boxed().toList() : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, float... values) {
this(fieldName, values != null ? IntStream.range(0, values.length).mapToObj(i -> values[i]).toList() : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, double... values) {
this(fieldName, values != null ? Arrays.stream(values).boxed().toList() : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, Object... values) {
this(fieldName, values != null ? Arrays.asList(values) : null);
}
/**
* A filter for a field based on several terms matching on any of them.
*
* @param fieldName The field name
* @param values The terms
*/
public TermsQueryBuilder(String fieldName, Collection<?> values) {
if (Strings.isEmpty(fieldName)) {
throw new IllegalArgumentException("field name cannot be null.");
}
if (values == null) {
throw new IllegalArgumentException("No value specified for terms query");
}
this.fieldName = fieldName;
if (values instanceof BinaryValues binaryValues) {
this.values = binaryValues;
} else {
this.values = new BinaryValues(values, true);
}
this.termsLookup = null;
this.supplier = null;
}
private TermsQueryBuilder(String fieldName, Supplier<List<?>> supplier) {
this.fieldName = fieldName;
this.values = null;
this.termsLookup = null;
this.supplier = supplier;
}
/**
* Read from a stream.
*/
public TermsQueryBuilder(StreamInput in) throws IOException {
super(in);
this.fieldName = in.readString();
this.termsLookup = in.readOptionalWriteable(TermsLookup::new);
this.values = in.readOptionalWriteable(BinaryValues::new);
this.supplier = null;
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
if (supplier != null) {
throw new IllegalStateException("supplier must be null, can't serialize suppliers, missing a rewriteAndFetch?");
}
out.writeString(fieldName);
out.writeOptionalWriteable(termsLookup);
out.writeOptionalWriteable(values);
}
public String fieldName() {
return this.fieldName;
}
public BinaryValues getValues() {
return values;
}
/**
* get readable values
* only for {@link #toXContent} and tests, don't use this to construct a query.
* use {@link #getValues()} instead.
*/
public List<Object> values() {
List<Object> readableValues = new ArrayList<>();
for (Object value : values) {
readableValues.add(AbstractQueryBuilder.maybeConvertToString(value));
}
return readableValues;
}
public TermsLookup termsLookup() {
return this.termsLookup;
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
if (this.termsLookup != null) {
builder.startObject(fieldName);
termsLookup.toXContent(builder, params);
builder.endObject();
} else {
builder.field(fieldName, values());
}
printBoostAndQueryName(builder);
builder.endObject();
}
public static TermsQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
List<Object> values = null;
TermsLookup termsLookup = null;
String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if (fieldName != null) {
throw new ParsingException(
parser.getTokenLocation(),
"[" + TermsQueryBuilder.NAME + "] query does not support multiple fields"
);
}
fieldName = currentFieldName;
values = parseValues(parser);
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(
parser.getTokenLocation(),
"["
+ TermsQueryBuilder.NAME
+ "] query does not support more than one field. "
+ "Already got: ["
+ fieldName
+ "] but also found ["
+ currentFieldName
+ "]"
);
}
fieldName = currentFieldName;
termsLookup = TermsLookup.parseTermsLookup(parser);
} else if (token.isValue()) {
if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
boost = parser.floatValue();
} else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
queryName = parser.text();
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + TermsQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"
);
}
} else {
throw new ParsingException(
parser.getTokenLocation(),
"[" + TermsQueryBuilder.NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]"
);
}
}
if (fieldName == null) {
throw new ParsingException(
parser.getTokenLocation(),
"["
+ TermsQueryBuilder.NAME
+ "] query requires a field name, "
+ "followed by array of terms or a document lookup specification"
);
}
TermsQueryBuilder builder = new TermsQueryBuilder(fieldName, values, termsLookup).boost(boost).queryName(queryName);
return builder;
}
static List<Object> parseValues(XContentParser parser) throws IOException {
List<Object> values = new ArrayList<>();
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
Object value = maybeConvertToBytesRef(parser.objectBytes());
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No value specified for terms query");
}
values.add(value);
}
return values;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
protected Query doToQuery(SearchExecutionContext context) throws IOException {
if (termsLookup != null || supplier != null || values == null || values.isEmpty()) {
throw new UnsupportedOperationException("query must be rewritten first");
}
int maxTermsCount = context.getIndexSettings().getMaxTermsCount();
if (values.size() > maxTermsCount) {
throw new IllegalArgumentException(
"The number of terms ["
+ values.size()
+ "] used in the Terms Query request has exceeded "
+ "the allowed maximum of ["
+ maxTermsCount
+ "]. "
+ "This maximum can be set by changing the ["
+ IndexSettings.MAX_TERMS_COUNT_SETTING.getKey()
+ "] index level setting."
);
}
MappedFieldType fieldType = context.getFieldType(fieldName);
if (fieldType == null) {
throw new IllegalStateException("Rewrite first");
}
return fieldType.termsQuery(values, context);
}
private static void fetch(TermsLookup termsLookup, Client client, ActionListener<List<Object>> actionListener) {
GetRequest getRequest = new GetRequest(termsLookup.index(), termsLookup.id());
getRequest.preference("_local").routing(termsLookup.routing());
client.get(getRequest, actionListener.map(getResponse -> {
List<Object> terms = new ArrayList<>();
if (getResponse.isSourceEmpty() == false) { // extract terms only if the doc source exists
List<Object> extractedValues = XContentMapValues.extractRawValues(termsLookup.path(), getResponse.getSourceAsMap());
terms.addAll(extractedValues);
}
return terms;
}));
}
@Override
protected int doHashCode() {
return Objects.hash(fieldName, values, termsLookup, supplier);
}
@Override
protected boolean doEquals(TermsQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName)
&& Objects.equals(values, other.values)
&& Objects.equals(termsLookup, other.termsLookup)
&& Objects.equals(supplier, other.supplier);
}
@Override
protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws IOException {
if (supplier != null) {
return supplier.get() == null ? this : new TermsQueryBuilder(this.fieldName, supplier.get());
} else if (this.termsLookup != null) {
SetOnce<List<?>> supplier = new SetOnce<>();
queryRewriteContext.registerAsyncAction((client, listener) -> fetch(termsLookup, client, listener.map(list -> {
supplier.set(list);
return null;
})));
return new TermsQueryBuilder(this.fieldName, supplier::get);
}
if (values == null || values.isEmpty()) {
return new MatchNoneQueryBuilder("The \"" + getName() + "\" query was rewritten to a \"match_none\" query.");
}
return super.doRewrite(queryRewriteContext);
}
@Override
protected QueryBuilder doIndexMetadataRewrite(QueryRewriteContext context) {
MappedFieldType fieldType = context.getFieldType(this.fieldName);
if (fieldType == null) {
return new MatchNoneQueryBuilder("The \"" + getName() + "\" query is against a field that does not exist");
}
return maybeRewriteBasedOnConstantFields(fieldType, context);
}
@Override
protected QueryBuilder doCoordinatorRewrite(CoordinatorRewriteContext coordinatorRewriteContext) {
MappedFieldType fieldType = coordinatorRewriteContext.getFieldType(this.fieldName);
// we don't rewrite a null field type to `match_none` on the coordinator because the coordinator has access
// to only a subset of fields see {@link CoordinatorRewriteContext#getFieldType}
return maybeRewriteBasedOnConstantFields(fieldType, coordinatorRewriteContext);
}
private QueryBuilder maybeRewriteBasedOnConstantFields(@Nullable MappedFieldType fieldType, QueryRewriteContext context) {
if (fieldType instanceof ConstantFieldType constantFieldType) {
// This logic is correct for all field types, but by only applying it to constant
// fields we also have the guarantee that it doesn't perform I/O, which is important
// since rewrites might happen on a network thread.
Query query = constantFieldType.innerTermsQuery(values, context);
if (query instanceof MatchAllDocsQuery) {
return new MatchAllQueryBuilder();
} else if (query instanceof MatchNoDocsQuery) {
return new MatchNoneQueryBuilder("The \"" + getName() + "\" query was rewritten to a \"match_none\" query.");
} else {
assert false : "Constant fields must produce match-all or match-none queries, got " + query;
}
}
return this;
}
/**
* Store terms as a {@link BytesReference}.
* <p>
* When users send a query contain a lot of terms, A {@link BytesReference} can help
* gc and reduce the cost of {@link #doWriteTo}, which can be slow for lots of terms.
*/
@SuppressWarnings("rawtypes")
public static final | TermsQueryBuilder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java | {
"start": 3107,
"end": 4544
} | class ____ implements ResourceTracker {
private int heartBeatID;
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request) throws YarnException,
IOException {
RegisterNodeManagerResponse response = recordFactory
.newRecordInstance(RegisterNodeManagerResponse.class);
MasterKey masterKey = new MasterKeyPBImpl();
masterKey.setKeyId(123);
masterKey.setBytes(ByteBuffer.wrap(new byte[] { new Integer(123)
.byteValue() }));
response.setContainerTokenMasterKey(masterKey);
response.setNMTokenMasterKey(masterKey);
return response;
}
@Override
public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request)
throws YarnException, IOException {
NodeStatus nodeStatus = request.getNodeStatus();
LOG.info("Got heartbeat number " + heartBeatID);
nodeStatus.setResponseId(heartBeatID++);
NodeHeartbeatResponse nhResponse = YarnServerBuilderUtils
.newNodeHeartbeatResponse(heartBeatID, null, null,
null, null, null, 1000L);
return nhResponse;
}
@Override
public UnRegisterNodeManagerResponse unRegisterNodeManager(
UnRegisterNodeManagerRequest request) throws YarnException, IOException {
return recordFactory
.newRecordInstance(UnRegisterNodeManagerResponse.class);
}
}
}
| MockResourceTracker |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/ScalbConstantIntEvaluator.java | {
"start": 1124,
"end": 4311
} | class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ScalbConstantIntEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator d;
private final int scaleFactor;
private final DriverContext driverContext;
private Warnings warnings;
public ScalbConstantIntEvaluator(Source source, EvalOperator.ExpressionEvaluator d,
int scaleFactor, DriverContext driverContext) {
this.source = source;
this.d = d;
this.scaleFactor = scaleFactor;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (DoubleBlock dBlock = (DoubleBlock) d.eval(page)) {
DoubleVector dVector = dBlock.asVector();
if (dVector == null) {
return eval(page.getPositionCount(), dBlock);
}
return eval(page.getPositionCount(), dVector);
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += d.baseRamBytesUsed();
return baseRamBytesUsed;
}
public DoubleBlock eval(int positionCount, DoubleBlock dBlock) {
try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (dBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
double d = dBlock.getDouble(dBlock.getFirstValueIndex(p));
try {
result.appendDouble(Scalb.processConstantInt(d, this.scaleFactor));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
public DoubleBlock eval(int positionCount, DoubleVector dVector) {
try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
double d = dVector.getDouble(p);
try {
result.appendDouble(Scalb.processConstantInt(d, this.scaleFactor));
} catch (ArithmeticException e) {
warnings().registerException(e);
result.appendNull();
}
}
return result.build();
}
}
@Override
public String toString() {
return "ScalbConstantIntEvaluator[" + "d=" + d + ", scaleFactor=" + scaleFactor + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(d);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static | ScalbConstantIntEvaluator |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ChoiceWhenNoOutputTest.java | {
"start": 1129,
"end": 2549
} | class ____ extends ContextTestSupport {
@Test
public void testWhenNoOutput() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Bye World");
getMockEndpoint("mock:2").expectedBodiesReceived("Bye World");
template.sendBodyAndHeader("direct:start", "Hello World", "test", "1");
template.sendBodyAndHeader("direct:start", "Bye World", "test", "2");
try {
template.sendBodyAndHeader("direct:start", "Hi World", "test", "3");
fail();
} catch (Exception e) {
Assertions.assertInstanceOf(IllegalArgumentException.class, e.getCause());
assertEquals("Validation error!", e.getCause().getMessage());
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.choice()
.when(header("test").isEqualTo("1"))
.when(header("test").isEqualTo("2"))
.to("mock:2")
.otherwise()
.throwException(new IllegalArgumentException("Validation error!"))
.end()
.to("mock:result");
}
};
}
}
| ChoiceWhenNoOutputTest |
java | quarkusio__quarkus | extensions/smallrye-jwt/deployment/src/test/java/io/quarkus/jwt/test/GreetingResource.java | {
"start": 228,
"end": 406
} | class ____ {
@GET
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed({ "User" })
public String hello() {
return "Hello from Quarkus REST";
}
} | GreetingResource |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/web/EnableWebMvcAnnotationConfigTests.java | {
"start": 1521,
"end": 1772
} | class ____ extends AbstractBasicWacTests {
@Test
void applicationContextLoads(WebApplicationContext wac) {
assertThat(wac.getBean("foo", String.class)).isEqualTo("enigma");
}
@Configuration
@EnableWebMvc
static | EnableWebMvcAnnotationConfigTests |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/dev/filesystem/watch/FileChangeCallback.java | {
"start": 143,
"end": 383
} | interface ____ {
/**
* Method that is invoked when file system changes are detected.
*
* @param changes the file system changes
*/
void handleChanges(final Collection<FileChangeEvent> changes);
}
| FileChangeCallback |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/ProducerTemplate.java | {
"start": 40427,
"end": 41329
} | class ____)
* @throws CamelExecutionException if the processing of the exchange failed
*/
<T> T requestBodyAndHeader(String endpointUri, Object body, String header, Object headerValue, Class<T> type)
throws CamelExecutionException;
/**
* Sends the body to an endpoint with the specified headers and header values. Uses an {@link ExchangePattern#InOut}
* message exchange pattern. <br/>
* <br/>
* <p/>
* <b>Notice:</b> that if the processing of the exchange failed with an Exception it is thrown from this method as a
* {@link org.apache.camel.CamelExecutionException} with the caused exception wrapped.
*
* @param endpointUri the endpoint URI to send to
* @param body the payload to send
* @param headers headers
* @return the result (see | javadoc |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/AbfsConfiguration.java | {
"start": 43760,
"end": 44066
} | class ____ AuthType
* matches with authType passed.
* @param authType AuthType effective on the account
* @param name Account-agnostic configuration key
* @param defaultValue Class returned if none is configured
* @param xface Interface shared by all possible values
* @param <U> Interface | if |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/ControllerResponse.java | {
"start": 571,
"end": 2833
} | class ____ implements ToXContentObject {
public static final ParseField TYPE = new ParseField("controller_response");
public static final ParseField COMMAND_ID = new ParseField("id");
public static final ParseField SUCCESS = new ParseField("success");
public static final ParseField REASON = new ParseField("reason");
public static final ConstructingObjectParser<ControllerResponse, Void> PARSER = new ConstructingObjectParser<>(
TYPE.getPreferredName(),
a -> new ControllerResponse((int) a[0], (boolean) a[1], (String) a[2])
);
static {
PARSER.declareInt(ConstructingObjectParser.constructorArg(), COMMAND_ID);
PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), SUCCESS);
PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), REASON);
}
private final int commandId;
private final boolean success;
private final String reason;
ControllerResponse(int commandId, boolean success, String reason) {
this.commandId = commandId;
this.success = success;
this.reason = reason;
}
public int getCommandId() {
return commandId;
}
public boolean isSuccess() {
return success;
}
public String getReason() {
return reason;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(COMMAND_ID.getPreferredName(), commandId);
builder.field(SUCCESS.getPreferredName(), success);
if (reason != null) {
builder.field(REASON.getPreferredName(), reason);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ControllerResponse that = (ControllerResponse) o;
return this.commandId == that.commandId && this.success == that.success && Objects.equals(this.reason, that.reason);
}
@Override
public int hashCode() {
return Objects.hash(commandId, success, reason);
}
}
| ControllerResponse |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/AbstractMediaTypeExpression.java | {
"start": 1295,
"end": 3723
} | class ____ implements Comparable<AbstractMediaTypeExpression>, MediaTypeExpression {
private final MediaType mediaType;
private final boolean isNegated;
AbstractMediaTypeExpression(String expression) {
if (expression.startsWith("!")) {
this.isNegated = true;
expression = expression.substring(1);
}
else {
this.isNegated = false;
}
this.mediaType = MediaType.parseMediaType(expression);
}
AbstractMediaTypeExpression(MediaType mediaType, boolean negated) {
this.mediaType = mediaType;
this.isNegated = negated;
}
@Override
public MediaType getMediaType() {
return this.mediaType;
}
@Override
public boolean isNegated() {
return this.isNegated;
}
public final boolean match(ServerWebExchange exchange) {
try {
boolean match = matchMediaType(exchange);
return (!this.isNegated == match);
}
catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
return false;
}
}
protected abstract boolean matchMediaType(ServerWebExchange exchange)
throws NotAcceptableStatusException, UnsupportedMediaTypeStatusException;
protected boolean matchParameters(MediaType contentType) {
for (Map.Entry<String, String> entry : getMediaType().getParameters().entrySet()) {
if (StringUtils.hasText(entry.getValue())) {
String value = contentType.getParameter(entry.getKey());
if (StringUtils.hasText(value) && !entry.getValue().equalsIgnoreCase(value)) {
return false;
}
}
}
return true;
}
@Override
public int compareTo(AbstractMediaTypeExpression other) {
MediaType mediaType1 = getMediaType();
MediaType mediaType2 = other.getMediaType();
if (mediaType1.isMoreSpecific(mediaType2)) {
return -1;
}
else if (mediaType1.isLessSpecific(mediaType2)) {
return 1;
}
else {
return 0;
}
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
AbstractMediaTypeExpression otherExpr = (AbstractMediaTypeExpression) other;
return (this.mediaType.equals(otherExpr.mediaType) && this.isNegated == otherExpr.isNegated);
}
@Override
public int hashCode() {
return this.mediaType.hashCode();
}
@Override
public String toString() {
if (this.isNegated) {
return '!' + this.mediaType.toString();
}
return this.mediaType.toString();
}
}
| AbstractMediaTypeExpression |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java | {
"start": 58634,
"end": 59111
} | class ____ implements ServerResponse.Context {
private final HandlerStrategies strategies;
public HandlerStrategiesResponseContext(HandlerStrategies strategies) {
this.strategies = strategies;
}
@Override
public List<HttpMessageWriter<?>> messageWriters() {
return this.strategies.messageWriters();
}
@Override
public List<ViewResolver> viewResolvers() {
return this.strategies.viewResolvers();
}
}
private static | HandlerStrategiesResponseContext |
java | spring-projects__spring-framework | spring-orm/src/main/java/org/springframework/orm/jpa/JpaSystemException.java | {
"start": 1052,
"end": 1207
} | class ____ extends UncategorizedDataAccessException {
public JpaSystemException(RuntimeException ex) {
super(ex.getMessage(), ex);
}
}
| JpaSystemException |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ConfigurableClusterPrivileges.java | {
"start": 13513,
"end": 14016
} | interface ____ {
ParseField WRITE = new ParseField("write");
ParseField APPLICATIONS = new ParseField("applications");
}
}
/**
* The {@code ManageApplicationPrivileges} privilege is a {@link ConfigurableClusterPrivilege} that grants the
* ability to execute actions related to the management of application privileges (Get, Put, Delete) for a subset
* of applications (identified by a wildcard-aware application-name).
*/
public static | Fields |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/Spr12636Tests.java | {
"start": 1266,
"end": 2583
} | class ____ {
private ConfigurableApplicationContext context;
@AfterEach
void closeContext() {
if (this.context != null) {
this.context.close();
}
}
@Test
void orderOnImplementation() {
this.context = new AnnotationConfigApplicationContext(
UserServiceTwo.class, UserServiceOne.class, UserServiceCollector.class);
UserServiceCollector bean = this.context.getBean(UserServiceCollector.class);
assertThat(bean.userServices).containsExactly(
context.getBean("serviceOne", UserService.class),
context.getBean("serviceTwo", UserService.class));
}
@Test
void orderOnImplementationWithProxy() {
this.context = new AnnotationConfigApplicationContext(
UserServiceTwo.class, UserServiceOne.class, UserServiceCollector.class, AsyncConfig.class);
// Validate those beans are indeed wrapped by a proxy
UserService serviceOne = this.context.getBean("serviceOne", UserService.class);
UserService serviceTwo = this.context.getBean("serviceTwo", UserService.class);
assertThat(AopUtils.isAopProxy(serviceOne)).isTrue();
assertThat(AopUtils.isAopProxy(serviceTwo)).isTrue();
UserServiceCollector bean = this.context.getBean(UserServiceCollector.class);
assertThat(bean.userServices).containsExactly(serviceOne, serviceTwo);
}
@Configuration
@EnableAsync
static | Spr12636Tests |
java | assertj__assertj-core | assertj-core/src/test/java/org/example/test/BDDSoftAssertionsLineNumberTest.java | {
"start": 1161,
"end": 2488
} | class ____ {
@Test
void should_print_line_numbers_of_failed_assertions() {
BDDSoftAssertions softly = new BDDSoftAssertions();
softly.then(1)
.isLessThan(0)
.isLessThan(1);
// WHEN
var error = expectAssertionError(softly::assertAll);
// THEN
assertThat(error).hasMessageContaining(format("%n"
+ "Expecting actual:%n"
+ " 1%n"
+ "to be less than:%n"
+ " 0 %n"
+ "at BDDSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(BDDSoftAssertionsLineNumberTest.java:36)%n"))
.hasMessageContaining(format("%n"
+ "Expecting actual:%n"
+ " 1%n"
+ "to be less than:%n"
+ " 1 %n"
+ "at BDDSoftAssertionsLineNumberTest.should_print_line_numbers_of_failed_assertions(BDDSoftAssertionsLineNumberTest.java:37)"));
}
}
| BDDSoftAssertionsLineNumberTest |
java | quarkusio__quarkus | extensions/spring-web/core/common-runtime/src/main/java/io/quarkus/spring/web/runtime/common/ResponseEntityConverter.java | {
"start": 457,
"end": 1589
} | class ____ {
@SuppressWarnings("rawtypes")
public static Response toResponse(ResponseEntity responseEntity, MediaType defaultMediaType) {
Response.ResponseBuilder responseBuilder = Response.status(responseEntity.getStatusCodeValue())
.entity(responseEntity.getBody());
var jaxRsHeaders = toJaxRsHeaders(responseEntity.getHeaders());
if (!jaxRsHeaders.containsKey(HttpHeaders.CONTENT_TYPE) && (defaultMediaType != null)) {
jaxRsHeaders.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(defaultMediaType.toString()));
}
for (var entry : jaxRsHeaders.entrySet()) {
var value = entry.getValue();
if (value.size() == 1) {
responseBuilder.header(entry.getKey(), entry.getValue().get(0));
} else {
responseBuilder.header(entry.getKey(), entry.getValue());
}
}
return responseBuilder.build();
}
private static Map<String, List<String>> toJaxRsHeaders(HttpHeaders springHeaders) {
return new HashMap<>(springHeaders);
}
}
| ResponseEntityConverter |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java | {
"start": 3697,
"end": 4555
} | class ____ extends BaseConstraint.Builder<Builder, Check> {
private String predicateSql;
private Predicate predicate;
Builder(String name) {
super(name);
}
@Override
protected Builder self() {
return this;
}
public Builder predicateSql(String predicateSql) {
this.predicateSql = predicateSql;
return this;
}
public Builder predicate(Predicate predicate) {
this.predicate = predicate;
return this;
}
public Check build() {
if (predicateSql == null && predicate == null) {
throw new SparkIllegalArgumentException(
"INTERNAL_ERROR",
Map.of("message", "Predicate SQL and expression can't be both null in CHECK"));
}
return new Check(name(), predicateSql, predicate, enforced(), validationStatus(), rely());
}
}
}
| Builder |
java | quarkusio__quarkus | extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/GraphQLBlockingModeTest.java | {
"start": 895,
"end": 10493
} | class ____ extends AbstractGraphQLTest {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((JavaArchive jar) -> jar
.addClasses(TestThreadResource.class, TestThread.class)
.addAsResource(new StringAsset("quarkus.smallrye-graphql.nonblocking.enabled=false"),
"application.properties")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));
@Test
public void testOnlyObject() {
String fooRequest = getPayload("{\n" +
" onlyObject {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.onlyObject.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.onlyObject.vertxContextClassName", Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedNonBlockingObject() {
String fooRequest = getPayload("{\n" +
" annotatedNonBlockingObject {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedNonBlockingObject.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedNonBlockingObject.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedBlockingObject() {
String fooRequest = getPayload("{\n" +
" annotatedBlockingObject {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedBlockingObject.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedBlockingObject.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testOnlyReactiveUni() {
String fooRequest = getPayload("{\n" +
" onlyReactiveUni {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.onlyReactiveUni.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.onlyReactiveUni.vertxContextClassName", Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedBlockingReactiveUni() {
String fooRequest = getPayload("{\n" +
" annotatedBlockingReactiveUni {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedBlockingReactiveUni.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedBlockingReactiveUni.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedNonBlockingReactiveUni() {
String fooRequest = getPayload("{\n" +
" annotatedNonBlockingReactiveUni {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedNonBlockingReactiveUni.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedNonBlockingReactiveUni.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testOnlyCompletionStage() {
String fooRequest = getPayload("{\n" +
" onlyCompletionStage {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.onlyCompletionStage.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.onlyCompletionStage.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedBlockingCompletionStage() {
String fooRequest = getPayload("{\n" +
" annotatedBlockingCompletionStage {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedBlockingCompletionStage.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedBlockingCompletionStage.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@Test
public void testAnnotatedNonBlockingCompletionStage() {
String fooRequest = getPayload("{\n" +
" annotatedNonBlockingCompletionStage {\n" +
" name\n" +
" priority\n" +
" state\n" +
" group\n" +
" vertxContextClassName\n" +
" }\n" +
"}");
RestAssured.given().when()
.accept(MEDIATYPE_JSON)
.contentType(MEDIATYPE_JSON)
.body(fooRequest)
.post("/graphql")
.then()
.assertThat()
.statusCode(200)
.and()
.log().body().and()
.body("data.annotatedNonBlockingCompletionStage.name", Matchers.startsWith("executor-thread"))
.and()
.body("data.annotatedNonBlockingCompletionStage.vertxContextClassName",
Matchers.equalTo("io.vertx.core.impl.DuplicatedContext"));
}
@GraphQLApi
public static | GraphQLBlockingModeTest |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java | {
"start": 9403,
"end": 9469
} | interface ____ {
void foo() throws Exception;
}
private | ITester |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/ObjectWritable.java | {
"start": 11706,
"end": 12754
} | enum
____ = Enum.valueOf((Class<? extends Enum>) declaredClass, UTF8.readString(in));
} else if (Message.class.isAssignableFrom(declaredClass)) {
instance = tryInstantiateProtobuf(declaredClass, in);
} else { // Writable
Class instanceClass = null;
String str = UTF8.readString(in);
instanceClass = loadClass(conf, str);
Writable writable = WritableFactories.newInstance(instanceClass, conf);
writable.readFields(in);
instance = writable;
if (instanceClass == NullInstance.class) { // null
declaredClass = ((NullInstance)instance).declaredClass;
instance = null;
}
}
if (objectWritable != null) { // store values
objectWritable.declaredClass = declaredClass;
objectWritable.instance = instance;
}
return instance;
}
/**
* Try to instantiate a protocol buffer of the given message class
* from the given input stream.
*
* @param protoClass the | instance |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/SnapshotSortKey.java | {
"start": 1242,
"end": 11575
} | enum ____ {
/**
* Sort by snapshot start time.
*/
START_TIME("start_time", Comparator.comparingLong(SnapshotInfo::startTime)) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return Long.toString(snapshotInfo.startTime());
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
return after.longValuePredicate(SnapshotInfo::startTime, sortOrder);
}
},
/**
* Sort by snapshot name.
*/
NAME("name", Comparator.comparing(sni -> sni.snapshotId().getName())) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return snapshotInfo.snapshotId().getName();
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
// TODO: cover via pre-flight predicate
final String snapshotName = after.snapshotName();
final String repoName = after.repoName();
return sortOrder == SortOrder.ASC
? (info -> compareName(snapshotName, repoName, info) < 0)
: (info -> compareName(snapshotName, repoName, info) > 0);
}
},
/**
* Sort by snapshot duration (end time minus start time).
*/
DURATION("duration", Comparator.comparingLong(sni -> sni.endTime() - sni.startTime())) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return Long.toString(snapshotInfo.endTime() - snapshotInfo.startTime());
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
return after.longValuePredicate(info -> info.endTime() - info.startTime(), sortOrder);
}
},
/**
* Sort by number of indices in the snapshot.
*/
INDICES("index_count", Comparator.comparingInt(sni -> sni.indices().size())) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return Integer.toString(snapshotInfo.indices().size());
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
// TODO: cover via pre-flight predicate
return after.longValuePredicate(info -> info.indices().size(), sortOrder);
}
},
/**
* Sort by number of shards in the snapshot.
*/
SHARDS("shard_count", Comparator.comparingInt(SnapshotInfo::totalShards)) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return Integer.toString(snapshotInfo.totalShards());
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
return after.longValuePredicate(SnapshotInfo::totalShards, sortOrder);
}
},
/**
* Sort by number of failed shards in the snapshot.
*/
FAILED_SHARDS("failed_shard_count", Comparator.comparingInt(SnapshotInfo::failedShards)) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return Integer.toString(snapshotInfo.failedShards());
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
return after.longValuePredicate(SnapshotInfo::failedShards, sortOrder);
}
},
/**
* Sort by repository name.
*/
REPOSITORY("repository", Comparator.comparing(SnapshotInfo::repository)) {
@Override
protected String getSortKeyValue(SnapshotInfo snapshotInfo) {
return snapshotInfo.repository();
}
@Override
protected Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder) {
// TODO: cover via pre-flight predicate
final String snapshotName = after.snapshotName();
final String repoName = after.repoName();
return sortOrder == SortOrder.ASC
? (info -> compareRepositoryName(snapshotName, repoName, info) < 0)
: (info -> compareRepositoryName(snapshotName, repoName, info) > 0);
}
private static int compareRepositoryName(String name, String repoName, SnapshotInfo info) {
final int res = repoName.compareTo(info.repository());
if (res != 0) {
return res;
}
return name.compareTo(info.snapshotId().getName());
}
};
private final String name;
private final Comparator<SnapshotInfo> ascendingSnapshotInfoComparator;
private final Comparator<SnapshotInfo> descendingSnapshotInfoComparator;
SnapshotSortKey(String name, Comparator<SnapshotInfo> snapshotInfoComparator) {
this.name = name;
this.ascendingSnapshotInfoComparator = snapshotInfoComparator.thenComparing(SnapshotInfo::snapshotId);
this.descendingSnapshotInfoComparator = ascendingSnapshotInfoComparator.reversed();
}
@Override
public String toString() {
return name;
}
/**
* @return a {@link Comparator} which sorts {@link SnapshotInfo} instances according to this sort key.
*/
public final Comparator<SnapshotInfo> getSnapshotInfoComparator(SortOrder sortOrder) {
return switch (sortOrder) {
case ASC -> ascendingSnapshotInfoComparator;
case DESC -> descendingSnapshotInfoComparator;
};
}
/**
* @return an {@link After} which can be included in a {@link GetSnapshotsRequest} (e.g. to be sent to a remote node) and ultimately
* converted into a predicate to filter out {@link SnapshotInfo} items which were returned on earlier pages of results. See also
* {@link #encodeAfterQueryParam} and {@link #getAfterPredicate}.
*/
public static After decodeAfterQueryParam(String param) {
final String[] parts = new String(Base64.getUrlDecoder().decode(param), StandardCharsets.UTF_8).split(",");
if (parts.length != 3) {
throw new IllegalArgumentException("invalid ?after parameter [" + param + "]");
}
return new After(parts[0], parts[1], parts[2]);
}
/**
* @return an encoded representation of the value of the sort key for the given {@link SnapshotInfo}, including the values of the
* snapshot name and repo name for tiebreaking purposes, which can be returned to the user so they can pass it back to the
* {@code ?after} param of a subsequent call to the get-snapshots API in order to retrieve the next page of results.
*/
public final String encodeAfterQueryParam(SnapshotInfo snapshotInfo) {
final var rawValue = getSortKeyValue(snapshotInfo) + "," + snapshotInfo.repository() + "," + snapshotInfo.snapshotId().getName();
return Base64.getUrlEncoder().encodeToString(rawValue.getBytes(StandardCharsets.UTF_8));
}
/**
* @return a string representation of the value of the sort key for the given {@link SnapshotInfo}, which should be the last item in the
* response, which is combined with the snapshot and repository names, encoded, and returned to the user so they can pass it back to
* the {@code ?after} param of a subsequent call to the get-snapshots API in order to retrieve the next page of results.
*/
protected abstract String getSortKeyValue(SnapshotInfo snapshotInfo);
/**
* @return a predicate to filter out {@link SnapshotInfo} items that match the user's query but which sort earlier than the given
* {@link After} value (i.e. they were returned on earlier pages of results). If {@code after} is {@code null} then the returned
* predicate matches all snapshots.
*/
public final Predicate<SnapshotInfo> getAfterPredicate(@Nullable After after, SortOrder sortOrder) {
return after == null ? Predicates.always() : innerGetAfterPredicate(after, sortOrder);
}
/**
* @return a predicate to filter out {@link SnapshotInfo} items that match the user's query but which sort earlier than the given
* {@link After} value (i.e. they were returned on earlier pages of results). The {@code after} parameter is not {@code null}.
*/
protected abstract Predicate<SnapshotInfo> innerGetAfterPredicate(After after, SortOrder sortOrder);
private static int compareName(String name, String repoName, SnapshotInfo info) {
final int res = name.compareTo(info.snapshotId().getName());
if (res != 0) {
return res;
}
return repoName.compareTo(info.repository());
}
public static SnapshotSortKey of(String name) {
return switch (name) {
case "start_time" -> START_TIME;
case "name" -> NAME;
case "duration" -> DURATION;
case "index_count" -> INDICES;
case "shard_count" -> SHARDS;
case "failed_shard_count" -> FAILED_SHARDS;
case "repository" -> REPOSITORY;
default -> throw new IllegalArgumentException("unknown sort key [" + name + "]");
};
}
public record After(String value, String repoName, String snapshotName) implements Writeable {
After(StreamInput in) throws IOException {
this(in.readString(), in.readString(), in.readString());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(value);
out.writeString(repoName);
out.writeString(snapshotName);
}
Predicate<SnapshotInfo> longValuePredicate(ToLongFunction<SnapshotInfo> extractor, SortOrder sortOrder) {
final var after = Long.parseLong(value);
return sortOrder == SortOrder.ASC ? info -> {
final long val = extractor.applyAsLong(info);
return after < val || (after == val && compareName(snapshotName, repoName, info) < 0);
} : info -> {
final long val = extractor.applyAsLong(info);
return after > val || (after == val && compareName(snapshotName, repoName, info) > 0);
};
}
}
}
| SnapshotSortKey |
java | dropwizard__dropwizard | dropwizard-health/src/main/java/io/dropwizard/health/HealthCheckConfiguration.java | {
"start": 217,
"end": 1419
} | class ____ {
@NotNull
@Size(min = 1)
@JsonProperty
private String name = "";
@NotNull
@JsonProperty
private HealthCheckType type = HealthCheckType.READY;
@JsonProperty
private boolean critical = false;
@JsonProperty
private boolean initialState = true;
@Valid
@NotNull
@JsonProperty
private Schedule schedule = new Schedule();
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public HealthCheckType getType() {
return type;
}
public void setType(HealthCheckType type) {
this.type = type;
}
public boolean isCritical() {
return critical;
}
public void setCritical(final boolean critical) {
this.critical = critical;
}
public boolean isInitialState() {
return initialState;
}
public void setInitialState(boolean initialState) {
this.initialState = initialState;
}
public Schedule getSchedule() {
return schedule;
}
public void setSchedule(final Schedule schedule) {
this.schedule = schedule;
}
}
| HealthCheckConfiguration |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_SpitFire_3.java | {
"start": 169,
"end": 565
} | class ____ extends TestCase {
public void test_for_SpitFire() {
Generic<Payload> q = new Generic<Payload>();
q.setHeader("Sdfdf");
q.setPayload(new Payload());
String text = JSON.toJSONString(q, SerializerFeature.WriteClassName);
System.out.println(text);
JSON.parseObject(text, Generic.class);
}
public static abstract | Bug_for_SpitFire_3 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinedInheritanceCircularBiDirectionalFetchTest.java | {
"start": 3463,
"end": 3726
} | class ____ {
@Id
@GeneratedValue
private long id;
@ManyToOne( fetch = FetchType.LAZY )
private Cat cat;
private String name;
public Leg() {
}
public Leg(String name) {
this.name = name;
}
public Cat getCat() {
return cat;
}
}
}
| Leg |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/inference/ResolvedInferenceTests.java | {
"start": 522,
"end": 1552
} | class ____ extends AbstractWireTestCase<ResolvedInference> {
@Override
protected ResolvedInference createTestInstance() {
return new ResolvedInference(randomIdentifier(), randomTaskType());
}
@Override
protected ResolvedInference mutateInstance(ResolvedInference instance) throws IOException {
if (randomBoolean()) {
return new ResolvedInference(randomValueOtherThan(instance.inferenceId(), ESTestCase::randomIdentifier), instance.taskType());
}
return new ResolvedInference(instance.inferenceId(), randomValueOtherThan(instance.taskType(), this::randomTaskType));
}
@Override
protected ResolvedInference copyInstance(ResolvedInference instance, TransportVersion version) throws IOException {
return copyInstance(instance, getNamedWriteableRegistry(), (out, v) -> v.writeTo(out), in -> new ResolvedInference(in), version);
}
private TaskType randomTaskType() {
return randomFrom(TaskType.values());
}
}
| ResolvedInferenceTests |
java | alibaba__nacos | core/src/test/java/com/alibaba/nacos/core/namespace/filter/NamespaceValidationRequestFilterTest.java | {
"start": 13558,
"end": 13924
} | class ____ extends RequestHandler<Request, Response> {
@Override
@ExtractorManager.Extractor(rpcExtractor = InstanceRequestParamExtractor.class)
public Response handle(Request request, RequestMeta meta) throws NacosException {
return new Response() {
};
}
}
static | MockWithoutNamespaceValidationAnnotation |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/function/MethodInvokersFailableFunctionTest.java | {
"start": 1478,
"end": 3357
} | class ____ extends MethodFixtures {
@Test
void testApply0Arg() throws Throwable {
assertEquals(INSTANCE.getString(), MethodInvokers.asFailableFunction(getMethodForGetString()).apply(INSTANCE));
}
@Test
void testBuildVarArg() throws SecurityException, NoSuchMethodException {
MethodInvokers.asFailableFunction(getMethodForGetStringVarStringArgs());
}
@Test
void testConstructorForNull() throws SecurityException {
assertNullPointerException(() -> MethodInvokers.asFailableFunction((Method) null));
}
@Test
void testFindAndInvoke() throws SecurityException {
// Finding
final List<FailableFunction<Object, Object, Throwable>> invokers = Stream.of(MethodFixtures.class.getDeclaredMethods())
.filter(m -> m.isAnnotationPresent(AnnotationTestFixture.class)).map(MethodInvokers::asFailableFunction).collect(Collectors.toList());
assertEquals(2, invokers.size());
// ...
// Invoking
final Set<Object> set = invokers.stream().map(i -> {
try {
return i.apply(MethodFixtures.INSTANCE);
} catch (final Throwable e) {
throw new UncheckedException(e);
}
}).collect(Collectors.toSet());
assertEquals(new HashSet<>(Arrays.asList(INSTANCE.getString(), INSTANCE.getString2())), set);
}
@Test
void testThrowsChecked() throws Exception {
assertThrows(Exception.class, () -> MethodInvokers.asFailableFunction(getMethodForGetStringThrowsChecked()).apply(INSTANCE));
}
@Test
void testToString() throws SecurityException, ReflectiveOperationException {
// Should not blow up and must return _something_
assertFalse(MethodInvokers.asFailableFunction(getMethodForGetString()).toString().isEmpty());
}
}
| MethodInvokersFailableFunctionTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/tck/TimeoutTckTest.java | {
"start": 811,
"end": 1045
} | class ____ extends BaseTck<Integer> {
@Override
public Publisher<Integer> createPublisher(long elements) {
return
Flowable.range(0, (int)elements).timeout(1, TimeUnit.DAYS)
;
}
}
| TimeoutTckTest |
java | apache__flink | flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/operator/CepRuntimeContextTest.java | {
"start": 13123,
"end": 14048
} | class ____ {
private final VerifyRuntimeContextProcessFunction function;
static MockProcessFunctionAsserter assertFunction(
VerifyRuntimeContextProcessFunction function) {
return new MockProcessFunctionAsserter(function);
}
private MockProcessFunctionAsserter(VerifyRuntimeContextProcessFunction function) {
this.function = function;
}
MockProcessFunctionAsserter checkOpenCalled() {
assertThat(function.openCalled, is(true));
return this;
}
MockProcessFunctionAsserter checkCloseCalled() {
assertThat(function.openCalled, is(true));
return this;
}
MockProcessFunctionAsserter checkProcessMatchCalled() {
assertThat(function.processMatchCalled, is(true));
return this;
}
}
private static | MockProcessFunctionAsserter |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/selection/twosteperror/ErroneousMapperCM.java | {
"start": 777,
"end": 913
} | class ____ {
public String t1;
public TargetType(String test) {
this.t1 = test;
}
}
| TargetType |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/hdfs/NNBench.java | {
"start": 25462,
"end": 36315
} | class ____ extends Configured
implements Mapper<Text, LongWritable, Text, Text> {
FileSystem filesystem = null;
long numberOfFiles = 1l;
long blkSize = 1l;
short replFactor = 1;
int bytesToWrite = 0;
String baseDir = null;
String dataDirName = null;
String op = null;
boolean readFile = false;
// Data to collect from the operation
int numOfExceptions = 0;
long startTimeAL = 0l;
long totalTimeAL1 = 0l;
long totalTimeAL2 = 0l;
long successfulFileOps = 0l;
/**
* Constructor
*/
public NNBenchMapper() {
}
/**
* Mapper base implementation
*/
public void configure(JobConf conf) {
setConf(conf);
try {
String dir = conf.get("test.nnbench.basedir");
filesystem = FileSystem.get(new Path(dir).toUri(), conf);
} catch(Exception e) {
throw new RuntimeException("Cannot get file system.", e);
}
}
/**
* Mapper base implementation
*/
public void close() throws IOException {
}
/**
* Returns when the current number of seconds from the epoch equals
* the command line argument given by <code>-startTime</code>.
* This allows multiple instances of this program, running on clock
* synchronized nodes, to start at roughly the same time.
* @return true if the method was able to sleep for <code>-startTime</code>
* without interruption; false otherwise
*/
private boolean barrier() {
long startTime = getConf().getLong("test.nnbench.starttime", 0l);
long currentTime = System.currentTimeMillis();
long sleepTime = startTime - currentTime;
boolean retVal = true;
// If the sleep time is greater than 0, then sleep and return
if (sleepTime > 0) {
LOG.info("Waiting in barrier for: " + sleepTime + " ms");
try {
Thread.sleep(sleepTime);
retVal = true;
} catch (Exception e) {
retVal = false;
}
}
return retVal;
}
/**
* Map method
*/
public void map(Text key,
LongWritable value,
OutputCollector<Text, Text> output,
Reporter reporter) throws IOException {
Configuration conf = getConf();
numberOfFiles = conf.getLong("test.nnbench.numberoffiles", 1l);
blkSize = conf.getLong("test.nnbench.blocksize", 1l);
replFactor = (short) (conf.getInt("test.nnbench.replicationfactor", 1));
bytesToWrite = conf.getInt("test.nnbench.bytestowrite", 0);
baseDir = conf.get("test.nnbench.basedir");
dataDirName = conf.get("test.nnbench.datadir.name");
op = conf.get("test.nnbench.operation");
readFile = conf.getBoolean("test.nnbench.readFileAfterOpen", false);
long totalTimeTPmS = 0l;
long startTimeTPmS = 0l;
long endTimeTPms = 0l;
numOfExceptions = 0;
startTimeAL = 0l;
totalTimeAL1 = 0l;
totalTimeAL2 = 0l;
successfulFileOps = 0l;
if (barrier()) {
String fileName = "file_" + value;
if (op.equals(OP_CREATE_WRITE)) {
startTimeTPmS = System.currentTimeMillis();
doCreateWriteOp(fileName, reporter);
} else if (op.equals(OP_OPEN_READ)) {
startTimeTPmS = System.currentTimeMillis();
doOpenReadOp(fileName, reporter);
} else if (op.equals(OP_RENAME)) {
startTimeTPmS = System.currentTimeMillis();
doRenameOp(fileName, reporter);
} else if (op.equals(OP_DELETE)) {
startTimeTPmS = System.currentTimeMillis();
doDeleteOp(fileName, reporter);
} else {
throw new IllegalArgumentException(
"unsupported operation [" + op + "]");
}
endTimeTPms = System.currentTimeMillis();
totalTimeTPmS = endTimeTPms - startTimeTPmS;
} else {
output.collect(new Text("l:latemaps"), new Text("1"));
}
// collect after the map end time is measured
output.collect(new Text("l:totalTimeAL1"),
new Text(String.valueOf(totalTimeAL1)));
output.collect(new Text("l:totalTimeAL2"),
new Text(String.valueOf(totalTimeAL2)));
output.collect(new Text("l:numOfExceptions"),
new Text(String.valueOf(numOfExceptions)));
output.collect(new Text("l:successfulFileOps"),
new Text(String.valueOf(successfulFileOps)));
output.collect(new Text("l:totalTimeTPmS"),
new Text(String.valueOf(totalTimeTPmS)));
output.collect(new Text("min:mapStartTimeTPmS"),
new Text(String.valueOf(startTimeTPmS)));
output.collect(new Text("max:mapEndTimeTPmS"),
new Text(String.valueOf(endTimeTPms)));
}
/**
* Create and Write operation.
* @param name of the prefix of the putput file to be created
* @param reporter an instanse of (@link Reporter) to be used for
* status' updates
*/
private void doCreateWriteOp(String name,
Reporter reporter) {
FSDataOutputStream out;
byte[] buffer = new byte[bytesToWrite];
for (long l = 0l; l < numberOfFiles; l++) {
Path filePath = new Path(new Path(baseDir, dataDirName),
name + "_" + l);
boolean successfulOp = false;
while (! successfulOp && numOfExceptions < MAX_OPERATION_EXCEPTIONS) {
try {
// Set up timer for measuring AL (transaction #1)
startTimeAL = System.currentTimeMillis();
// Create the file
// Use a buffer size of 512
out = filesystem.create(filePath,
true,
512,
replFactor,
blkSize);
out.write(buffer);
totalTimeAL1 += (System.currentTimeMillis() - startTimeAL);
// Close the file / file output stream
// Set up timers for measuring AL (transaction #2)
startTimeAL = System.currentTimeMillis();
out.close();
totalTimeAL2 += (System.currentTimeMillis() - startTimeAL);
successfulOp = true;
successfulFileOps ++;
reporter.setStatus("Finish "+ l + " files");
} catch (IOException e) {
LOG.error("Exception recorded in op: Create/Write/Close, "
+ "file: \"" + filePath + "\"", e);
numOfExceptions++;
}
}
}
}
/**
* Open operation
* @param name of the prefix of the putput file to be read
* @param reporter an instanse of (@link Reporter) to be used for
* status' updates
*/
private void doOpenReadOp(String name,
Reporter reporter) {
FSDataInputStream input;
byte[] buffer = new byte[bytesToWrite];
for (long l = 0l; l < numberOfFiles; l++) {
Path filePath = new Path(new Path(baseDir, dataDirName),
name + "_" + l);
boolean successfulOp = false;
while (! successfulOp && numOfExceptions < MAX_OPERATION_EXCEPTIONS) {
try {
// Set up timer for measuring AL
startTimeAL = System.currentTimeMillis();
input = filesystem.open(filePath);
totalTimeAL1 += (System.currentTimeMillis() - startTimeAL);
// If the file needs to be read (specified at command line)
if (readFile) {
startTimeAL = System.currentTimeMillis();
input.readFully(buffer);
totalTimeAL2 += (System.currentTimeMillis() - startTimeAL);
}
input.close();
successfulOp = true;
successfulFileOps ++;
reporter.setStatus("Finish "+ l + " files");
} catch (IOException e) {
LOG.error("Exception recorded in op: OpenRead, " + "file: \""
+ filePath + "\"", e);
numOfExceptions++;
}
}
}
}
/**
* Rename operation
* @param name of prefix of the file to be renamed
* @param reporter an instanse of (@link Reporter) to be used for
* status' updates
*/
private void doRenameOp(String name,
Reporter reporter) {
for (long l = 0l; l < numberOfFiles; l++) {
Path filePath = new Path(new Path(baseDir, dataDirName),
name + "_" + l);
Path filePathR = new Path(new Path(baseDir, dataDirName),
name + "_r_" + l);
boolean successfulOp = false;
while (! successfulOp && numOfExceptions < MAX_OPERATION_EXCEPTIONS) {
try {
// Set up timer for measuring AL
startTimeAL = System.currentTimeMillis();
boolean result = filesystem.rename(filePath, filePathR);
if (!result) {
throw new IOException("rename failed for " + filePath);
}
totalTimeAL1 += (System.currentTimeMillis() - startTimeAL);
successfulOp = true;
successfulFileOps ++;
reporter.setStatus("Finish "+ l + " files");
} catch (IOException e) {
LOG.error("Exception recorded in op: Rename, " + "file: \""
+ filePath + "\"", e);
numOfExceptions++;
}
}
}
}
/**
* Delete operation
* @param name of prefix of the file to be deleted
* @param reporter an instanse of (@link Reporter) to be used for
* status' updates
*/
private void doDeleteOp(String name,
Reporter reporter) {
for (long l = 0l; l < numberOfFiles; l++) {
Path filePath = new Path(new Path(baseDir, dataDirName),
name + "_" + l);
boolean successfulOp = false;
while (! successfulOp && numOfExceptions < MAX_OPERATION_EXCEPTIONS) {
try {
// Set up timer for measuring AL
startTimeAL = System.currentTimeMillis();
boolean result = filesystem.delete(filePath, true);
if (!result) {
throw new IOException("delete failed for " + filePath);
}
totalTimeAL1 += (System.currentTimeMillis() - startTimeAL);
successfulOp = true;
successfulFileOps ++;
reporter.setStatus("Finish "+ l + " files");
} catch (IOException e) {
LOG.error("Exception recorded in op: Delete, " + "file: \""
+ filePath + "\"", e);
numOfExceptions++;
}
}
}
}
}
/**
* Reducer class
*/
static | NNBenchMapper |
java | google__truth | core/src/main/java/com/google/common/truth/MapSubject.java | {
"start": 26108,
"end": 39293
} | class ____<
A extends @Nullable Object, E extends @Nullable Object> {
private final MapSubject subject;
private final Correspondence<? super A, ? super E> correspondence;
private final @Nullable Map<?, ?> actual;
private UsingCorrespondence(
MapSubject subject, Correspondence<? super A, ? super E> correspondence) {
this.subject = subject;
this.correspondence = checkNotNull(correspondence);
this.actual = subject.actual;
}
/**
* Checks that the actual map contains an entry with the given key and a value that corresponds
* to the given value.
*/
@SuppressWarnings("UnnecessaryCast") // needed by nullness checker
public void containsEntry(@Nullable Object key, E value) {
if (actual == null) {
failWithActual("expected a map that contains entry", immutableEntry(key, value));
return;
}
if (actual.containsKey(key)) {
// Found matching key.
A actualValue = castActual(actual).get(key);
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues();
if (correspondence.safeCompare((A) actualValue, value, exceptions)) {
// The expected key had the expected value. There's no need to check exceptions here,
// because if Correspondence.compare() threw then safeCompare() would return false.
return;
}
// Found matching key with non-matching value.
String diff = correspondence.safeFormatDiff((A) actualValue, value, exceptions);
if (diff != null) {
failWithoutActual(
factsBuilder()
.add(fact("for key", key))
.add(fact("expected value", value))
.addAll(correspondence.describeForMapValues())
.add(fact("but got value", actualValue))
.add(fact("diff", diff))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.addAll(exceptions.describeAsAdditionalInfo())
.build());
} else {
failWithoutActual(
factsBuilder()
.add(fact("for key", key))
.add(fact("expected value", value))
.addAll(correspondence.describeForMapValues())
.add(fact("but got value", actualValue))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.addAll(exceptions.describeAsAdditionalInfo())
.build());
}
} else {
// Did not find matching key. Look for the matching value with a different key.
Set<@Nullable Object> keys = new LinkedHashSet<>();
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues();
for (Map.Entry<?, A> actualEntry : castActual(actual).entrySet()) {
if (correspondence.safeCompare(actualEntry.getValue(), value, exceptions)) {
keys.add(actualEntry.getKey());
}
}
if (!keys.isEmpty()) {
// Found matching values with non-matching keys.
failWithoutActual(
factsBuilder()
.add(fact("for key", key))
.add(fact("expected value", value))
.addAll(correspondence.describeForMapValues())
.add(simpleFact("but was missing"))
.add(fact("other keys with matching values", keys))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.addAll(exceptions.describeAsAdditionalInfo())
.build());
} else {
// Did not find matching key or value.
failWithoutActual(
factsBuilder()
.add(fact("for key", key))
.add(fact("expected value", value))
.addAll(correspondence.describeForMapValues())
.add(simpleFact("but was missing"))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.addAll(exceptions.describeAsAdditionalInfo())
.build());
}
}
}
/**
* Checks that the actual map does not contain an entry with the given key and a value that
* corresponds to the given value.
*/
@SuppressWarnings("UnnecessaryCast") // needed by nullness checker
public void doesNotContainEntry(@Nullable Object key, E value) {
if (actual == null) {
failWithActual("expected a map that does not contain entry", immutableEntry(key, value));
return;
}
if (actual.containsKey(key)) {
// Found matching key. Fail if the value matches, too.
A actualValue = castActual(actual).get(key);
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues();
if (correspondence.safeCompare((A) actualValue, value, exceptions)) {
// The matching key had a matching value. There's no need to check exceptions here,
// because if Correspondence.compare() threw then safeCompare() would return false.
failWithoutActual(
factsBuilder()
.add(fact("expected not to contain", immutableEntry(key, value)))
.addAll(correspondence.describeForMapValues())
.add(
fact(
"but contained",
Maps.<@Nullable Object, @Nullable A>immutableEntry(key, actualValue)))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.addAll(exceptions.describeAsAdditionalInfo())
.build());
}
// The value didn't match, but we still need to fail if we hit an exception along the way.
if (exceptions.hasCompareException()) {
failWithoutActual(
factsBuilder()
.addAll(exceptions.describeAsMainCause())
.add(fact("expected not to contain", immutableEntry(key, value)))
.addAll(correspondence.describeForMapValues())
.add(simpleFact("found no match (but failing because of exception)"))
.add(fact("full map", actualCustomStringRepresentationForPackageMembersToCall()))
.build());
}
}
}
/**
* Checks that the actual map contains exactly the given set of keys mapping to values that
* correspond to the given values.
*
* <p>The values must all be of type {@code E}, and a {@link ClassCastException} will be thrown
* if any other type is encountered.
*
* <p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of
* key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
*/
// TODO(b/25744307): Can we add an error-prone check that rest.length % 2 == 0?
// For bonus points, checking that the even-numbered values are of type E would be sweet.
@CanIgnoreReturnValue
public Ordered containsExactly(@Nullable Object k0, @Nullable E v0, @Nullable Object... rest) {
@SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour
Map<Object, E> expectedMap = (Map<Object, E>) accumulateMap("containsExactly", k0, v0, rest);
return containsExactlyEntriesIn(expectedMap);
}
/**
* Checks that the actual map contains at least the given set of keys mapping to values that
* correspond to the given values.
*
* <p>The values must all be of type {@code E}, and a {@link ClassCastException} will be thrown
* if any other type is encountered.
*
* <p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of
* key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
*/
// TODO(b/25744307): Can we add an error-prone check that rest.length % 2 == 0?
// For bonus points, checking that the even-numbered values are of type E would be sweet.
@CanIgnoreReturnValue
public Ordered containsAtLeast(@Nullable Object k0, @Nullable E v0, @Nullable Object... rest) {
@SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour
Map<Object, E> expectedMap = (Map<Object, E>) accumulateMap("containsAtLeast", k0, v0, rest);
return containsAtLeastEntriesIn(expectedMap);
}
/**
* Checks that the actual map contains exactly the keys in the given map, mapping to values that
* correspond to the values of the given map.
*/
@CanIgnoreReturnValue
public Ordered containsExactlyEntriesIn(@Nullable Map<?, ? extends E> expected) {
if (expected == null) {
failWithoutActual(
simpleFact("could not perform containment check because expected map was null"),
actualContents());
return ALREADY_FAILED;
} else if (expected.isEmpty()) {
return subject.containsExactly();
} else if (actual == null) {
failWithActual("expected a map that contains exactly", expected);
return ALREADY_FAILED;
}
return internalContainsEntriesIn(actual, expected, /* allowUnexpected= */ false);
}
/**
* Checks that the actual map contains at least the keys in the given map, mapping to values
* that correspond to the values of the given map.
*/
@CanIgnoreReturnValue
public Ordered containsAtLeastEntriesIn(@Nullable Map<?, ? extends E> expected) {
if (expected == null) {
failWithoutActual(
simpleFact("could not perform containment check because expected map was null"),
actualContents());
return ALREADY_FAILED;
} else if (expected.isEmpty()) {
return IN_ORDER;
} else if (actual == null) {
failWithActual("expected a map that contains at least", expected);
return ALREADY_FAILED;
}
return internalContainsEntriesIn(actual, expected, /* allowUnexpected= */ true);
}
private <K extends @Nullable Object, V extends E> Ordered internalContainsEntriesIn(
Map<?, ?> actual, Map<K, V> expected, boolean allowUnexpected) {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forMapValues();
MapDifference<@Nullable Object, A, V> diff =
MapDifference.create(
castActual(actual),
expected,
allowUnexpected,
(actualValue, expectedValue) ->
correspondence.safeCompare(actualValue, expectedValue, exceptions));
if (diff.isEmpty()) {
// The maps correspond exactly. There's no need to check exceptions here, because if
// Correspondence.compare() threw then safeCompare() would return false and the diff would
// record that we had the wrong value for that key.
return MapInOrder.create(subject, actual, expected, allowUnexpected, correspondence);
}
failWithoutActual(
factsBuilder()
.addAll(diff.describe(differ(exceptions)))
.add(simpleFact("---"))
.add(fact(allowUnexpected ? "expected to contain at least" : "expected", expected))
.addAll(correspondence.describeForMapValues())
.add(butWas())
.addAll(exceptions.describeAsAdditionalInfo())
.build());
return ALREADY_FAILED;
}
private <V extends E> Differ<A, V> differ(Correspondence.ExceptionStore exceptions) {
return (actual, expected) -> correspondence.safeFormatDiff(actual, expected, exceptions);
}
@SuppressWarnings("unchecked") // throwing ClassCastException is the correct behaviour
private Map<?, A> castActual(Map<?, ?> actual) {
return (Map<?, A>) actual;
}
private String actualCustomStringRepresentationForPackageMembersToCall() {
return subject.actualCustomStringRepresentationForPackageMembersToCall();
}
private Fact actualContents() {
return subject.actualContents();
}
private Fact butWas() {
return subject.butWas();
}
private void failWithActual(String key, @Nullable Object value) {
subject.failWithActual(key, value);
}
private void failWithoutActual(Iterable<Fact> facts) {
subject.failWithoutActual(facts);
}
private void failWithoutActual(Fact first, Fact... rest) {
subject.failWithoutActual(first, rest);
}
static <A extends @Nullable Object, E extends @Nullable Object>
UsingCorrespondence<A, E> create(
MapSubject subject, Correspondence<? super A, ? super E> correspondence) {
return new UsingCorrespondence<>(subject, correspondence);
}
}
private Fact fullContents() {
return actualValue("full contents");
}
private Fact actualContents() {
return actualValue("actual contents");
}
static Factory<MapSubject, Map<?, ?>> maps() {
return MapSubject::new;
}
}
| UsingCorrespondence |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/StackLocator.java | {
"start": 7932,
"end": 8519
} | class
____ DEFAULT_CALLER_CLASS;
}
}
// migrated from Log4jLoggerFactory
@PerformanceSensitive
public Class<?> getCallerClass(final String fqcn, final String pkg) {
boolean next = false;
Class<?> clazz;
for (int i = 2; null != (clazz = getCallerClass(i)); i++) {
if (fqcn.equals(clazz.getName())) {
next = true;
continue;
}
if (next && clazz.getName().startsWith(pkg)) {
return clazz;
}
}
// TODO: return Object. | return |
java | redisson__redisson | redisson-hibernate/redisson-hibernate-52/src/main/java/org/redisson/hibernate/region/BaseRegion.java | {
"start": 1359,
"end": 7356
} | class ____ implements TransactionalDataRegion, GeneralDataRegion {
private final Logger logger = LoggerFactory.getLogger(getClass());
final RMapCache<Object, Object> mapCache;
final RegionFactory regionFactory;
final CacheDataDescription metadata;
final ServiceManager serviceManager;
int ttl;
int maxIdle;
int size;
boolean fallback;
volatile boolean fallbackMode;
public BaseRegion(RMapCache<Object, Object> mapCache, ServiceManager serviceManager, RegionFactory regionFactory, CacheDataDescription metadata, Properties properties, String defaultKey) {
super();
this.mapCache = mapCache;
this.regionFactory = regionFactory;
this.metadata = metadata;
this.serviceManager = serviceManager;
String maxEntries = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_ENTRIES_SUFFIX);
if (maxEntries != null) {
size = Integer.valueOf(maxEntries);
mapCache.setMaxSize(size);
}
String timeToLive = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.TTL_SUFFIX);
if (timeToLive != null) {
ttl = Integer.valueOf(timeToLive);
}
String maxIdleTime = getProperty(properties, mapCache.getName(), defaultKey, RedissonRegionFactory.MAX_IDLE_SUFFIX);
if (maxIdleTime != null) {
maxIdle = Integer.valueOf(maxIdleTime);
}
String fallbackValue = (String) properties.getOrDefault(RedissonRegionFactory.FALLBACK, "false");
fallback = Boolean.valueOf(fallbackValue);
}
private String getProperty(Properties properties, String name, String defaultKey, String suffix) {
String value = properties.getProperty(RedissonRegionFactory.CONFIG_PREFIX + name + suffix);
if (value != null) {
return value;
}
String defValue = properties.getProperty(RedissonRegionFactory.CONFIG_PREFIX + defaultKey + suffix);
if (defValue != null) {
return defValue;
}
return null;
}
private void ping() {
fallbackMode = true;
serviceManager.newTimeout(t -> {
RFuture<Boolean> future = mapCache.isExistsAsync();
future.whenComplete((r, ex) -> {
if (ex == null) {
fallbackMode = false;
} else {
ping();
}
});
}, 1, TimeUnit.SECONDS);
}
@Override
public boolean isTransactionAware() {
// TODO Auto-generated method stub
return false;
}
@Override
public CacheDataDescription getCacheDataDescription() {
return metadata;
}
@Override
public String getName() {
return mapCache.getName();
}
@Override
public void destroy() throws CacheException {
try {
mapCache.destroy();
} catch (Exception e) {
throw new CacheException(e);
}
}
@Override
public boolean contains(Object key) {
if (fallbackMode) {
return false;
}
try {
return mapCache.containsKey(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return false;
}
throw new CacheException(e);
}
}
@Override
public long getSizeInMemory() {
return mapCache.sizeInMemory();
}
@Override
public long getElementCountInMemory() {
return mapCache.size();
}
@Override
public long getElementCountOnDisk() {
return -1;
}
@Override
public Map<?, ?> toMap() {
return Collections.unmodifiableMap(mapCache);
}
@Override
public long nextTimestamp() {
return regionFactory.nextTimestamp();
}
@Override
public int getTimeout() {
// 60 seconds (normalized value)
return (1 << 12) * 60000;
}
@Override
public Object get(SharedSessionContractImplementor session, Object key) throws CacheException {
if (fallbackMode) {
return null;
}
try {
if (maxIdle == 0 && size == 0) {
return mapCache.getWithTTLOnly(key);
}
return mapCache.get(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return null;
}
throw new CacheException(e);
}
}
@Override
public void put(SharedSessionContractImplementor session, Object key, Object value) throws CacheException {
if (fallbackMode) {
return;
}
try {
mapCache.fastPut(key, value, ttl, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
@Override
public void evict(Object key) throws CacheException {
if (fallbackMode) {
return;
}
try {
mapCache.fastRemove(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
@Override
public void evictAll() throws CacheException {
if (fallbackMode) {
return;
}
try {
mapCache.clear();
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
}
| BaseRegion |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/ErrorProneOptionsTest.java | {
"start": 1468,
"end": 13035
} | class ____ {
@Test
public void nonErrorProneFlagsPlacedInRemainingArgs() {
String[] args = {"-nonErrorProneFlag", "value"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
assertThat(options.getRemainingArgs()).containsExactlyElementsIn(args);
}
@Test
public void malformedOptionThrowsProperException() {
List<String> badArgs =
Arrays.asList(
"-Xep:Foo:WARN:jfkdlsdf", // too many parts
"-Xep:", // no check name
"-Xep:Foo:FJDKFJSD"); // nonexistent severity level
badArgs.forEach(
arg -> {
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(Arrays.asList(arg)));
assertThat(expected).hasMessageThat().contains("invalid flag");
});
}
@Test
public void handlesErrorProneSeverityFlags() {
String[] args1 = {"-Xep:Check1"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args1);
ImmutableMap<String, Severity> expectedSeverityMap =
ImmutableMap.of("Check1", Severity.DEFAULT);
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
String[] args2 = {"-Xep:Check1", "-Xep:Check2:OFF", "-Xep:Check3:WARN"};
options = ErrorProneOptions.processArgs(args2);
expectedSeverityMap =
ImmutableMap.<String, Severity>builder()
.put("Check1", Severity.DEFAULT)
.put("Check2", Severity.OFF)
.put("Check3", Severity.WARN)
.buildOrThrow();
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
}
@Test
public void handlesErrorProneCustomFlags() {
String[] args = {"-XepOpt:Flag1", "-XepOpt:Flag2=Value2", "-XepOpt:Flag3=a,b,c"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, String> expectedFlagsMap =
ImmutableMap.<String, String>builder()
.put("Flag1", "true")
.put("Flag2", "Value2")
.put("Flag3", "a,b,c")
.buildOrThrow();
assertThat(options.getFlags().getFlagsMap()).isEqualTo(expectedFlagsMap);
}
@Test
public void combineErrorProneFlagsWithNonErrorProneFlags() {
String[] args = {
"-classpath",
"/this/is/classpath",
"-verbose",
"-Xep:Check1:WARN",
"-XepOpt:Check1:Flag1=Value1",
"-Xep:Check2:ERROR"
};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
String[] expectedRemainingArgs = {"-classpath", "/this/is/classpath", "-verbose"};
assertThat(options.getRemainingArgs()).containsExactlyElementsIn(expectedRemainingArgs);
ImmutableMap<String, Severity> expectedSeverityMap =
ImmutableMap.<String, Severity>builder()
.put("Check1", Severity.WARN)
.put("Check2", Severity.ERROR)
.buildOrThrow();
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
ImmutableMap<String, String> expectedFlagsMap = ImmutableMap.of("Check1:Flag1", "Value1");
assertThat(options.getFlags().getFlagsMap()).containsExactlyEntriesIn(expectedFlagsMap);
}
@Test
public void lastSeverityFlagWins() {
String[] args = {"-Xep:Check1:ERROR", "-Xep:Check1:OFF"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, Severity> expectedSeverityMap = ImmutableMap.of("Check1", Severity.OFF);
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
}
@Test
public void lastCustomFlagWins() {
String[] args = {"-XepOpt:Flag1=First", "-XepOpt:Flag1=Second"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, String> expectedFlagsMap = ImmutableMap.of("Flag1", "Second");
assertThat(options.getFlags().getFlagsMap()).containsExactlyEntriesIn(expectedFlagsMap);
}
@Test
public void recognizesAllChecksAsWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllDisabledChecksAsWarnings"});
assertThat(options.isEnableAllChecksAsWarnings()).isTrue();
}
@Test
public void recognizesDemoteErrorToWarning() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllErrorsAsWarnings"});
assertThat(options.isDropErrorsToWarnings()).isTrue();
}
@Test
public void recognizesAllSuggestionsAsWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllSuggestionsAsWarnings"});
assertThat(options.isSuggestionsAsWarnings()).isTrue();
}
@Test
public void recognizesDisableAllChecks() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepDisableAllChecks"});
assertThat(options.isDisableAllChecks()).isTrue();
}
@Test
public void recognizesCompilingTestOnlyCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepCompilingTestOnlyCode"});
assertThat(options.isTestOnlyTarget()).isTrue();
}
@Test
public void recognizesCompilingPubliclyVisibleCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepCompilingPubliclyVisibleCode"});
assertThat(options.isPubliclyVisibleTarget()).isTrue();
}
@Test
public void recognizesDisableAllWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepDisableAllWarnings"});
assertThat(options.isDisableAllWarnings()).isTrue();
}
@Test
public void recognizesVisitSuppressedCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepIgnoreSuppressionAnnotations"});
assertThat(options.isIgnoreSuppressionAnnotations()).isTrue();
}
@Test
public void recognizesExcludedPaths() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepExcludedPaths:(.*/)?(build/generated|other_output)/.*\\.java"});
Pattern excludedPattern = options.getExcludedPattern();
assertThat(excludedPattern).isNotNull();
assertThat(excludedPattern.matcher("fizz/build/generated/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("fizz/bazz/generated/Gen.java").matches()).isFalse();
assertThat(excludedPattern.matcher("fizz/abuild/generated/Gen.java").matches()).isFalse();
assertThat(excludedPattern.matcher("other_output/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("foo/other_output/subdir/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("foo/other_output/subdir/Gen.cpp").matches()).isFalse();
}
@Test
public void recognizesPatch() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepPatchLocation:IN_PLACE", "-XepPatchChecks:FooBar,MissingOverride"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().namedCheckers())
.containsExactly("MissingOverride", "FooBar");
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
options =
ErrorProneOptions.processArgs(
new String[] {
"-XepPatchLocation:/some/base/dir", "-XepPatchChecks:FooBar,MissingOverride"
});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isFalse();
assertThat(options.patchingOptions().baseDirectory()).isEqualTo("/some/base/dir");
assertThat(options.patchingOptions().namedCheckers())
.containsExactly("MissingOverride", "FooBar");
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
options = ErrorProneOptions.processArgs(new String[] {});
assertThat(options.patchingOptions().doRefactor()).isFalse();
}
@Test
public void throwsExceptionWithBadPatchArgs() {
assertThrows(
InvalidCommandLineOptionException.class,
() ->
ErrorProneOptions.processArgs(new String[] {"-XepPatchChecks:FooBar,MissingOverride"}));
}
@Test
public void recognizesRefaster() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepPatchChecks:refaster:/foo/bar", "-XepPatchLocation:IN_PLACE"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().customRefactorer()).isPresent();
}
@Test
public void understandsEmptySetOfNamedCheckers() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchLocation:IN_PLACE"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().namedCheckers()).isEmpty();
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
options =
ErrorProneOptions.processArgs(
new String[] {"-XepPatchLocation:IN_PLACE", "-XepPatchChecks:"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().namedCheckers()).isEmpty();
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
}
@Test
public void importOrder_staticFirst() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:static-first"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.STATIC_FIRST_ORGANIZER);
}
@Test
public void importOrder_staticLast() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:static-last"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.STATIC_LAST_ORGANIZER);
}
@Test
public void importOrder_androidStaticFirst() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:android-static-first"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.ANDROID_STATIC_FIRST_ORGANIZER);
}
@Test
public void importOrder_androidStaticLast() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:android-static-last"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.ANDROID_STATIC_LAST_ORGANIZER);
}
@Test
public void noSuchXepFlag() {
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(new String[] {"-XepNoSuchFlag"}));
}
@Test
public void severityOrder() {
for (Collection<String> permutation :
Collections2.permutations(ImmutableList.of("A", "B", "C"))) {
ImmutableMap<String, Severity> severityMap =
permutation.stream().collect(toImmutableMap(x -> x, x -> Severity.ERROR));
ErrorProneOptions options =
ErrorProneOptions.processArgs(
permutation.stream()
.map(x -> String.format("-Xep:%s:ERROR", x))
.collect(toImmutableList()));
assertThat(options.getSeverityMap()).containsExactlyEntriesIn(severityMap).inOrder();
}
}
}
| ErrorProneOptionsTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidThrowsLinkTest.java | {
"start": 996,
"end": 1346
} | class ____ {
private final BugCheckerRefactoringTestHelper refactoring =
BugCheckerRefactoringTestHelper.newInstance(InvalidThrowsLink.class, getClass());
@Test
public void positive() {
refactoring
.addInputLines(
"Test.java",
"""
import java.io.IOException;
| InvalidThrowsLinkTest |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedTransformerRegistryTest.java | {
"start": 1756,
"end": 5427
} | class ____ extends ManagementTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(ManagedTransformerRegistryTest.class);
@Test
public void testManageTransformerRegistry() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
// get the stats for the route
MBeanServer mbeanServer = getMBeanServer();
Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=services,*"), null);
List<ObjectName> list = new ArrayList<>(set);
ObjectName on = null;
for (ObjectName name : list) {
if (name.getCanonicalName().contains("DefaultTransformerRegistry")) {
on = name;
break;
}
}
assertNotNull(on, "Should have found TransformerRegistry");
Integer max = (Integer) mbeanServer.getAttribute(on, "MaximumCacheSize");
assertEquals(1000, max.intValue());
Integer current = (Integer) mbeanServer.getAttribute(on, "Size");
assertEquals(2, current.intValue());
current = (Integer) mbeanServer.getAttribute(on, "StaticSize");
assertEquals(2, current.intValue());
current = (Integer) mbeanServer.getAttribute(on, "DynamicSize");
assertEquals(0, current.intValue());
String source = (String) mbeanServer.getAttribute(on, "Source");
assertTrue(source.startsWith("TransformerRegistry"));
assertTrue(source.endsWith("capacity: 1000]"));
TabularData data = (TabularData) mbeanServer.invoke(on, "listTransformers", null, null);
for (Object row : data.values()) {
CompositeData composite = (CompositeData) row;
String name = (String) composite.get("name");
String from = (String) composite.get("from");
String to = (String) composite.get("to");
String description = (String) composite.get("description");
boolean isStatic = (boolean) composite.get("static");
boolean isDynamic = (boolean) composite.get("dynamic");
LOG.info("[{}][{}][{}][{}][{}][{}]", name, from, to, isStatic, isDynamic, description);
if (description.startsWith("ProcessorTransformer")) {
assertNull(name);
assertEquals("xml:foo", from);
assertEquals("json:bar", to);
} else if (description.startsWith("DataFormatTransformer")) {
assertNull(name);
assertEquals("java:" + ManagedTransformerRegistryTest.class.getName(), from);
assertEquals("xml:test", to);
} else if (description.startsWith("MyTransformer")) {
assertEquals("custom", name);
assertEquals("camel:any", from);
assertEquals("camel:any", to);
} else {
fail("Unexpected transformer:" + description);
}
}
assertEquals(2, data.size());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
transformer()
.fromType("xml:foo")
.toType("json:bar")
.withUri("direct:transformer");
transformer()
.name("custom")
.withJava(MyTransformer.class);
from("direct:start").to("mock:result");
}
};
}
public static | ManagedTransformerRegistryTest |
java | apache__flink | flink-libraries/flink-cep/src/main/java/org/apache/flink/cep/nfa/aftermatch/SkipToElementStrategy.java | {
"start": 1162,
"end": 4533
} | class ____ extends AfterMatchSkipStrategy {
private static final long serialVersionUID = 7127107527654629026L;
private final String patternName;
private final boolean shouldThrowException;
SkipToElementStrategy(String patternName, boolean shouldThrowException) {
this.patternName = checkNotNull(patternName);
this.shouldThrowException = shouldThrowException;
}
@Override
public boolean isSkipStrategy() {
return true;
}
@Override
protected boolean shouldPrune(EventId startEventID, EventId pruningId) {
return startEventID != null && startEventID.compareTo(pruningId) < 0;
}
@Override
protected EventId getPruningId(Collection<Map<String, List<EventId>>> match) {
EventId pruningId = null;
for (Map<String, List<EventId>> resultMap : match) {
List<EventId> pruningPattern = resultMap.get(patternName);
if (pruningPattern == null || pruningPattern.isEmpty()) {
if (shouldThrowException) {
throw new FlinkRuntimeException(
String.format(
"Could not skip to %s. No such element in the found match %s",
patternName, resultMap));
}
} else {
pruningId = max(pruningId, pruningPattern.get(getIndex(pruningPattern.size())));
}
if (shouldThrowException) {
EventId startEvent =
resultMap.values().stream()
.flatMap(Collection::stream)
.min(EventId::compareTo)
.orElseThrow(
() ->
new IllegalStateException(
"Cannot prune based on empty match"));
if (pruningId != null && pruningId.equals(startEvent)) {
throw new FlinkRuntimeException("Could not skip to first element of a match.");
}
}
}
return pruningId;
}
@Override
public Optional<String> getPatternName() {
return Optional.of(patternName);
}
/**
* Tells which element from the list of events mapped to *PatternName* to use.
*
* @param size number of elements mapped to the *PatternName*
* @return index of event mapped to *PatternName* to use for pruning
*/
abstract int getIndex(int size);
/**
* Enables throwing exception if no events mapped to the *PatternName*. If not enabled and no
* events were mapped, {@link NoSkipStrategy} will be used
*/
public abstract SkipToElementStrategy throwExceptionOnMiss();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SkipToElementStrategy that = (SkipToElementStrategy) o;
return shouldThrowException == that.shouldThrowException
&& Objects.equals(patternName, that.patternName);
}
@Override
public int hashCode() {
return Objects.hash(patternName, shouldThrowException);
}
}
| SkipToElementStrategy |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/StringUtils.java | {
"start": 5071,
"end": 5312
} | class ____ sample code in their Javadoc comments to explain their operation.
* The symbol {@code *} is used to indicate any input including {@code null}.</p>
*
* <p>#ThreadSafe#</p>
* @see String
* @since 1.0
*/
//@Immutable
public | include |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/short2darrays/Short2DArraysBaseTest.java | {
"start": 1125,
"end": 1724
} | class ____ {
protected short[][] actual;
protected Failures failures;
protected Short2DArrays short2DArrays;
protected Arrays2D arrays2d;
protected AssertionInfo info = TestData.someInfo();
@BeforeEach
public void setUp() {
failures = spy(Failures.instance());
short2DArrays = new Short2DArrays();
writeField(short2DArrays, "failures", failures);
arrays2d = mock(Arrays2D.class);
short2DArrays.setArrays(arrays2d);
initActualArray();
}
protected void initActualArray() {
actual = new short[][] { { 0, 2, 4 }, { 6, 8, 10 } };
}
}
| Short2DArraysBaseTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/test/java/org/apache/hadoop/yarn/server/router/clientrm/TestRouterYarnClientUtils.java | {
"start": 3844,
"end": 3888
} | class ____ RouterYarnClientUtils.
*/
public | for |
java | google__guava | android/guava-tests/test/com/google/common/io/TestReader.java | {
"start": 982,
"end": 1391
} | class ____ extends FilterReader {
private final TestInputStream in;
public TestReader(TestOption... options) throws IOException {
this(new TestInputStream(new ByteArrayInputStream(new byte[10]), options));
}
public TestReader(TestInputStream in) {
super(new InputStreamReader(checkNotNull(in), UTF_8));
this.in = in;
}
public boolean closed() {
return in.closed();
}
}
| TestReader |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/GetApplicationAttemptsRequestPBImpl.java | {
"start": 1555,
"end": 4109
} | class ____ extends
GetApplicationAttemptsRequest {
GetApplicationAttemptsRequestProto proto = GetApplicationAttemptsRequestProto
.getDefaultInstance();
GetApplicationAttemptsRequestProto.Builder builder = null;
boolean viaProto = false;
ApplicationId applicationId = null;
public GetApplicationAttemptsRequestPBImpl() {
builder = GetApplicationAttemptsRequestProto.newBuilder();
}
public GetApplicationAttemptsRequestPBImpl(
GetApplicationAttemptsRequestProto proto) {
this.proto = proto;
viaProto = true;
}
public GetApplicationAttemptsRequestProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
private void mergeLocalToBuilder() {
if (applicationId != null) {
builder.setApplicationId(convertToProtoFormat(this.applicationId));
}
}
private void mergeLocalToProto() {
if (viaProto) {
maybeInitBuilder();
}
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = GetApplicationAttemptsRequestProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public ApplicationId getApplicationId() {
if (this.applicationId != null) {
return this.applicationId;
}
GetApplicationAttemptsRequestProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasApplicationId()) {
return null;
}
this.applicationId = convertFromProtoFormat(p.getApplicationId());
return this.applicationId;
}
@Override
public void setApplicationId(ApplicationId applicationId) {
maybeInitBuilder();
if (applicationId == null) {
builder.clearApplicationId();
}
this.applicationId = applicationId;
}
private ApplicationIdPBImpl convertFromProtoFormat(ApplicationIdProto p) {
return new ApplicationIdPBImpl(p);
}
private ApplicationIdProto convertToProtoFormat(ApplicationId t) {
return ((ApplicationIdPBImpl) t).getProto();
}
}
| GetApplicationAttemptsRequestPBImpl |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java | {
"start": 12343,
"end": 13245
} | class ____ resources with the given name
return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
}
} else {
// Generally only look for a pattern after a prefix here,
// and on Tomcat only after the "*/" separator for its "war:" protocol.
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
locationPattern.indexOf(':') + 1);
if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
// a file pattern
return findPathMatchingResources(locationPattern);
} else {
// a single resource with the given name
return new Resource[]{getResourceLoader().getResource(locationPattern)};
}
}
}
/**
* Find all | path |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/impl/consumer/ConsumeMessagePopConcurrentlyService.java | {
"start": 14257,
"end": 20931
} | class ____ implements Runnable {
private final List<MessageExt> msgs;
private final PopProcessQueue processQueue;
private final MessageQueue messageQueue;
private long popTime = 0;
private long invisibleTime = 0;
public ConsumeRequest(List<MessageExt> msgs, PopProcessQueue processQueue, MessageQueue messageQueue) {
this.msgs = msgs;
this.processQueue = processQueue;
this.messageQueue = messageQueue;
try {
String extraInfo = msgs.get(0).getProperty(MessageConst.PROPERTY_POP_CK);
String[] extraInfoStrs = ExtraInfoUtil.split(extraInfo);
popTime = ExtraInfoUtil.getPopTime(extraInfoStrs);
invisibleTime = ExtraInfoUtil.getInvisibleTime(extraInfoStrs);
} catch (Throwable t) {
log.error("parse extra info error. msg:" + msgs.get(0), t);
}
}
public boolean isPopTimeout() {
if (msgs.size() == 0 || popTime <= 0 || invisibleTime <= 0) {
return true;
}
long current = System.currentTimeMillis();
return current - popTime >= invisibleTime;
}
public List<MessageExt> getMsgs() {
return msgs;
}
public PopProcessQueue getPopProcessQueue() {
return processQueue;
}
@Override
public void run() {
if (this.processQueue.isDropped()) {
log.info("the message queue not be able to consume, because it's dropped(pop). group={} {}", ConsumeMessagePopConcurrentlyService.this.consumerGroup, this.messageQueue);
return;
}
if (isPopTimeout()) {
log.info("the pop message time out so abort consume. popTime={} invisibleTime={}, group={} {}",
popTime, invisibleTime, ConsumeMessagePopConcurrentlyService.this.consumerGroup, this.messageQueue);
processQueue.decFoundMsg(-msgs.size());
return;
}
MessageListenerConcurrently listener = ConsumeMessagePopConcurrentlyService.this.messageListener;
ConsumeConcurrentlyContext context = new ConsumeConcurrentlyContext(messageQueue);
ConsumeConcurrentlyStatus status = null;
defaultMQPushConsumerImpl.resetRetryAndNamespace(msgs, defaultMQPushConsumer.getConsumerGroup());
ConsumeMessageContext consumeMessageContext = null;
if (ConsumeMessagePopConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
consumeMessageContext = new ConsumeMessageContext();
consumeMessageContext.setNamespace(defaultMQPushConsumer.getNamespace());
consumeMessageContext.setConsumerGroup(defaultMQPushConsumer.getConsumerGroup());
consumeMessageContext.setProps(new HashMap<>());
consumeMessageContext.setMq(messageQueue);
consumeMessageContext.setMsgList(msgs);
consumeMessageContext.setSuccess(false);
ConsumeMessagePopConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookBefore(consumeMessageContext);
}
long beginTimestamp = System.currentTimeMillis();
boolean hasException = false;
ConsumeReturnType returnType = ConsumeReturnType.SUCCESS;
try {
if (msgs != null && !msgs.isEmpty()) {
for (MessageExt msg : msgs) {
MessageAccessor.setConsumeStartTimeStamp(msg, String.valueOf(System.currentTimeMillis()));
}
}
status = listener.consumeMessage(Collections.unmodifiableList(msgs), context);
} catch (Throwable e) {
log.warn("consumeMessage exception: {} Group: {} Msgs: {} MQ: {}",
UtilAll.exceptionSimpleDesc(e),
ConsumeMessagePopConcurrentlyService.this.consumerGroup,
msgs,
messageQueue);
hasException = true;
}
long consumeRT = System.currentTimeMillis() - beginTimestamp;
if (null == status) {
if (hasException) {
returnType = ConsumeReturnType.EXCEPTION;
} else {
returnType = ConsumeReturnType.RETURNNULL;
}
} else if (consumeRT >= invisibleTime * 1000) {
returnType = ConsumeReturnType.TIME_OUT;
} else if (ConsumeConcurrentlyStatus.RECONSUME_LATER == status) {
returnType = ConsumeReturnType.FAILED;
} else if (ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status) {
returnType = ConsumeReturnType.SUCCESS;
}
if (null == status) {
log.warn("consumeMessage return null, Group: {} Msgs: {} MQ: {}",
ConsumeMessagePopConcurrentlyService.this.consumerGroup,
msgs,
messageQueue);
status = ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
if (ConsumeMessagePopConcurrentlyService.this.defaultMQPushConsumerImpl.hasHook()) {
consumeMessageContext.getProps().put(MixAll.CONSUME_CONTEXT_TYPE, returnType.name());
consumeMessageContext.setStatus(status.toString());
consumeMessageContext.setSuccess(ConsumeConcurrentlyStatus.CONSUME_SUCCESS == status);
consumeMessageContext.setAccessChannel(defaultMQPushConsumer.getAccessChannel());
ConsumeMessagePopConcurrentlyService.this.defaultMQPushConsumerImpl.executeHookAfter(consumeMessageContext);
}
ConsumeMessagePopConcurrentlyService.this.getConsumerStatsManager()
.incConsumeRT(ConsumeMessagePopConcurrentlyService.this.consumerGroup, messageQueue.getTopic(), consumeRT);
if (!processQueue.isDropped() && !isPopTimeout()) {
ConsumeMessagePopConcurrentlyService.this.processConsumeResult(status, context, this);
} else {
if (msgs != null) {
processQueue.decFoundMsg(-msgs.size());
}
log.warn("processQueue invalid or popTimeout. isDropped={}, isPopTimeout={}, messageQueue={}, msgs={}",
processQueue.isDropped(), isPopTimeout(), messageQueue, msgs);
}
}
public MessageQueue getMessageQueue() {
return messageQueue;
}
}
}
| ConsumeRequest |
java | elastic__elasticsearch | x-pack/plugin/transform/src/internalClusterTest/java/org/elasticsearch/xpack/transform/checkpoint/TransformGetCheckpointIT.java | {
"start": 1502,
"end": 9521
} | class ____ extends TransformSingleNodeTestCase {
public void testGetCheckpoint() throws Exception {
final String indexNamePrefix = "test_index-";
final int shards = randomIntBetween(1, 5);
var indices = indices(indexNamePrefix, randomIntBetween(1, 5));
for (var index : indices) {
indicesAdmin().prepareCreate(index).setSettings(indexSettings(shards, 1)).get();
}
final GetCheckpointAction.Request request = new GetCheckpointAction.Request(
new String[] { indexNamePrefix + "*" },
IndicesOptions.LENIENT_EXPAND_OPEN,
null,
null,
TimeValue.timeValueSeconds(5)
);
final GetCheckpointAction.Response response = client().execute(GetCheckpointAction.INSTANCE, request).get();
assertEquals(indices.size(), response.getCheckpoints().size());
// empty indices should report -1 as sequence id
assertFalse(
response.getCheckpoints().entrySet().stream().anyMatch(entry -> Arrays.stream(entry.getValue()).anyMatch(l -> l != -1L))
);
final int docsToCreatePerShard = randomIntBetween(0, 10);
for (int d = 0; d < docsToCreatePerShard; ++d) {
for (var index : indices) {
for (int j = 0; j < shards; ++j) {
prepareIndex(index).setSource("{" + "\"field\":" + j + "}", XContentType.JSON).get();
}
}
}
indicesAdmin().refresh(new RefreshRequest(indexNamePrefix + "*"));
final GetCheckpointAction.Response response2 = client().execute(GetCheckpointAction.INSTANCE, request).get();
assertEquals(indices.size(), response2.getCheckpoints().size());
// check the sum, counting starts with 0, so we have to take docsToCreatePerShard - 1
long checkpointSum = response2.getCheckpoints().values().stream().map(l -> Arrays.stream(l).sum()).mapToLong(Long::valueOf).sum();
assertEquals(
"Expected "
+ (docsToCreatePerShard - 1) * shards * indices.size()
+ " as sum of "
+ response2.getCheckpoints()
.entrySet()
.stream()
.map(e -> e.getKey() + ": {" + Strings.arrayToCommaDelimitedString(Arrays.stream(e.getValue()).boxed().toArray()) + "}")
.collect(Collectors.joining(",")),
(docsToCreatePerShard - 1) * shards * indices.size(),
checkpointSum
);
final IndicesStatsResponse statsResponse = indicesAdmin().prepareStats(indexNamePrefix + "*").get();
assertEquals(
"Checkpoint API and indices stats don't match",
Arrays.stream(statsResponse.getShards())
.filter(i -> i.getShardRouting().primary())
.sorted(Comparator.comparingInt(value -> value.getShardRouting().id()))
.mapToLong(s -> s.getSeqNoStats().getGlobalCheckpoint())
.filter(Objects::nonNull)
.sum(),
checkpointSum
);
deleteIndices(indices);
}
public void testGetCheckpointWithQueryThatFiltersOutEverything() throws Exception {
final String indexNamePrefix = "test_index-";
var indices = indices(indexNamePrefix, randomIntBetween(1, 5));
final int shards = randomIntBetween(1, 5);
final int docsToCreatePerShard = randomIntBetween(0, 10);
for (int i = 0; i < indices.size(); ++i) {
var index = indices.get(i);
indicesAdmin().prepareCreate(index)
.setSettings(indexSettings(shards, 1))
.setMapping("field", "type=long", "@timestamp", "type=date")
.get();
for (int j = 0; j < shards; ++j) {
for (int d = 0; d < docsToCreatePerShard; ++d) {
client().prepareIndex(index)
.setSource(Strings.format("{ \"field\":%d, \"@timestamp\": %d }", j, 10_000_000 + d + i + j), XContentType.JSON)
.get();
}
}
}
indicesAdmin().refresh(new RefreshRequest(indexNamePrefix + "*"));
final GetCheckpointAction.Request request = new GetCheckpointAction.Request(
new String[] { indexNamePrefix + "*" },
IndicesOptions.LENIENT_EXPAND_OPEN,
// This query does not match any documents
QueryBuilders.rangeQuery("@timestamp").gte(20_000_000),
null,
TimeValue.timeValueSeconds(5)
);
final GetCheckpointAction.Response response = client().execute(GetCheckpointAction.INSTANCE, request).get();
assertThat("Response was: " + response.getCheckpoints(), response.getCheckpoints(), is(anEmptyMap()));
deleteIndices(indices);
}
public void testGetCheckpointWithMissingIndex() throws Exception {
GetCheckpointAction.Request request = new GetCheckpointAction.Request(
new String[] { "test_index_missing" },
IndicesOptions.LENIENT_EXPAND_OPEN,
null,
null,
TimeValue.timeValueSeconds(5)
);
GetCheckpointAction.Response response = client().execute(GetCheckpointAction.INSTANCE, request).get();
assertThat("Response was: " + response.getCheckpoints(), response.getCheckpoints(), is(anEmptyMap()));
request = new GetCheckpointAction.Request(
new String[] { "test_index_missing-*" },
IndicesOptions.LENIENT_EXPAND_OPEN,
null,
null,
TimeValue.timeValueSeconds(5)
);
response = client().execute(GetCheckpointAction.INSTANCE, request).get();
assertThat("Response was: " + response.getCheckpoints(), response.getCheckpoints(), is(anEmptyMap()));
}
public void testGetCheckpointTimeoutExceeded() throws Exception {
final String indexNamePrefix = "test_index-";
var indices = indices(indexNamePrefix, 100);
final int shards = 5;
for (var index : indices) {
indicesAdmin().prepareCreate(index).setSettings(indexSettings(shards, 0)).get();
}
final GetCheckpointAction.Request request = new GetCheckpointAction.Request(
new String[] { indexNamePrefix + "*" },
IndicesOptions.LENIENT_EXPAND_OPEN,
null,
null,
TimeValue.ZERO
);
CountDownLatch latch = new CountDownLatch(1);
SetOnce<Exception> finalException = new SetOnce<>();
client().execute(GetCheckpointAction.INSTANCE, request, ActionListener.wrap(r -> latch.countDown(), e -> {
finalException.set(e);
latch.countDown();
}));
assertTrue(latch.await(10, TimeUnit.SECONDS));
Exception e = finalException.get();
if (e != null) {
assertThat(e, is(instanceOf(ElasticsearchTimeoutException.class)));
assertThat(
"Message was: " + e.getMessage(),
e.getMessage(),
startsWith("Transform checkpointing timed out on node [node_s_0] after [0ms]")
);
} else {
// Due to system clock usage, the timeout does not always occur where it should.
// We cannot mock the clock so we just have to live with it.
}
deleteIndices(indices);
}
private List<String> indices(String prefix, int numberOfIndices) {
return IntStream.range(0, numberOfIndices).mapToObj(i -> prefix + i).toList();
}
private void deleteIndices(List<String> indices) {
try {
indicesAdmin().prepareDelete(indices.toArray(new String[0])).get();
} catch (Exception e) {
// we can fail to clean up the indices, but this wouldn't impact other tests since the node gets torn down anyway
// the index delete is to help the node tear down go smoother
}
}
}
| TransformGetCheckpointIT |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java | {
"start": 9565,
"end": 9695
} | class ____ {
@Bean
TestBean m() {
return new TestBean();
}
}
@Configuration
@Import(ThirdLevel.class)
static | FirstLevel |
java | google__error-prone | core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java | {
"start": 19419,
"end": 19529
} | class ____ {
Void foo() {
return null;
}
@ | AddAnnotation |
java | apache__flink | flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/sink/writer/BufferedRequestState.java | {
"start": 1493,
"end": 3018
} | class ____<RequestEntryT extends Serializable> implements Serializable {
private final List<RequestEntryWrapper<RequestEntryT>> bufferedRequestEntries;
private final long stateSize;
@Deprecated
public BufferedRequestState(Deque<RequestEntryWrapper<RequestEntryT>> bufferedRequestEntries) {
this.bufferedRequestEntries = new ArrayList<>(bufferedRequestEntries);
this.stateSize = calculateStateSize();
}
public BufferedRequestState(List<RequestEntryWrapper<RequestEntryT>> bufferedRequestEntries) {
this.bufferedRequestEntries = new ArrayList<>(bufferedRequestEntries);
this.stateSize = calculateStateSize();
}
public BufferedRequestState(RequestBuffer<RequestEntryT> requestBuffer) {
this.bufferedRequestEntries = new ArrayList<>(requestBuffer.getBufferedState());
this.stateSize = calculateStateSize();
}
public List<RequestEntryWrapper<RequestEntryT>> getBufferedRequestEntries() {
return bufferedRequestEntries;
}
public long getStateSize() {
return stateSize;
}
private long calculateStateSize() {
long stateSize = 0;
for (RequestEntryWrapper<RequestEntryT> requestEntryWrapper : bufferedRequestEntries) {
stateSize += requestEntryWrapper.getSize();
}
return stateSize;
}
public static <T extends Serializable> BufferedRequestState<T> emptyState() {
return new BufferedRequestState<>(Collections.emptyList());
}
}
| BufferedRequestState |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/state/ttl/mock/MockInternalListState.java | {
"start": 1186,
"end": 2276
} | class ____<K, N, T> extends MockInternalMergingState<K, N, T, List<T>, Iterable<T>>
implements InternalListState<K, N, T> {
private MockInternalListState() {
super(ArrayList::new);
}
@Override
public void update(List<T> elements) {
updateInternal(elements);
}
@Override
public void addAll(List<T> elements) {
getInternal().addAll(elements);
}
@Override
List<T> mergeState(List<T> acc, List<T> nAcc) {
acc = new ArrayList<>(acc);
acc.addAll(nAcc);
return acc;
}
@Override
public Iterable<T> get() {
return getInternal();
}
@Override
public void add(T element) {
getInternal().add(element);
}
@Override
public void clear() {
getInternal().clear();
}
@SuppressWarnings({"unchecked", "unused"})
static <N, T, S extends State, IS extends S> IS createState(
TypeSerializer<N> namespaceSerializer, StateDescriptor<S, T> stateDesc) {
return (IS) new MockInternalListState<>();
}
}
| MockInternalListState |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/state/operator/restore/StreamOperatorSnapshotRestoreTest.java | {
"start": 4326,
"end": 4788
} | class ____ extends TestLogger {
private static final int ONLY_JM_RECOVERY = 0;
private static final int TM_AND_JM_RECOVERY = 1;
private static final int TM_REMOVE_JM_RECOVERY = 2;
private static final int JM_REMOVE_TM_RECOVERY = 3;
private static final int MAX_PARALLELISM = 10;
protected static TemporaryFolder temporaryFolder;
@Parameterized.Parameter public StateBackendEnum stateBackendEnum;
| StreamOperatorSnapshotRestoreTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr12526Tests.java | {
"start": 3155,
"end": 3603
} | class ____ implements Service {
private DependencyTwo dependency;
@Override
public void doStuff() {
if (dependency == null) {
throw new IllegalStateException("SecondService: dependency is null");
}
}
@Resource(name = "dependencyTwo")
public void setDependency(DependencyTwo dependency) {
this.dependency = dependency;
}
public DependencyTwo getDependency() {
return dependency;
}
}
public static | SecondService |
java | apache__flink | flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/state/rocksdb/snapshot/RocksIncrementalSnapshotStrategyTest.java | {
"start": 2729,
"end": 9788
} | class ____ {
@TempDir public Path tmp;
@RegisterExtension public RocksDBExtension rocksDBExtension = new RocksDBExtension();
// Verify the next checkpoint is still incremental after a savepoint completed.
@Test
void testCheckpointIsIncremental() throws Exception {
try (CloseableRegistry closeableRegistry = new CloseableRegistry();
RocksIncrementalSnapshotStrategy<?> checkpointSnapshotStrategy =
createSnapshotStrategy()) {
FsCheckpointStreamFactory checkpointStreamFactory = createFsCheckpointStreamFactory();
// make and notify checkpoint with id 1
snapshot(1L, checkpointSnapshotStrategy, checkpointStreamFactory, closeableRegistry);
checkpointSnapshotStrategy.notifyCheckpointComplete(1L);
// notify savepoint with id 2
checkpointSnapshotStrategy.notifyCheckpointComplete(2L);
// make checkpoint with id 3
IncrementalRemoteKeyedStateHandle incrementalRemoteKeyedStateHandle3 =
snapshot(
3L,
checkpointSnapshotStrategy,
checkpointStreamFactory,
closeableRegistry);
// If 3rd checkpoint's full size > checkpointed size, it means 3rd checkpoint is
// incremental.
assertThat(incrementalRemoteKeyedStateHandle3.getStateSize())
.isGreaterThan(incrementalRemoteKeyedStateHandle3.getCheckpointedSize());
}
}
@Test
void testCheckpointIsIncrementalWithLateNotification() throws Exception {
try (CloseableRegistry closeableRegistry = new CloseableRegistry();
RocksIncrementalSnapshotStrategy<?> checkpointSnapshotStrategy =
createSnapshotStrategy()) {
FsCheckpointStreamFactory checkpointStreamFactory = createFsCheckpointStreamFactory();
// make and checkpoint with id 1
snapshot(1L, checkpointSnapshotStrategy, checkpointStreamFactory, closeableRegistry);
// make and checkpoint with id 2
snapshot(2L, checkpointSnapshotStrategy, checkpointStreamFactory, closeableRegistry);
// Late notify checkpoint with id 1
checkpointSnapshotStrategy.notifyCheckpointComplete(1L);
// make checkpoint with id 3, based on checkpoint 1
IncrementalRemoteKeyedStateHandle incrementalRemoteKeyedStateHandle3 =
snapshot(
3L,
checkpointSnapshotStrategy,
checkpointStreamFactory,
closeableRegistry);
// Late notify checkpoint with id 2
checkpointSnapshotStrategy.notifyCheckpointComplete(2L);
// 3rd checkpoint is based on 1st checkpoint, BUT the 2nd checkpoint re-uploaded the 1st
// one, so it should be based on nothing, thus this is effectively a full checkpoint.
assertThat(incrementalRemoteKeyedStateHandle3.getStateSize())
.isEqualTo(incrementalRemoteKeyedStateHandle3.getCheckpointedSize());
}
}
public RocksIncrementalSnapshotStrategy<?> createSnapshotStrategy()
throws IOException, RocksDBException {
ColumnFamilyHandle columnFamilyHandle = rocksDBExtension.createNewColumnFamily("test");
RocksDB rocksDB = rocksDBExtension.getRocksDB();
byte[] key = "checkpoint".getBytes();
byte[] val = "incrementalTest".getBytes();
rocksDB.put(columnFamilyHandle, key, val);
// construct RocksIncrementalSnapshotStrategy
long lastCompletedCheckpointId = -1L;
ResourceGuard rocksDBResourceGuard = new ResourceGuard();
SortedMap<Long, Collection<HandleAndLocalPath>> materializedSstFiles = new TreeMap<>();
LinkedHashMap<String, RocksDBKeyedStateBackend.RocksDbKvStateInfo> kvStateInformation =
new LinkedHashMap<>();
RocksDBStateUploader rocksDBStateUploader =
new RocksDBStateUploader(
RocksDBOptions.CHECKPOINT_TRANSFER_THREAD_NUM.defaultValue());
int keyGroupPrefixBytes =
CompositeKeySerializationUtils.computeRequiredBytesInKeyGroupPrefix(2);
RegisteredKeyValueStateBackendMetaInfo<Integer, ArrayList<Integer>> metaInfo =
new RegisteredKeyValueStateBackendMetaInfo<>(
StateDescriptor.Type.VALUE,
"test",
IntSerializer.INSTANCE,
new ArrayListSerializer<>(IntSerializer.INSTANCE));
RocksDBKeyedStateBackend.RocksDbKvStateInfo rocksDbKvStateInfo =
new RocksDBKeyedStateBackend.RocksDbKvStateInfo(columnFamilyHandle, metaInfo);
kvStateInformation.putIfAbsent("test", rocksDbKvStateInfo);
return new RocksIncrementalSnapshotStrategy<>(
rocksDB,
rocksDBResourceGuard,
IntSerializer.INSTANCE,
kvStateInformation,
new KeyGroupRange(0, 1),
keyGroupPrefixBytes,
TestLocalRecoveryConfig.disabled(),
TempDirUtils.newFolder(tmp),
UUID.randomUUID(),
materializedSstFiles,
rocksDBStateUploader,
lastCompletedCheckpointId);
}
public FsCheckpointStreamFactory createFsCheckpointStreamFactory() throws IOException {
int threshold = 100;
File checkpointsDir = TempDirUtils.newFolder(tmp, "checkpointsDir");
File sharedStateDir = TempDirUtils.newFolder(tmp, "sharedStateDir");
return new FsCheckpointStreamFactory(
getSharedInstance(),
fromLocalFile(checkpointsDir),
fromLocalFile(sharedStateDir),
threshold,
threshold);
}
public IncrementalRemoteKeyedStateHandle snapshot(
long checkpointId,
RocksIncrementalSnapshotStrategy<?> checkpointSnapshotStrategy,
FsCheckpointStreamFactory checkpointStreamFactory,
CloseableRegistry closeableRegistry)
throws Exception {
RocksIncrementalSnapshotStrategy.NativeRocksDBSnapshotResources snapshotResources =
checkpointSnapshotStrategy.syncPrepareResources(checkpointId);
return (IncrementalRemoteKeyedStateHandle)
checkpointSnapshotStrategy
.asyncSnapshot(
snapshotResources,
checkpointId,
checkpointId,
checkpointStreamFactory,
CheckpointOptions.forCheckpointWithDefaultLocation())
.get(closeableRegistry)
.getJobManagerOwnedSnapshot();
}
}
| RocksIncrementalSnapshotStrategyTest |
java | apache__dubbo | dubbo-compatible/src/test/java/org/apache/dubbo/metadata/annotation/processing/builder/GeneralTypeDefinitionBuilderTest.java | {
"start": 1663,
"end": 2698
} | class ____ extends AbstractAnnotationProcessingTest {
private GeneralTypeDefinitionBuilder builder;
@Override
protected void addCompiledClasses(Set<Class<?>> classesToBeCompiled) {
classesToBeCompiled.add(Model.class);
}
@Override
protected void beforeEach() {
builder = new GeneralTypeDefinitionBuilder();
}
@Test
void testAccept() {
assertTrue(builder.accept(processingEnv, getType(Model.class).asType()));
assertTrue(
builder.accept(processingEnv, getType(PrimitiveTypeModel.class).asType()));
assertTrue(builder.accept(processingEnv, getType(SimpleTypeModel.class).asType()));
assertTrue(builder.accept(processingEnv, getType(ArrayTypeModel.class).asType()));
assertTrue(
builder.accept(processingEnv, getType(CollectionTypeModel.class).asType()));
assertFalse(builder.accept(processingEnv, getType(Color.class).asType()));
}
@Test
void testBuild() {}
}
| GeneralTypeDefinitionBuilderTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/MessageBodyReaderTests.java | {
"start": 8486,
"end": 8966
} | class ____ {
@JsonProperty("id")
public int id;
@JsonProperty("name")
public String name;
Book() {
// do nothing ... for Jackson
}
Book(int id, String name, Student owner) {
this.id = id;
this.name = name;
this.owner = owner;
}
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty("owner")
public Student owner;
}
private static | Book |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/filemerging/BlockingPhysicalFilePool.java | {
"start": 1250,
"end": 1334
} | class ____
* best to reuse a physical file until its size > maxFileSize.
*/
public | try |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/hql/CollectionMapWithComponentValueTest.java | {
"start": 1478,
"end": 9026
} | class ____ {
private final KeyValue keyValue = new KeyValue( "key1" );
private final EmbeddableValue embeddableValue = new EmbeddableValue( 3 );
@BeforeAll
protected void prepareTest(SessionFactoryScope scope) {
scope.inTransaction( s -> {
keyValue.base = null;
s.persist( keyValue );
BaseTestEntity baseTestEntity1 = new BaseTestEntity();
TestEntity testEntity = new TestEntity();
Map<KeyValue, EmbeddableValue> map = new HashMap<>();
map.put( keyValue, embeddableValue );
testEntity.values = map;
s.persist( testEntity );
baseTestEntity1.entities = new HashSet<>();
baseTestEntity1.entities.add( testEntity );
s.persist( baseTestEntity1 );
keyValue.base = baseTestEntity1;
KeyValue keyValue2 = new KeyValue( "key2" );
s.persist( keyValue2 );
BaseTestEntity baseTestEntity2 = new BaseTestEntity();
s.persist( baseTestEntity2 );
TestEntity testEntity2 = new TestEntity();
Map<KeyValue, EmbeddableValue> map2 = new HashMap<>();
map2.put( keyValue2, embeddableValue );
testEntity2.values = map2;
s.persist( testEntity2 );
} );
}
@Test
public void testMapKeyExpressionInWhere(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// JPA form
Query query = s.createQuery( "select te from TestEntity te join te.values v where ?1 in (key(v)) " );
query.setParameter( 1, keyValue );
assertThat( query.list().size() ).isEqualTo( 1 );
// Hibernate additional form
query = s.createQuery( "select te from TestEntity te where ?1 in (key(te.values))" );
query.setParameter( 1, keyValue );
assertThat( query.list().size() ).isEqualTo( 1 );
// Test key property dereference
query = s.createQuery( "select te from TestEntity te join te.values v where key(v).name in :names" );
query.setParameterList( "names", Arrays.asList( keyValue.name ) );
assertThat( query.list().size() ).isEqualTo( 1 );
} );
}
@Test
@JiraKey(value = "HHH-10577")
public void testMapValueExpressionInWhere(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// JPA form
try {
Query query = s.createQuery( "select te from TestEntity te join te.values v where ? in (value(v))" );
query.setParameter( 0, new EmbeddableValue( 3 ) );
assertThat( query.list().size() ).isEqualTo( 2 );
fail( "HibernateException expected - Could not determine type for EmbeddableValue" );
}
catch (Exception e) {
assertTyping( IllegalArgumentException.class, e );
}
// Hibernate additional form
try {
Query query = s.createQuery( "select te from TestEntity te where ? in (value(te.values))" );
query.setParameter( 0, new EmbeddableValue( 3 ) );
assertThat( query.list().size() ).isEqualTo( 2 );
fail( "HibernateException expected - Could not determine type for EmbeddableValue" );
}
catch (Exception e) {
assertTyping( IllegalArgumentException.class, e );
}
// Test value property dereference
Query query = s.createQuery( "select te from TestEntity te join te.values v where value(v).value in :values" );
query.setParameterList( "values", Arrays.asList( 3 ) );
assertThat( query.list().size() ).isEqualTo( 2 );
} );
}
@Test
public void testMapKeyExpressionInSelect(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// JPA form
List results = s.createQuery( "select key(v) from TestEntity te join te.values v" ).list();
assertThat( results.size() ).isEqualTo( 2 );
assertTyping( KeyValue.class, results.get( 0 ) );
// Hibernate additional form
results = s.createQuery( "select key(te.values) from TestEntity te" ).list();
assertThat( results.size() ).isEqualTo( 2 );
assertTyping( KeyValue.class, results.get( 0 ) );
} );
}
@Test
public void testMapValueExpressionInSelect(SessionFactoryScope scope) {
scope.inTransaction( s -> {
List addresses = s.createQuery( "select value(v) from TestEntity te join te.values v" ).list();
assertThat( addresses.size() ).isEqualTo( 2 );
assertTyping( EmbeddableValue.class, addresses.get( 0 ) );
addresses = s.createQuery( "select value(te.values) from TestEntity te" ).list();
assertThat( addresses.size() ).isEqualTo( 2 );
assertTyping( EmbeddableValue.class, addresses.get( 0 ) );
} );
}
@Test
public void testMapEntryExpressionInSelect(SessionFactoryScope scope) {
scope.inTransaction( s -> {
List addresses = s.createQuery( "select entry(v) from TestEntity te join te.values v" ).list();
assertThat( addresses.size() ).isEqualTo( 2 );
assertTyping( Map.Entry.class, addresses.get( 0 ) );
addresses = s.createQuery( "select entry(te.values) from TestEntity te" ).list();
assertThat( addresses.size() ).isEqualTo( 2 );
assertTyping( Map.Entry.class, addresses.get( 0 ) );
} );
}
@Test
@JiraKey(value = "HHH-10577")
public void testMapKeyExpressionDereferenceInSelect(SessionFactoryScope scope) {
scope.inTransaction( s -> {
List<String> keyValueNames = s.createQuery(
"select key(v).name as name from TestEntity te join te.values v order by name",
String.class
).getResultList();
assertThat( keyValueNames.size() ).isEqualTo( 2 );
assertThat( keyValueNames.get( 0 ) ).isEqualTo( "key1" );
assertThat( keyValueNames.get( 1 ) ).isEqualTo( "key2" );
} );
}
@Test
@JiraKey(value = "HHH-10537")
public void testLeftJoinMapAndUseKeyExpression(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// Assert that a left join is used for joining the map key entity table
List keyValues = s.createQuery(
"select key(v) from BaseTestEntity bte left join bte.entities te left join te.values v" ).list();
System.out.println( keyValues );
assertThat( keyValues.size() ).isEqualTo( 2 );
} );
}
@Test
@JiraKey(value = "HHH-11433")
public void testJoinMapValue(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// Assert that a left join is used for joining the map key entity table
List keyValues = s.createQuery(
"select v from BaseTestEntity bte left join bte.entities te left join te.values v" ).list();
System.out.println( keyValues );
assertThat( keyValues.size() ).isEqualTo( 2 );
} );
}
@Test
@JiraKey(value = "HHH-11433")
public void testJoinMapKey(SessionFactoryScope scope) {
scope.inTransaction( s -> {
// Assert that a left join is used for joining the map key entity table
List keyValues = s.createQuery(
"select k from BaseTestEntity bte left join bte.entities te left join te.values v left join key(v) k" )
.list();
System.out.println( keyValues );
assertThat( keyValues.size() ).isEqualTo( 2 );
} );
}
@Test
@JiraKey(value = "HHH-11433")
public void testJoinMapKeyAssociation(SessionFactoryScope scope) {
scope.inTransaction( s -> {
List keyValues = s.createQuery(
"select b from BaseTestEntity bte left join bte.entities te left join te.values v left join key(v) k join k.base b" )
.list();
System.out.println( keyValues );
assertThat( keyValues.size() ).isEqualTo( 1 );
} );
}
@Test
@JiraKey(value = "HHH-11433")
public void testJoinMapKeyAssociationImplicit(SessionFactoryScope scope) {
scope.inTransaction( s -> {
List keyValues = s.createQuery(
"select b from BaseTestEntity bte left join bte.entities te left join te.values v join key(v).base b" )
.list();
System.out.println( keyValues );
assertThat( keyValues.size() ).isEqualTo( 1 );
} );
}
@Entity(name = "BaseTestEntity")
@Table(name = "BASE_TEST_ENTITY")
public static | CollectionMapWithComponentValueTest |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/Listing.java | {
"start": 12683,
"end": 20245
} | class ____
implements RemoteIterator<S3AFileStatus>, IOStatisticsSource, Closeable {
/** Source of objects. */
private final ObjectListingIterator source;
/** Filter of paths from API call. */
private final PathFilter filter;
/** Filter of entries from file status. */
private final FileStatusAcceptor acceptor;
/** request batch size. */
private int batchSize;
/** Iterator over the current set of results. */
private ListIterator<S3AFileStatus> statusBatchIterator;
/**
* Create an iterator over file status entries.
* @param source the listing iterator from a listObjects call.
* @param filter the filter on which paths to accept
* @param acceptor the class/predicate to decide which entries to accept
* in the listing based on the full file status.
* @throws IOException IO Problems
*/
@Retries.RetryTranslated
FileStatusListingIterator(ObjectListingIterator source,
PathFilter filter,
FileStatusAcceptor acceptor)
throws IOException {
this.source = source;
this.filter = filter;
this.acceptor = acceptor;
// build the first set of results. This will not trigger any
// remote IO, assuming the source iterator is in its initial
// iteration
requestNextBatch();
}
/**
* Report whether or not there is new data available.
* If there is data in the local filtered list, return true.
* Else: request more data util that condition is met, or there
* is no more remote listing data.
* Lastly, return true if the {@code providedStatusIterator}
* has left items.
* @return true if a call to {@link #next()} will succeed.
* @throws IOException IO Problems
*/
@Override
@Retries.RetryTranslated
public boolean hasNext() throws IOException {
return sourceHasNext();
}
@Retries.RetryTranslated
private boolean sourceHasNext() throws IOException {
return statusBatchIterator.hasNext() || requestNextBatch();
}
@Override
@Retries.RetryTranslated
public S3AFileStatus next() throws IOException {
final S3AFileStatus status;
if (sourceHasNext()) {
status = statusBatchIterator.next();
} else {
throw new NoSuchElementException();
}
return status;
}
/**
* Close, if called, will update
* the thread statistics context with the value.
*/
@Override
public void close() {
source.close();
}
/**
* Try to retrieve another batch.
* Note that for the initial batch,
* {@link ObjectListingIterator} does not generate a request;
* it simply returns the initial set.
*
* @return true if a new batch was created.
* @throws IOException IO problems
*/
@Retries.RetryTranslated
private boolean requestNextBatch() throws IOException {
// look for more object listing batches being available
while (source.hasNext()) {
// if available, retrieve it and build the next status
if (buildNextStatusBatch(source.next())) {
// this batch successfully generated entries matching the filters/
// acceptors; declare that the request was successful
return true;
} else {
LOG.debug("All entries in batch were filtered...continuing");
}
}
// if this code is reached, it means that all remaining
// object lists have been retrieved, and there are no new entries
// to return.
return false;
}
/**
* Build the next status batch from a listing.
* @param objects the next object listing
* @return true if this added any entries after filtering
* @throws IOException IO problems. This can happen only when CSE is enabled.
*/
private boolean buildNextStatusBatch(S3ListResult objects) throws IOException {
// counters for debug logs
int added = 0, ignored = 0;
// list to fill in with results. Initial size will be list maximum.
List<S3AFileStatus> stats = new ArrayList<>(
objects.getS3Objects().size() +
objects.getCommonPrefixes().size());
String userName = getStoreContext().getUsername();
long blockSize = listingOperationCallbacks.getDefaultBlockSize(null);
// objects
for (S3Object s3Object : objects.getS3Objects()) {
String key = s3Object.key();
Path keyPath = getStoreContext().getContextAccessors().keyToPath(key);
if (LOG.isDebugEnabled()) {
LOG.debug("{}: {}", keyPath, stringify(s3Object));
}
// Skip over keys that are ourselves and old S3N _$folder$ files
if (acceptor.accept(keyPath, s3Object) && filter.accept(keyPath)) {
S3AFileStatus status = createFileStatus(keyPath, s3Object,
blockSize, userName, s3Object.eTag(),
null,
listingOperationCallbacks.getObjectSize(s3Object));
LOG.debug("Adding: {}", status);
stats.add(status);
added++;
} else {
LOG.debug("Ignoring: {}", keyPath);
ignored++;
}
}
// prefixes: always directories
for (CommonPrefix prefix : objects.getCommonPrefixes()) {
Path keyPath = getStoreContext()
.getContextAccessors()
.keyToPath(prefix.prefix());
if (acceptor.accept(keyPath, prefix.prefix()) && filter.accept(keyPath)) {
S3AFileStatus status = new S3AFileStatus(Tristate.FALSE, keyPath,
getStoreContext().getUsername());
LOG.debug("Adding directory: {}", status);
added++;
stats.add(status);
} else {
LOG.debug("Ignoring directory: {}", keyPath);
ignored++;
}
}
// finish up
batchSize = stats.size();
statusBatchIterator = stats.listIterator();
boolean hasNext = statusBatchIterator.hasNext();
LOG.debug("Added {} entries; ignored {}; hasNext={}; hasMoreObjects={}",
added, ignored, hasNext, objects.isTruncated());
return hasNext;
}
/**
* Get the number of entries in the current batch.
* @return a number, possibly zero.
*/
public int getBatchSize() {
return batchSize;
}
/**
* Return any IOStatistics provided by the underlying stream.
* @return IO stats from the inner stream.
*/
@Override
public IOStatistics getIOStatistics() {
return source.getIOStatistics();
}
@Override
public String toString() {
return new StringJoiner(", ",
FileStatusListingIterator.class.getSimpleName() + "[", "]")
.add(source.toString())
.toString();
}
}
/**
* Wraps up AWS `ListObjects` requests in a remote iterator
* which will ask for more listing data if needed.
*
* That is:
*
* 1. The first invocation of the {@link #next()} call will return the results
* of the first request, the one created during the construction of the
* instance.
*
* 2. Second and later invocations will continue the ongoing listing,
* calling {@link S3AFileSystem#continueListObjects} to request the next
* batch of results.
*
* 3. The {@link #hasNext()} predicate returns true for the initial call,
* where {@link #next()} will return the initial results. It declares
* that it has future results iff the last executed request was truncated.
*
* Thread safety: none.
*/
| FileStatusListingIterator |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/spi-deployment/src/main/java/io/quarkus/resteasy/reactive/server/spi/MethodScannerBuildItem.java | {
"start": 188,
"end": 491
} | class ____ extends MultiBuildItem {
private final MethodScanner methodScanner;
public MethodScannerBuildItem(MethodScanner methodScanner) {
this.methodScanner = methodScanner;
}
public MethodScanner getMethodScanner() {
return methodScanner;
}
}
| MethodScannerBuildItem |
java | apache__maven | its/core-it-support/core-it-plugins/maven-it-plugin-artifact/src/main/java/org/apache/maven/plugin/coreit/AttachPomMojo.java | {
"start": 1504,
"end": 2986
} | class ____ extends AbstractMojo {
/**
* The current Maven project.
*/
@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;
/**
* The path to the POM file to attach to the main artifact, relative to the project base directory. The plugin will
* not validate this path.
*/
@Parameter(property = "artifact.pomFile", defaultValue = "${project.file.path}", required = true)
private String pomFile;
/**
* Runs this mojo.
*
* @throws MojoFailureException If the artifact file has not been set.
*/
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info("[MAVEN-CORE-IT-LOG] Attaching POM to main artifact: " + pomFile);
if (pomFile == null || pomFile.length() <= 0) {
throw new MojoFailureException("Path name for POM file has not been specified");
}
/*
* NOTE: We do not want to test path translation here, so resolve relative paths manually.
*/
File metadataFile = new File(pomFile);
if (!metadataFile.isAbsolute()) {
metadataFile = new File(project.getBasedir(), pomFile);
}
Artifact artifact = project.getArtifact();
artifact.addMetadata(new ProjectArtifactMetadata(artifact, metadataFile));
getLog().info("[MAVEN-CORE-IT-LOG] Attached POM to main artifact: " + metadataFile);
}
}
| AttachPomMojo |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/requests/RenewDelegationTokenRequest.java | {
"start": 2103,
"end": 3052
} | class ____ extends AbstractRequest.Builder<RenewDelegationTokenRequest> {
private final RenewDelegationTokenRequestData data;
public Builder(RenewDelegationTokenRequestData data) {
super(ApiKeys.RENEW_DELEGATION_TOKEN);
this.data = data;
}
@Override
public RenewDelegationTokenRequest build(short version) {
return new RenewDelegationTokenRequest(data, version);
}
@Override
public String toString() {
return maskData(data);
}
}
private static String maskData(RenewDelegationTokenRequestData data) {
RenewDelegationTokenRequestData tempData = data.duplicate();
tempData.setHmac(new byte[0]);
return tempData.toString();
}
// Do not print Hmac, overwrite a temp copy of the data with empty content
@Override
public String toString() {
return maskData(data);
}
}
| Builder |
java | micronaut-projects__micronaut-core | context/src/main/java/io/micronaut/scheduling/cron/CronExpression.java | {
"start": 19240,
"end": 19301
} | class ____ represent a simple cron field.
*/
static | that |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.