method2testcases
stringlengths 118
3.08k
|
---|
### Question:
JceksAWSCredentialProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (credentials == null) { refresh(); } return credentials; } JceksAWSCredentialProvider(String credentialProviderPath); JceksAWSCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); }### Answer:
@Test public void credentialsFromFile() throws IOException { String jceksPath = "jceks: JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(jceksPath); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("access")); assertThat(credentials.getAWSSecretKey(), is("secret")); }
@Test public void credentialsFromConf() throws IOException { when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray()); when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray()); JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(conf); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("accessKey")); assertThat(credentials.getAWSSecretKey(), is("secretKey")); }
@Test(expected = IllegalStateException.class) public void secretKeyNotSetInConfThrowsException() throws Exception { when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray()); new JceksAWSCredentialProvider(conf).getCredentials(); }
@Test(expected = IllegalStateException.class) public void accessKeyNotSetInConfThrowsException() throws Exception { when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray()); new JceksAWSCredentialProvider(conf).getCredentials(); } |
### Question:
ReplicaCatalog implements TunnelMetastoreCatalog { public void setName(String name) { this.name = name; } @Override String getName(); void setName(String name); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); }### Answer:
@Test public void nullName() { replicaCatalog.setName(null); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyName() { replicaCatalog.setName(""); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankName() { replicaCatalog.setName(" "); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); } |
### Question:
ReplicaCatalog implements TunnelMetastoreCatalog { public void setHiveMetastoreUris(String hiveMetastoreUris) { this.hiveMetastoreUris = hiveMetastoreUris; } @Override String getName(); void setName(String name); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); }### Answer:
@Test public void nullHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(null); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(""); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(" "); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); } |
### Question:
AvroStringUtils { @VisibleForTesting static String appendForwardSlashIfNotPresent(String path) { checkArgument(isNotBlank(path), "There must be a path provided"); if (path.charAt(path.length() - 1) == '/') { return path; } return path + "/"; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer:
@Test public void appendForwardSlashWhenNoneIsPresent() { assertThat(appendForwardSlashIfNotPresent("test"), is("test/")); }
@Test public void doesntAppendSecondForwardSlashWhenOneIsPresent() { assertThat(appendForwardSlashIfNotPresent("test/"), is("test/")); }
@Test(expected = IllegalArgumentException.class) public void nullArgParamTest() { appendForwardSlashIfNotPresent(null); }
@Test(expected = IllegalArgumentException.class) public void emptyArgParamTest() { appendForwardSlashIfNotPresent(""); } |
### Question:
TableReplication { public String getQualifiedReplicaName() { return getReplicaDatabaseName() + "." + getReplicaTableName(); } SourceTable getSourceTable(); void setSourceTable(SourceTable sourceTable); ReplicaTable getReplicaTable(); void setReplicaTable(ReplicaTable replicaTable); Map<String, Object> getCopierOptions(); Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions); static Map<String, Object> getMergedCopierOptions(
Map<String, Object> baseCopierOptions,
Map<String, Object> overrideCopierOptions); void setCopierOptions(Map<String, Object> copierOptions); Map<String, Object> getTransformOptions(); void setTransformOptions(Map<String, Object> transformOptions); String getReplicaDatabaseName(); String getReplicaTableName(); String getQualifiedReplicaName(); short getPartitionIteratorBatchSize(); void setPartitionIteratorBatchSize(short partitionIteratorBatchSize); short getPartitionFetcherBufferSize(); void setPartitionFetcherBufferSize(short partitionFetcherBufferSize); ReplicationMode getReplicationMode(); void setReplicationMode(ReplicationMode replicationMode); Map<String, String> getTableMappings(); void setTableMappings(Map<String, String> tableMappings); ReplicationStrategy getReplicationStrategy(); void setReplicationStrategy(ReplicationStrategy replicationStrategy); OrphanedDataStrategy getOrphanedDataStrategy(); void setOrphanedDataStrategy(OrphanedDataStrategy orphanedDataStrategy); }### Answer:
@Test public void getQualifiedReplicaName() { assertThat(tableReplication.getQualifiedReplicaName(), is("replica-database.replica-table")); }
@Test public void getQualifiedReplicaNameUseSourceDatabase() { replicaTable.setDatabaseName(null); assertThat(tableReplication.getQualifiedReplicaName(), is("source-database.replica-table")); }
@Test public void getQualifiedReplicaNameUseSourceTable() { replicaTable.setTableName(null); assertThat(tableReplication.getQualifiedReplicaName(), is("replica-database.source-table")); } |
### Question:
TableReplication { public Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions) { return getMergedCopierOptions(baseCopierOptions, getCopierOptions()); } SourceTable getSourceTable(); void setSourceTable(SourceTable sourceTable); ReplicaTable getReplicaTable(); void setReplicaTable(ReplicaTable replicaTable); Map<String, Object> getCopierOptions(); Map<String, Object> getMergedCopierOptions(Map<String, Object> baseCopierOptions); static Map<String, Object> getMergedCopierOptions(
Map<String, Object> baseCopierOptions,
Map<String, Object> overrideCopierOptions); void setCopierOptions(Map<String, Object> copierOptions); Map<String, Object> getTransformOptions(); void setTransformOptions(Map<String, Object> transformOptions); String getReplicaDatabaseName(); String getReplicaTableName(); String getQualifiedReplicaName(); short getPartitionIteratorBatchSize(); void setPartitionIteratorBatchSize(short partitionIteratorBatchSize); short getPartitionFetcherBufferSize(); void setPartitionFetcherBufferSize(short partitionFetcherBufferSize); ReplicationMode getReplicationMode(); void setReplicationMode(ReplicationMode replicationMode); Map<String, String> getTableMappings(); void setTableMappings(Map<String, String> tableMappings); ReplicationStrategy getReplicationStrategy(); void setReplicationStrategy(ReplicationStrategy replicationStrategy); OrphanedDataStrategy getOrphanedDataStrategy(); void setOrphanedDataStrategy(OrphanedDataStrategy orphanedDataStrategy); }### Answer:
@Test public void mergeNullOptions() { Map<String, Object> mergedCopierOptions = tableReplication.getMergedCopierOptions(null); assertThat(mergedCopierOptions, is(not(nullValue()))); assertThat(mergedCopierOptions.isEmpty(), is(true)); } |
### Question:
SourceCatalog implements TunnelMetastoreCatalog { public void setName(String name) { this.name = name; } @Override String getName(); void setName(String name); boolean isDisableSnapshots(); void setDisableSnapshots(boolean disableSnapshots); @Override MetastoreTunnel getMetastoreTunnel(); void setMetastoreTunnel(MetastoreTunnel metastoreTunnel); @Override List<String> getSiteXml(); void setSiteXml(List<String> siteXml); @Override Map<String, String> getConfigurationProperties(); void setConfigurationProperties(Map<String, String> configurationProperties); @Override String getHiveMetastoreUris(); void setHiveMetastoreUris(String hiveMetastoreUris); }### Answer:
@Test public void nullName() { sourceCatalog.setName(null); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); }
@Test public void emptyName() { sourceCatalog.setName(""); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); }
@Test public void blankName() { sourceCatalog.setName(" "); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void nullDatabaseName() { sourceTable.setDatabaseName(null); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void emptyDatabaseName() { sourceTable.setDatabaseName(""); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void blankDatabaseName() { sourceTable.setDatabaseName(" "); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setTableName(String tableName) { this.tableName = tableName; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void nullTableName() { sourceTable.setTableName(null); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); }
@Test public void emptyTableName() { sourceTable.setTableName(""); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public void setPartitionLimit(Short partitionLimit) { this.partitionLimit = partitionLimit; } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void partitionLimitTooLow() { sourceTable.setPartitionLimit((short) 0); Set<ConstraintViolation<SourceTable>> violations = validator.validate(sourceTable); assertThat(violations.size(), is(1)); } |
### Question:
SourceTable { public String getQualifiedName() { return databaseName.toLowerCase(Locale.ROOT) + "." + tableName.toLowerCase(Locale.ROOT); } String getDatabaseName(); void setDatabaseName(String databaseName); String getTableName(); void setTableName(String tableName); String getTableLocation(); void setTableLocation(String tableLocation); String getPartitionFilter(); void setPartitionFilter(String partitionFilter); Short getPartitionLimit(); void setPartitionLimit(Short partitionLimit); String getQualifiedName(); boolean isGeneratePartitionFilter(); void setGeneratePartitionFilter(boolean generatePartitionFilter); }### Answer:
@Test public void qualifiedTableName() { assertThat(sourceTable.getQualifiedName(), is("databasename.tablename")); } |
### Question:
AvroStringUtils { public static boolean argsPresent(String... args) { for (String arg : args) { if (isBlank(arg)) { return false; } } return true; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer:
@Test public void argsPresentTest() { assertTrue(argsPresent("test", "strings", "are", "present")); }
@Test public void argsPresentShouldFailWithNullStringTest() { assertFalse(argsPresent("test", "strings", null, "present")); }
@Test public void argsPresentShouldFailWithEmptyStringTest() { assertFalse(argsPresent("test", "strings", "", "present")); } |
### Question:
S3S3CopierOptions { public URI getS3Endpoint() { return s3Endpoint(Keys.S3_ENDPOINT_URI.keyName()); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer:
@Test public void getS3Endpoint() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.S3_ENDPOINT_URI.keyName(), "http: S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getS3Endpoint(), is(URI.create("http: }
@Test public void getS3EndpointDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getS3Endpoint()); } |
### Question:
S3MapReduceCpCopierFactory implements CopierFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return !S3Schemes.isS3Scheme(sourceScheme) && S3Schemes.isS3Scheme(replicaScheme); } @Autowired S3MapReduceCpCopierFactory(@Value("#{sourceHiveConf}") Configuration conf, MetricRegistry runningMetricsRegistry); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); @Override Copier newInstance(CopierContext copierContext); @Override Copier newInstance(
String eventId,
Path sourceBaseLocation,
Path replicaLocation,
Map<String, Object> copierOptions); @Override Copier newInstance(
String eventId,
Path sourceBaseLocation,
List<Path> sourceSubLocations,
Path replicaLocation,
Map<String, Object> copierOptions); }### Answer:
@Test public void supportsSchemes() throws Exception { S3MapReduceCpCopierFactory factory = new S3MapReduceCpCopierFactory(conf, runningMetricsRegistry); assertTrue(factory.supportsSchemes("hdfs", "s3")); assertTrue(factory.supportsSchemes("hdfs", "s3a")); assertTrue(factory.supportsSchemes("hdfs", "s3n")); assertTrue(factory.supportsSchemes("file", "s3")); assertTrue(factory.supportsSchemes("whatever", "s3")); }
@Test public void doesNotsupportsSchemes() throws Exception { S3MapReduceCpCopierFactory factory = new S3MapReduceCpCopierFactory(conf, runningMetricsRegistry); assertFalse(factory.supportsSchemes("hdfs", "hdfs")); assertFalse(factory.supportsSchemes("s3", "s3")); assertFalse(factory.supportsSchemes("s3", "hdfs")); assertFalse(factory.supportsSchemes("hdfs", "s321")); } |
### Question:
FileSystemPathResolver { public Path resolveScheme(Path path) { try { URI uri = path.toUri(); if (isEmpty(uri.getScheme())) { String scheme = FileSystem.get(configuration).getScheme(); Path result = new Path(new URI(scheme, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()).toString()); LOG.info("Added scheme {} to path {}. Resulting path is {}", scheme, path, result); return result; } } catch (URISyntaxException | IOException e) { throw new CircusTrainException(e); } return path; } FileSystemPathResolver(Configuration configuration); Path resolveScheme(Path path); Path resolveNameServices(Path path); }### Answer:
@Test public void resolveSchemeDoesntChangeSchemeForPathWithScheme() { Path expected = new Path("s3:/etl/test/avsc/schema.avsc"); Path result = resolver.resolveScheme(expected); assertThat(result, is(expected)); }
@Test public void resolveSchemeDoesntChangeSchemeForFullyQualifiedPathWithScheme() { Path expected = new Path("s3: Path result = resolver.resolveScheme(expected); assertThat(result, is(expected)); }
@Test public void resolveSchemeSetsSchemeIfSchemeIsntPresent() { Path input = new Path("/etl/test/avsc/schema.avsc"); Path result = resolver.resolveScheme(input); Path expected = new Path("file:/etl/test/avsc/schema.avsc"); assertThat(result, is(expected)); } |
### Question:
S3S3CopierOptions { public Boolean isS3ServerSideEncryption() { return MapUtils.getBoolean(copierOptions, Keys.S3_SERVER_SIDE_ENCRYPTION.keyName(), false); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer:
@Test public void setS3ServerSideEncryption() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.S3_SERVER_SIDE_ENCRYPTION.keyName(), "true"); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.isS3ServerSideEncryption(), is(true)); }
@Test public void defaultS3ServerSideEncryption() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.isS3ServerSideEncryption(), is(false)); } |
### Question:
CheckpointProperties implements Serializable { @VisibleForTesting CheckpointProperties( boolean forced, CheckpointType checkpointType, boolean discardSubsumed, boolean discardFinished, boolean discardCancelled, boolean discardFailed, boolean discardSuspended) { this.forced = forced; this.checkpointType = checkNotNull(checkpointType); this.discardSubsumed = discardSubsumed; this.discardFinished = discardFinished; this.discardCancelled = discardCancelled; this.discardFailed = discardFailed; this.discardSuspended = discardSuspended; } @VisibleForTesting CheckpointProperties(
boolean forced,
CheckpointType checkpointType,
boolean discardSubsumed,
boolean discardFinished,
boolean discardCancelled,
boolean discardFailed,
boolean discardSuspended); CheckpointType getCheckpointType(); boolean isSavepoint(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static CheckpointProperties forSavepoint(); static CheckpointProperties forCheckpoint(CheckpointRetentionPolicy policy); }### Answer:
@Test public void testCheckpointProperties() { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_FAILURE); assertFalse(props.forceCheckpoint()); assertTrue(props.discardOnSubsumed()); assertTrue(props.discardOnJobFinished()); assertTrue(props.discardOnJobCancelled()); assertFalse(props.discardOnJobFailed()); assertTrue(props.discardOnJobSuspended()); props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_CANCELLATION); assertFalse(props.forceCheckpoint()); assertTrue(props.discardOnSubsumed()); assertTrue(props.discardOnJobFinished()); assertFalse(props.discardOnJobCancelled()); assertFalse(props.discardOnJobFailed()); assertFalse(props.discardOnJobSuspended()); } |
### Question:
CheckpointProperties implements Serializable { public boolean isSavepoint() { return checkpointType == CheckpointType.SAVEPOINT; } @VisibleForTesting CheckpointProperties(
boolean forced,
CheckpointType checkpointType,
boolean discardSubsumed,
boolean discardFinished,
boolean discardCancelled,
boolean discardFailed,
boolean discardSuspended); CheckpointType getCheckpointType(); boolean isSavepoint(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static CheckpointProperties forSavepoint(); static CheckpointProperties forCheckpoint(CheckpointRetentionPolicy policy); }### Answer:
@Test public void testIsSavepoint() throws Exception { { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_FAILURE); assertFalse(props.isSavepoint()); } { CheckpointProperties props = CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.RETAIN_ON_CANCELLATION); assertFalse(props.isSavepoint()); } { CheckpointProperties props = CheckpointProperties.forSavepoint(); assertTrue(props.isSavepoint()); CheckpointProperties deserializedCheckpointProperties = InstantiationUtil.deserializeObject( InstantiationUtil.serializeObject(props), getClass().getClassLoader()); assertTrue(deserializedCheckpointProperties.isSavepoint()); } } |
### Question:
StateObjectCollection implements Collection<T>, StateObject { public boolean hasState() { for (StateObject state : stateObjects) { if (state != null) { return true; } } return false; } StateObjectCollection(); StateObjectCollection(Collection<T> stateObjects); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override Iterator<T> iterator(); @Override Object[] toArray(); @Override T1[] toArray(T1[] a); @Override boolean add(T t); @Override boolean remove(Object o); @Override boolean containsAll(Collection<?> c); @Override boolean addAll(Collection<? extends T> c); @Override boolean removeAll(Collection<?> c); @Override boolean removeIf(Predicate<? super T> filter); @Override boolean retainAll(Collection<?> c); @Override void clear(); @Override void discardState(); @Override long getStateSize(); boolean hasState(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static StateObjectCollection<T> empty(); static StateObjectCollection<T> singleton(T stateObject); }### Answer:
@Test public void testHasState() { StateObjectCollection<StateObject> stateObjects = new StateObjectCollection<>(new ArrayList<>()); Assert.assertFalse(stateObjects.hasState()); stateObjects = new StateObjectCollection<>(Collections.singletonList(null)); Assert.assertFalse(stateObjects.hasState()); stateObjects = new StateObjectCollection<>(Collections.singletonList(mock(StateObject.class))); Assert.assertTrue(stateObjects.hasState()); } |
### Question:
FailedCheckpointStats extends AbstractCheckpointStats { @Override public long getEndToEndDuration() { return Math.max(0, failureTimestamp - triggerTimestamp); } FailedCheckpointStats(
long checkpointId,
long triggerTimestamp,
CheckpointProperties props,
int totalSubtaskCount,
Map<JobVertexID, TaskStateStats> taskStats,
int numAcknowledgedSubtasks,
long stateSize,
long alignmentBuffered,
long failureTimestamp,
@Nullable SubtaskStateStats latestAcknowledgedSubtask,
@Nullable Throwable cause); @Override CheckpointStatsStatus getStatus(); @Override int getNumberOfAcknowledgedSubtasks(); @Override long getStateSize(); @Override long getAlignmentBuffered(); @Override @Nullable SubtaskStateStats getLatestAcknowledgedSubtaskStats(); @Override long getEndToEndDuration(); long getFailureTimestamp(); @Nullable String getFailureMessage(); }### Answer:
@Test public void testEndToEndDuration() throws Exception { long duration = 123912931293L; long triggerTimestamp = 10123; long failureTimestamp = triggerTimestamp + duration; Map<JobVertexID, TaskStateStats> taskStats = new HashMap<>(); JobVertexID jobVertexId = new JobVertexID(); taskStats.put(jobVertexId, new TaskStateStats(jobVertexId, 1)); FailedCheckpointStats failed = new FailedCheckpointStats( 0, triggerTimestamp, CheckpointProperties.forCheckpoint(CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), 1, taskStats, 0, 0, 0, failureTimestamp, null, null); assertEquals(duration, failed.getEndToEndDuration()); } |
### Question:
JobResult implements Serializable { public boolean isSuccess() { return serializedThrowable == null; } private JobResult(
final JobID jobId,
final Map<String, SerializedValue<OptionalFailure<Object>>> accumulatorResults,
final long netRuntime,
@Nullable final SerializedThrowable serializedThrowable); boolean isSuccess(); JobID getJobId(); Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorResults(); long getNetRuntime(); Optional<SerializedThrowable> getSerializedThrowable(); JobExecutionResult toJobExecutionResult(ClassLoader classLoader); static JobResult createFrom(AccessExecutionGraph accessExecutionGraph); }### Answer:
@Test public void testIsNotSuccess() throws Exception { final JobResult jobResult = new JobResult.Builder() .jobId(new JobID()) .serializedThrowable(new SerializedThrowable(new RuntimeException())) .netRuntime(Long.MAX_VALUE) .build(); assertThat(jobResult.isSuccess(), equalTo(false)); }
@Test public void testIsSuccess() throws Exception { final JobResult jobResult = new JobResult.Builder() .jobId(new JobID()) .netRuntime(Long.MAX_VALUE) .build(); assertThat(jobResult.isSuccess(), equalTo(true)); } |
### Question:
JobManagerRunner implements LeaderContender, OnCompletionActions, AutoCloseableAsync { @Override public void jobFinishedByOther() { resultFuture.completeExceptionally(new JobNotFinishedException(jobGraph.getJobID())); } JobManagerRunner(
final ResourceID resourceId,
final JobGraph jobGraph,
final Configuration configuration,
final RpcService rpcService,
final HighAvailabilityServices haServices,
final HeartbeatServices heartbeatServices,
final BlobServer blobServer,
final JobManagerSharedServices jobManagerSharedServices,
final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
final FatalErrorHandler fatalErrorHandler); CompletableFuture<JobMasterGateway> getLeaderGatewayFuture(); JobGraph getJobGraph(); CompletableFuture<ArchivedExecutionGraph> getResultFuture(); void start(); @Override CompletableFuture<Void> closeAsync(); @Override void jobReachedGloballyTerminalState(ArchivedExecutionGraph executionGraph); @Override void jobFinishedByOther(); @Override void jobMasterFailed(Throwable cause); @Override void grantLeadership(final UUID leaderSessionID); @Override void revokeLeadership(); @Override String getAddress(); @Override void handleError(Exception exception); }### Answer:
@Test public void testJobFinishedByOther() throws Exception { final JobManagerRunner jobManagerRunner = createJobManagerRunner(); try { jobManagerRunner.start(); final CompletableFuture<ArchivedExecutionGraph> resultFuture = jobManagerRunner.getResultFuture(); assertThat(resultFuture.isDone(), is(false)); jobManagerRunner.jobFinishedByOther(); try { resultFuture.get(); fail("Should have failed."); } catch (ExecutionException ee) { assertThat(ExceptionUtils.stripExecutionException(ee), instanceOf(JobNotFinishedException.class)); } } finally { jobManagerRunner.close(); } } |
### Question:
JobManagerRunner implements LeaderContender, OnCompletionActions, AutoCloseableAsync { public void start() throws Exception { try { leaderElectionService.start(this); } catch (Exception e) { log.error("Could not start the JobManager because the leader election service did not start.", e); throw new Exception("Could not start the leader election service.", e); } } JobManagerRunner(
final ResourceID resourceId,
final JobGraph jobGraph,
final Configuration configuration,
final RpcService rpcService,
final HighAvailabilityServices haServices,
final HeartbeatServices heartbeatServices,
final BlobServer blobServer,
final JobManagerSharedServices jobManagerSharedServices,
final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory,
final FatalErrorHandler fatalErrorHandler); CompletableFuture<JobMasterGateway> getLeaderGatewayFuture(); JobGraph getJobGraph(); CompletableFuture<ArchivedExecutionGraph> getResultFuture(); void start(); @Override CompletableFuture<Void> closeAsync(); @Override void jobReachedGloballyTerminalState(ArchivedExecutionGraph executionGraph); @Override void jobFinishedByOther(); @Override void jobMasterFailed(Throwable cause); @Override void grantLeadership(final UUID leaderSessionID); @Override void revokeLeadership(); @Override String getAddress(); @Override void handleError(Exception exception); }### Answer:
@Test public void testLibraryCacheManagerRegistration() throws Exception { final JobManagerRunner jobManagerRunner = createJobManagerRunner(); try { jobManagerRunner.start(); final LibraryCacheManager libraryCacheManager = jobManagerSharedServices.getLibraryCacheManager(); final JobID jobID = jobGraph.getJobID(); assertThat(libraryCacheManager.hasClassLoader(jobID), is(true)); jobManagerRunner.close(); assertThat(libraryCacheManager.hasClassLoader(jobID), is(false)); } finally { jobManagerRunner.close(); } } |
### Question:
ImmutableListState extends ImmutableState implements ListState<V> { @Override public void update(List<V> values) throws Exception { throw MODIFICATION_ATTEMPT_ERROR; } private ImmutableListState(final List<V> state); @Override Iterable<V> get(); @Override void add(V value); @Override void clear(); static ImmutableListState<V> createState(
final ListStateDescriptor<V> stateDescriptor,
final byte[] serializedState); @Override void update(List<V> values); @Override void addAll(List<V> values); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testUpdate() { List<Long> list = getStateContents(); assertEquals(1L, list.size()); long element = list.get(0); assertEquals(42L, element); listState.add(54L); } |
### Question:
ImmutableListState extends ImmutableState implements ListState<V> { @Override public void clear() { throw MODIFICATION_ATTEMPT_ERROR; } private ImmutableListState(final List<V> state); @Override Iterable<V> get(); @Override void add(V value); @Override void clear(); static ImmutableListState<V> createState(
final ListStateDescriptor<V> stateDescriptor,
final byte[] serializedState); @Override void update(List<V> values); @Override void addAll(List<V> values); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testClear() { List<Long> list = getStateContents(); assertEquals(1L, list.size()); long element = list.get(0); assertEquals(42L, element); listState.clear(); } |
### Question:
ExponentialWaitStrategy implements WaitStrategy { @Override public long sleepTime(final long attempt) { checkArgument(attempt >= 0, "attempt must not be negative (%d)", attempt); final long exponentialSleepTime = initialWait * Math.round(Math.pow(2, attempt)); return exponentialSleepTime >= 0 && exponentialSleepTime < maxWait ? exponentialSleepTime : maxWait; } ExponentialWaitStrategy(final long initialWait, final long maxWait); @Override long sleepTime(final long attempt); }### Answer:
@Test public void testMaxSleepTime() { final long sleepTime = new ExponentialWaitStrategy(1, 1).sleepTime(100); assertThat(sleepTime, equalTo(1L)); }
@Test public void testExponentialGrowth() { final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, 1000); assertThat(exponentialWaitStrategy.sleepTime(3) / exponentialWaitStrategy.sleepTime(2), equalTo(2L)); }
@Test public void testMaxAttempts() { final long maxWait = 1000; final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, maxWait); assertThat(exponentialWaitStrategy.sleepTime(Long.MAX_VALUE), equalTo(maxWait)); }
@Test public void test64Attempts() { final long maxWait = 1000; final ExponentialWaitStrategy exponentialWaitStrategy = new ExponentialWaitStrategy(1, maxWait); assertThat(exponentialWaitStrategy.sleepTime(64), equalTo(maxWait)); } |
### Question:
MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void statusUpdate(StatusUpdate message) { taskMonitor.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); schedulerDriver.acknowledgeStatusUpdate(message.status()); } MesosResourceManager(
// base class
RpcService rpcService,
String resourceManagerEndpointId,
ResourceID resourceId,
ResourceManagerConfiguration resourceManagerConfiguration,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
SlotManager slotManager,
MetricRegistry metricRegistry,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
// Mesos specifics
Configuration flinkConfig,
MesosServices mesosServices,
MesosConfiguration mesosConfig,
MesosTaskManagerParameters taskManagerParameters,
ContainerSpecification taskManagerContainerSpec); @Override CompletableFuture<Void> postStop(); @Override void startNewWorker(ResourceProfile resourceProfile); @Override boolean stopWorker(RegisteredMesosWorkerNode workerNode); void acceptOffers(AcceptOffers msg); void reconcile(ReconciliationCoordinator.Reconcile message); void taskTerminated(TaskMonitor.TaskTerminated message); }### Answer:
@Test public void testStatusHandling() throws Exception { new Context() {{ startResourceManager(); resourceManager.statusUpdate(new StatusUpdate(Protos.TaskStatus.newBuilder() .setTaskId(task1).setSlaveId(slave1).setState(Protos.TaskState.TASK_LOST).build())); resourceManager.reconciliationCoordinator.expectMsgClass(StatusUpdate.class); resourceManager.taskRouter.expectMsgClass(StatusUpdate.class); }}; } |
### Question:
MesosResourceManager extends ResourceManager<RegisteredMesosWorkerNode> { protected void disconnected(Disconnected message) { connectionMonitor.tell(message, selfActor); launchCoordinator.tell(message, selfActor); reconciliationCoordinator.tell(message, selfActor); taskMonitor.tell(message, selfActor); } MesosResourceManager(
// base class
RpcService rpcService,
String resourceManagerEndpointId,
ResourceID resourceId,
ResourceManagerConfiguration resourceManagerConfiguration,
HighAvailabilityServices highAvailabilityServices,
HeartbeatServices heartbeatServices,
SlotManager slotManager,
MetricRegistry metricRegistry,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
// Mesos specifics
Configuration flinkConfig,
MesosServices mesosServices,
MesosConfiguration mesosConfig,
MesosTaskManagerParameters taskManagerParameters,
ContainerSpecification taskManagerContainerSpec); @Override CompletableFuture<Void> postStop(); @Override void startNewWorker(ResourceProfile resourceProfile); @Override boolean stopWorker(RegisteredMesosWorkerNode workerNode); void acceptOffers(AcceptOffers msg); void reconcile(ReconciliationCoordinator.Reconcile message); void taskTerminated(TaskMonitor.TaskTerminated message); }### Answer:
@Test public void testDisconnected() throws Exception { new Context() {{ when(rmServices.workerStore.getFrameworkID()).thenReturn(Option.apply(framework1)); startResourceManager(); resourceManager.disconnected(new Disconnected()); resourceManager.connectionMonitor.expectMsgClass(Disconnected.class); resourceManager.reconciliationCoordinator.expectMsgClass(Disconnected.class); resourceManager.launchCoordinator.expectMsgClass(Disconnected.class); resourceManager.taskRouter.expectMsgClass(Disconnected.class); }}; } |
### Question:
Offer implements VirtualMachineLease { @Override public double cpuCores() { return cpuCores; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testCpuCores() { Offer offer = new Offer(offer(resources(cpus(1.0)), attrs())); Assert.assertEquals(1.0, offer.cpuCores(), EPSILON); } |
### Question:
Offer implements VirtualMachineLease { public double gpus() { return getScalarValue("gpus"); } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testGPUs() { Offer offer = new Offer(offer(resources(gpus(1.0)), attrs())); Assert.assertEquals(1.0, offer.gpus(), EPSILON); } |
### Question:
Offer implements VirtualMachineLease { @Override public double memoryMB() { return memoryMB; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testMemoryMB() { Offer offer = new Offer(offer(resources(mem(1024.0)), attrs())); Assert.assertEquals(1024.0, offer.memoryMB(), EPSILON); } |
### Question:
Offer implements VirtualMachineLease { @Override public double networkMbps() { return networkMbps; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testNetworkMbps() { Offer offer = new Offer(offer(resources(network(10.0)), attrs())); Assert.assertEquals(10.0, offer.networkMbps(), EPSILON); } |
### Question:
Offer implements VirtualMachineLease { @Override public double diskMB() { return diskMB; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testDiskMB() { Offer offer = new Offer(offer(resources(disk(1024.0)), attrs())); Assert.assertEquals(1024.0, offer.diskMB(), EPSILON); } |
### Question:
Offer implements VirtualMachineLease { @Override public List<Range> portRanges() { return portRanges; } Offer(Protos.Offer offer); List<Protos.Resource> getResources(); @Override String hostname(); @Override String getVMID(); @Override double cpuCores(); double gpus(); @Override double memoryMB(); @Override double networkMbps(); @Override double diskMB(); Protos.Offer getOffer(); @Override String getId(); @Override long getOfferedTime(); @Override List<Range> portRanges(); @Override Map<String, Protos.Attribute> getAttributeMap(); @Override Double getScalarValue(String name); @Override Map<String, Double> getScalarValues(); @Override String toString(); }### Answer:
@Test public void testPortRanges() { Offer offer = new Offer(offer(resources(ports(range(8080, 8081))), attrs())); Assert.assertEquals(Collections.singletonList(range(8080, 8081)), ranges(offer.portRanges())); } |
### Question:
RegisterApplicationMasterResponseReflector { @VisibleForTesting List<Container> getContainersFromPreviousAttemptsUnsafe(final Object response) { if (method != null && response != null) { try { @SuppressWarnings("unchecked") final List<Container> containers = (List<Container>) method.invoke(response); if (containers != null && !containers.isEmpty()) { return containers; } } catch (Exception t) { logger.error("Error invoking 'getContainersFromPreviousAttempts()'", t); } } return Collections.emptyList(); } RegisterApplicationMasterResponseReflector(final Logger log); @VisibleForTesting RegisterApplicationMasterResponseReflector(final Logger log, final Class<?> clazz); }### Answer:
@Test public void testCallsMethodIfPresent() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class); final List<Container> containersFromPreviousAttemptsUnsafe = registerApplicationMasterResponseReflector.getContainersFromPreviousAttemptsUnsafe(new HasMethod()); assertThat(containersFromPreviousAttemptsUnsafe, hasSize(1)); }
@Test public void testDoesntCallMethodIfAbsent() { final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class); final List<Container> containersFromPreviousAttemptsUnsafe = registerApplicationMasterResponseReflector.getContainersFromPreviousAttemptsUnsafe(new Object()); assertThat(containersFromPreviousAttemptsUnsafe, empty()); } |
### Question:
RegisterApplicationMasterResponseReflector { @VisibleForTesting Method getMethod() { return method; } RegisterApplicationMasterResponseReflector(final Logger log); @VisibleForTesting RegisterApplicationMasterResponseReflector(final Logger log, final Class<?> clazz); }### Answer:
@Test public void testGetMethodReflectiveHadoop22() { assumeTrue( "Method getContainersFromPreviousAttempts is not supported by Hadoop: " + VersionInfo.getVersion(), isHadoopVersionGreaterThanOrEquals(2, 2)); final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector = new RegisterApplicationMasterResponseReflector(LOG); final Method method = registerApplicationMasterResponseReflector.getMethod(); assertThat(method, notNullValue()); } |
### Question:
PrometheusReporter implements MetricReporter { @VisibleForTesting int getPort() { Preconditions.checkState(httpServer != null, "Server has not been initialized."); return port; } @Override void open(MetricConfig config); @Override void close(); @Override void notifyOfAddedMetric(final Metric metric, final String metricName, final MetricGroup group); @Override void notifyOfRemovedMetric(final Metric metric, final String metricName, final MetricGroup group); }### Answer:
@Test public void cannotStartTwoReportersOnSamePort() throws Exception { final MetricRegistryImpl fixedPort1 = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(createConfigWithOneReporter("test1", portRangeProvider.next()))); assertThat(fixedPort1.getReporters(), hasSize(1)); PrometheusReporter firstReporter = (PrometheusReporter) fixedPort1.getReporters().get(0); final MetricRegistryImpl fixedPort2 = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(createConfigWithOneReporter("test2", String.valueOf(firstReporter.getPort())))); assertThat(fixedPort2.getReporters(), hasSize(0)); fixedPort1.shutdown().get(); fixedPort2.shutdown().get(); } |
### Question:
JarIdPathParameter extends MessagePathParameter<String> { @Override protected String convertFromString(final String value) throws ConversionException { final Path path = Paths.get(value); if (path.getParent() != null) { throw new ConversionException(String.format("%s must be a filename only (%s)", KEY, path)); } return value; } protected JarIdPathParameter(); static final String KEY; }### Answer:
@Test(expected = ConversionException.class) public void testJarIdWithParentDir() throws Exception { jarIdPathParameter.convertFromString("../../test.jar"); }
@Test public void testConvertFromString() throws Exception { final String expectedJarId = "test.jar"; final String jarId = jarIdPathParameter.convertFromString(expectedJarId); assertEquals(expectedJarId, jarId); } |
### Question:
ListStateDescriptor extends StateDescriptor<ListState<T>, List<T>> { public ListStateDescriptor(String name, Class<T> elementTypeClass) { super(name, new ListTypeInfo<>(elementTypeClass), null); } ListStateDescriptor(String name, Class<T> elementTypeClass); ListStateDescriptor(String name, TypeInformation<T> elementTypeInfo); ListStateDescriptor(String name, TypeSerializer<T> typeSerializer); @Override ListState<T> bind(StateBinder stateBinder); TypeSerializer<T> getElementSerializer(); @Override Type getType(); }### Answer:
@Test public void testListStateDescriptor() throws Exception { TypeSerializer<String> serializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ListStateDescriptor<String> descr = new ListStateDescriptor<>("testName", serializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertTrue(descr.getSerializer() instanceof ListSerializer); assertNotNull(descr.getElementSerializer()); assertEquals(serializer, descr.getElementSerializer()); ListStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertTrue(copy.getSerializer() instanceof ListSerializer); assertNotNull(copy.getElementSerializer()); assertEquals(serializer, copy.getElementSerializer()); } |
### Question:
ListStateDescriptor extends StateDescriptor<ListState<T>, List<T>> { public TypeSerializer<T> getElementSerializer() { final TypeSerializer<List<T>> rawSerializer = getSerializer(); if (!(rawSerializer instanceof ListSerializer)) { throw new IllegalStateException(); } return ((ListSerializer<T>) rawSerializer).getElementSerializer(); } ListStateDescriptor(String name, Class<T> elementTypeClass); ListStateDescriptor(String name, TypeInformation<T> elementTypeInfo); ListStateDescriptor(String name, TypeSerializer<T> typeSerializer); @Override ListState<T> bind(StateBinder stateBinder); TypeSerializer<T> getElementSerializer(); @Override Type getType(); }### Answer:
@Test public void testSerializerDuplication() { TypeSerializer<String> statefulSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ListStateDescriptor<String> descr = new ListStateDescriptor<>("foobar", statefulSerializer); TypeSerializer<String> serializerA = descr.getElementSerializer(); TypeSerializer<String> serializerB = descr.getElementSerializer(); assertNotSame(serializerA, serializerB); TypeSerializer<List<String>> listSerializerA = descr.getSerializer(); TypeSerializer<List<String>> listSerializerB = descr.getSerializer(); assertNotSame(listSerializerA, listSerializerB); } |
### Question:
StateDescriptor implements Serializable { public TypeSerializer<T> getSerializer() { if (serializer != null) { return serializer.duplicate(); } else { throw new IllegalStateException("Serializer not yet initialized."); } } protected StateDescriptor(String name, TypeSerializer<T> serializer, @Nullable T defaultValue); protected StateDescriptor(String name, TypeInformation<T> typeInfo, @Nullable T defaultValue); protected StateDescriptor(String name, Class<T> type, @Nullable T defaultValue); String getName(); T getDefaultValue(); TypeSerializer<T> getSerializer(); void setQueryable(String queryableStateName); @Nullable String getQueryableStateName(); boolean isQueryable(); abstract S bind(StateBinder stateBinder); boolean isSerializerInitialized(); void initializeSerializerUnlessSet(ExecutionConfig executionConfig); @Override final int hashCode(); @Override final boolean equals(Object o); @Override String toString(); abstract Type getType(); }### Answer:
@Test public void testSerializerDuplication() throws Exception { TypeSerializer<String> statefulSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); TestStateDescriptor<String> descr = new TestStateDescriptor<>("foobar", statefulSerializer); TypeSerializer<String> serializerA = descr.getSerializer(); TypeSerializer<String> serializerB = descr.getSerializer(); assertNotSame(serializerA, serializerB); } |
### Question:
ReducingStateDescriptor extends StateDescriptor<ReducingState<T>, T> { public ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, Class<T> typeClass) { super(name, typeClass, null); this.reduceFunction = checkNotNull(reduceFunction); if (reduceFunction instanceof RichFunction) { throw new UnsupportedOperationException("ReduceFunction of ReducingState can not be a RichFunction."); } } ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, Class<T> typeClass); ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, TypeInformation<T> typeInfo); ReducingStateDescriptor(String name, ReduceFunction<T> reduceFunction, TypeSerializer<T> typeSerializer); @Override ReducingState<T> bind(StateBinder stateBinder); ReduceFunction<T> getReduceFunction(); @Override Type getType(); }### Answer:
@Test public void testReducingStateDescriptor() throws Exception { ReduceFunction<String> reducer = (a, b) -> a; TypeSerializer<String> serializer = new KryoSerializer<>(String.class, new ExecutionConfig()); ReducingStateDescriptor<String> descr = new ReducingStateDescriptor<>("testName", reducer, serializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertEquals(serializer, descr.getSerializer()); assertEquals(reducer, descr.getReduceFunction()); ReducingStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertEquals(serializer, copy.getSerializer()); } |
### Question:
MapStateDescriptor extends StateDescriptor<MapState<UK, UV>, Map<UK, UV>> { public MapStateDescriptor(String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer) { super(name, new MapSerializer<>(keySerializer, valueSerializer), null); } MapStateDescriptor(String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer); MapStateDescriptor(String name, TypeInformation<UK> keyTypeInfo, TypeInformation<UV> valueTypeInfo); MapStateDescriptor(String name, Class<UK> keyClass, Class<UV> valueClass); @Override MapState<UK, UV> bind(StateBinder stateBinder); @Override Type getType(); TypeSerializer<UK> getKeySerializer(); TypeSerializer<UV> getValueSerializer(); }### Answer:
@Test public void testMapStateDescriptor() throws Exception { TypeSerializer<Integer> keySerializer = new KryoSerializer<>(Integer.class, new ExecutionConfig()); TypeSerializer<String> valueSerializer = new KryoSerializer<>(String.class, new ExecutionConfig()); MapStateDescriptor<Integer, String> descr = new MapStateDescriptor<>("testName", keySerializer, valueSerializer); assertEquals("testName", descr.getName()); assertNotNull(descr.getSerializer()); assertTrue(descr.getSerializer() instanceof MapSerializer); assertNotNull(descr.getKeySerializer()); assertEquals(keySerializer, descr.getKeySerializer()); assertNotNull(descr.getValueSerializer()); assertEquals(valueSerializer, descr.getValueSerializer()); MapStateDescriptor<Integer, String> copy = CommonTestUtils.createCopySerializable(descr); assertEquals("testName", copy.getName()); assertNotNull(copy.getSerializer()); assertTrue(copy.getSerializer() instanceof MapSerializer); assertNotNull(copy.getKeySerializer()); assertEquals(keySerializer, copy.getKeySerializer()); assertNotNull(copy.getValueSerializer()); assertEquals(valueSerializer, copy.getValueSerializer()); } |
### Question:
JarIdPathParameter extends MessagePathParameter<String> { @Override protected String convertToString(final String value) { return value; } protected JarIdPathParameter(); static final String KEY; }### Answer:
@Test public void testConvertToString() throws Exception { final String expected = "test.jar"; final String toString = jarIdPathParameter.convertToString(expected); assertEquals(expected, toString); } |
### Question:
ResourceSpec implements Serializable { public boolean isValid() { if (this.cpuCores >= 0 && this.heapMemoryInMB >= 0 && this.directMemoryInMB >= 0 && this.nativeMemoryInMB >= 0 && this.stateSizeInMB >= 0) { for (Resource resource : extendedResources.values()) { if (resource.getValue() < 0) { return false; } } return true; } else { return false; } } protected ResourceSpec(
double cpuCores,
int heapMemoryInMB,
int directMemoryInMB,
int nativeMemoryInMB,
int stateSizeInMB,
Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer:
@Test public void testIsValid() throws Exception { ResourceSpec rs = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertTrue(rs.isValid()); rs = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1). build(); assertTrue(rs.isValid()); rs = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(-1). build(); assertFalse(rs.isValid()); } |
### Question:
ResourceSpec implements Serializable { public ResourceSpec merge(ResourceSpec other) { ResourceSpec target = new ResourceSpec( Math.max(this.cpuCores, other.cpuCores), this.heapMemoryInMB + other.heapMemoryInMB, this.directMemoryInMB + other.directMemoryInMB, this.nativeMemoryInMB + other.nativeMemoryInMB, this.stateSizeInMB + other.stateSizeInMB); target.extendedResources.putAll(extendedResources); for (Resource resource : other.extendedResources.values()) { target.extendedResources.merge(resource.getName(), resource, (v1, v2) -> v1.merge(v2)); } return target; } protected ResourceSpec(
double cpuCores,
int heapMemoryInMB,
int directMemoryInMB,
int nativeMemoryInMB,
int stateSizeInMB,
Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer:
@Test public void testMerge() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs3 = rs1.merge(rs2); assertEquals(1.1, rs3.getGPUResource(), 0.000001); ResourceSpec rs4 = rs1.merge(rs3); assertEquals(2.2, rs4.getGPUResource(), 0.000001); } |
### Question:
ResourceSpec implements Serializable { public static Builder newBuilder() { return new Builder(); } protected ResourceSpec(
double cpuCores,
int heapMemoryInMB,
int directMemoryInMB,
int nativeMemoryInMB,
int stateSizeInMB,
Resource... extendedResources); ResourceSpec merge(ResourceSpec other); double getCpuCores(); int getHeapMemory(); int getDirectMemory(); int getNativeMemory(); int getStateSize(); double getGPUResource(); Map<String, Resource> getExtendedResources(); boolean isValid(); boolean lessThanOrEqual(@Nonnull ResourceSpec other); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Builder newBuilder(); static final ResourceSpec DEFAULT; static final String GPU_NAME; }### Answer:
@Test public void testSerializable() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); byte[] buffer = InstantiationUtil.serializeObject(rs1); ResourceSpec rs2 = InstantiationUtil.deserializeObject(buffer, ClassLoader.getSystemClassLoader()); assertEquals(rs1, rs2); } |
### Question:
ParallelismQueryParameter extends MessageQueryParameter<Integer> { @Override public Integer convertStringToValue(final String value) { return Integer.valueOf(value); } ParallelismQueryParameter(); @Override Integer convertStringToValue(final String value); @Override String convertValueToString(final Integer value); }### Answer:
@Test public void testConvertStringToValue() { assertEquals("42", parallelismQueryParameter.convertValueToString(42)); }
@Test public void testConvertValueFromString() { assertEquals(42, (int) parallelismQueryParameter.convertStringToValue("42")); } |
### Question:
JarHandlerUtils { public static List<String> tokenizeArguments(@Nullable final String args) { if (args == null) { return Collections.emptyList(); } final Matcher matcher = ARGUMENTS_TOKENIZE_PATTERN.matcher(args); final List<String> tokens = new ArrayList<>(); while (matcher.find()) { tokens.add(matcher.group() .trim() .replace("\"", "") .replace("\'", "")); } return tokens; } static List<String> tokenizeArguments(@Nullable final String args); }### Answer:
@Test public void testTokenizeNonQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo bar"); assertThat(arguments.get(0), equalTo("--foo")); assertThat(arguments.get(1), equalTo("bar")); }
@Test public void testTokenizeSingleQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo 'bar baz '"); assertThat(arguments.get(0), equalTo("--foo")); assertThat(arguments.get(1), equalTo("bar baz ")); }
@Test public void testTokenizeDoubleQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--name \"K. Bote \""); assertThat(arguments.get(0), equalTo("--name")); assertThat(arguments.get(1), equalTo("K. Bote ")); } |
### Question:
LocalFileSystem extends FileSystem { @Override public FileSystemKind getKind() { return FileSystemKind.FILE_SYSTEM; } LocalFileSystem(); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override FileStatus getFileStatus(Path f); @Override URI getUri(); @Override Path getWorkingDirectory(); @Override Path getHomeDirectory(); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataInputStream open(final Path f); @Override boolean exists(Path f); @Override FileStatus[] listStatus(final Path f); @Override boolean delete(final Path f, final boolean recursive); @Override boolean mkdirs(final Path f); @Override FSDataOutputStream create(final Path filePath, final WriteMode overwrite); @Override boolean rename(final Path src, final Path dst); @Override boolean isDistributedFS(); @Override FileSystemKind getKind(); static URI getLocalFsURI(); static LocalFileSystem getSharedInstance(); }### Answer:
@Test public void testKind() { final FileSystem fs = FileSystem.getLocalFileSystem(); assertEquals(FileSystemKind.FILE_SYSTEM, fs.getKind()); } |
### Question:
JsonRowSerializationSchema implements SerializationSchema<Row> { @Override public byte[] serialize(Row row) { if (node == null) { node = mapper.createObjectNode(); } try { convertRow(node, (RowTypeInfo) typeInfo, row); return mapper.writeValueAsBytes(node); } catch (Throwable t) { throw new RuntimeException("Could not serialize row '" + row + "'. " + "Make sure that the schema matches the input.", t); } } JsonRowSerializationSchema(TypeInformation<Row> typeInfo); JsonRowSerializationSchema(String jsonSchema); @Override byte[] serialize(Row row); }### Answer:
@Test public void testSerializationOfTwoRows() throws IOException { final TypeInformation<Row> rowSchema = Types.ROW_NAMED( new String[] {"f1", "f2", "f3"}, Types.INT, Types.BOOLEAN, Types.STRING); final Row row1 = new Row(3); row1.setField(0, 1); row1.setField(1, true); row1.setField(2, "str"); final JsonRowSerializationSchema serializationSchema = new JsonRowSerializationSchema(rowSchema); final JsonRowDeserializationSchema deserializationSchema = new JsonRowDeserializationSchema(rowSchema); byte[] bytes = serializationSchema.serialize(row1); assertEquals(row1, deserializationSchema.deserialize(bytes)); final Row row2 = new Row(3); row2.setField(0, 10); row2.setField(1, false); row2.setField(2, "newStr"); bytes = serializationSchema.serialize(row2); assertEquals(row2, deserializationSchema.deserialize(bytes)); }
@Test(expected = RuntimeException.class) public void testSerializeRowWithInvalidNumberOfFields() { final TypeInformation<Row> rowSchema = Types.ROW_NAMED( new String[] {"f1", "f2", "f3"}, Types.INT, Types.BOOLEAN, Types.STRING); final Row row = new Row(1); row.setField(0, 1); final JsonRowSerializationSchema serializationSchema = new JsonRowSerializationSchema(rowSchema); serializationSchema.serialize(row); } |
### Question:
AllowNonRestoredStateQueryParameter extends MessageQueryParameter<Boolean> { @Override public Boolean convertStringToValue(final String value) { return Boolean.valueOf(value); } protected AllowNonRestoredStateQueryParameter(); @Override Boolean convertStringToValue(final String value); @Override String convertValueToString(final Boolean value); }### Answer:
@Test public void testConvertStringToValue() { assertEquals("false", allowNonRestoredStateQueryParameter.convertValueToString(false)); assertEquals("true", allowNonRestoredStateQueryParameter.convertValueToString(true)); }
@Test public void testConvertValueFromString() { assertEquals(false, allowNonRestoredStateQueryParameter.convertStringToValue("false")); assertEquals(true, allowNonRestoredStateQueryParameter.convertStringToValue("true")); assertEquals(true, allowNonRestoredStateQueryParameter.convertStringToValue("TRUE")); } |
### Question:
KafkaConsumerThread extends Thread { public void shutdown() { running = false; unassignedPartitionsQueue.close(); handover.wakeupProducer(); synchronized (consumerReassignmentLock) { if (consumer != null) { consumer.wakeup(); } else { hasBufferedWakeup = true; } } } KafkaConsumerThread(
Logger log,
Handover handover,
Properties kafkaProperties,
ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>> unassignedPartitionsQueue,
KafkaConsumerCallBridge consumerCallBridge,
String threadName,
long pollTimeout,
boolean useMetrics,
MetricGroup consumerMetricGroup,
MetricGroup subtaskMetricGroup); @Override void run(); void shutdown(); }### Answer:
@Test(timeout = 10000) public void testCloseWithoutAssignedPartitions() throws Exception { final KafkaConsumer<byte[], byte[]> mockConsumer = createMockConsumer( new LinkedHashMap<TopicPartition, Long>(), Collections.<TopicPartition, Long>emptyMap(), false, null, null); final MultiShotLatch getBatchBlockingInvoked = new MultiShotLatch(); final ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>> unassignedPartitionsQueue = new ClosableBlockingQueue<KafkaTopicPartitionState<TopicPartition>>() { @Override public List<KafkaTopicPartitionState<TopicPartition>> getBatchBlocking() throws InterruptedException { getBatchBlockingInvoked.trigger(); return super.getBatchBlocking(); } }; final TestKafkaConsumerThread testThread = new TestKafkaConsumerThread(mockConsumer, unassignedPartitionsQueue, new Handover()); testThread.start(); getBatchBlockingInvoked.await(); testThread.shutdown(); testThread.join(); } |
### Question:
FlinkKinesisProducer extends RichSinkFunction<OUT> implements CheckpointedFunction { public void setCustomPartitioner(KinesisPartitioner<OUT> partitioner) { checkNotNull(partitioner, "partitioner cannot be null"); checkArgument( InstantiationUtil.isSerializable(partitioner), "The provided custom partitioner is not serializable: " + partitioner.getClass().getName() + ". " + "Please check that it does not contain references to non-serializable instances."); this.customPartitioner = partitioner; } FlinkKinesisProducer(final SerializationSchema<OUT> schema, Properties configProps); FlinkKinesisProducer(KinesisSerializationSchema<OUT> schema, Properties configProps); void setFailOnError(boolean failOnError); void setDefaultStream(String defaultStream); void setDefaultPartition(String defaultPartition); void setCustomPartitioner(KinesisPartitioner<OUT> partitioner); @Override void open(Configuration parameters); @Override void invoke(OUT value, Context context); @Override void close(); @Override void initializeState(FunctionInitializationContext context); @Override void snapshotState(FunctionSnapshotContext context); }### Answer:
@Test public void testConfigureWithNonSerializableCustomPartitionerFails() { exception.expect(IllegalArgumentException.class); exception.expectMessage("The provided custom partitioner is not serializable"); new FlinkKinesisProducer<>(new SimpleStringSchema(), TestUtils.getStandardProperties()) .setCustomPartitioner(new NonSerializableCustomPartitioner()); }
@Test public void testConfigureWithSerializableCustomPartitioner() { new FlinkKinesisProducer<>(new SimpleStringSchema(), TestUtils.getStandardProperties()) .setCustomPartitioner(new SerializableCustomPartitioner()); } |
### Question:
GlobalConfiguration { public static boolean isSensitive(String key) { Preconditions.checkNotNull(key, "key is null"); final String keyInLower = key.toLowerCase(); for (String hideKey : SENSITIVE_KEYS) { if (keyInLower.length() >= hideKey.length() && keyInLower.contains(hideKey)) { return true; } } return false; } private GlobalConfiguration(); static Configuration loadConfiguration(); static Configuration loadConfiguration(final String configDir); static Configuration loadConfiguration(final String configDir, @Nullable final Configuration dynamicProperties); static Configuration loadConfigurationWithDynamicProperties(Configuration dynamicProperties); static boolean isSensitive(String key); static final String FLINK_CONF_FILENAME; static final String HIDDEN_CONTENT; }### Answer:
@Test public void testHiddenKey() { assertTrue(GlobalConfiguration.isSensitive("password123")); assertTrue(GlobalConfiguration.isSensitive("123pasSword")); assertTrue(GlobalConfiguration.isSensitive("PasSword")); assertTrue(GlobalConfiguration.isSensitive("Secret")); assertFalse(GlobalConfiguration.isSensitive("Hello")); } |
### Question:
StringUtils { public static String arrayToString(Object array) { if (array == null) { throw new NullPointerException(); } if (array instanceof int[]) { return Arrays.toString((int[]) array); } if (array instanceof long[]) { return Arrays.toString((long[]) array); } if (array instanceof Object[]) { return Arrays.toString((Object[]) array); } if (array instanceof byte[]) { return Arrays.toString((byte[]) array); } if (array instanceof double[]) { return Arrays.toString((double[]) array); } if (array instanceof float[]) { return Arrays.toString((float[]) array); } if (array instanceof boolean[]) { return Arrays.toString((boolean[]) array); } if (array instanceof char[]) { return Arrays.toString((char[]) array); } if (array instanceof short[]) { return Arrays.toString((short[]) array); } if (array.getClass().isArray()) { return "<unknown array type>"; } else { throw new IllegalArgumentException("The given argument is no array."); } } private StringUtils(); static String byteToHexString(final byte[] bytes, final int start, final int end); static String byteToHexString(final byte[] bytes); static byte[] hexStringToByte(final String hex); static String arrayAwareToString(Object o); static String arrayToString(Object array); static String showControlCharacters(String str); static String getRandomString(Random rnd, int minLength, int maxLength); static String getRandomString(Random rnd, int minLength, int maxLength, char minValue, char maxValue); static void writeString(@Nonnull String str, DataOutputView out); static String readString(DataInputView in); static void writeNullableString(@Nullable String str, DataOutputView out); static @Nullable String readNullableString(DataInputView in); static boolean isNullOrWhitespaceOnly(String str); @Nullable static String concatenateWithAnd(@Nullable String s1, @Nullable String s2); }### Answer:
@Test public void testArrayToString() { double[] array = {1.0}; String controlString = StringUtils.arrayToString(array); assertEquals("[1.0]", controlString); } |
### Question:
MinWatermarkGauge implements Gauge<Long> { @Override public Long getValue() { return Math.min(watermarkGauge1.getValue(), watermarkGauge2.getValue()); } MinWatermarkGauge(WatermarkGauge watermarkGauge1, WatermarkGauge watermarkGauge2); @Override Long getValue(); }### Answer:
@Test public void testSetCurrentLowWatermark() { WatermarkGauge metric1 = new WatermarkGauge(); WatermarkGauge metric2 = new WatermarkGauge(); MinWatermarkGauge metric = new MinWatermarkGauge(metric1, metric2); Assert.assertEquals(Long.MIN_VALUE, metric.getValue().longValue()); metric1.setCurrentWatermark(1); Assert.assertEquals(Long.MIN_VALUE, metric.getValue().longValue()); metric2.setCurrentWatermark(2); Assert.assertEquals(1L, metric.getValue().longValue()); metric1.setCurrentWatermark(3); Assert.assertEquals(2L, metric.getValue().longValue()); } |
### Question:
LambdaUtil { public static <E extends Throwable> void withContextClassLoader( final ClassLoader cl, final ThrowingRunnable<E> r) throws E { final Thread currentThread = Thread.currentThread(); final ClassLoader oldClassLoader = currentThread.getContextClassLoader(); try { currentThread.setContextClassLoader(cl); r.run(); } finally { currentThread.setContextClassLoader(oldClassLoader); } } private LambdaUtil(); static void applyToAllWhileSuppressingExceptions(
Iterable<T> inputs,
ThrowingConsumer<T, ? extends Exception> throwingConsumer); static void withContextClassLoader(
final ClassLoader cl,
final ThrowingRunnable<E> r); static R withContextClassLoader(
final ClassLoader cl,
final SupplierWithException<R, E> s); }### Answer:
@Test public void testRunWithContextClassLoaderRunnable() throws Exception { final ClassLoader aPrioriContextClassLoader = Thread.currentThread().getContextClassLoader(); try { final ClassLoader original = new URLClassLoader(new URL[0]); final ClassLoader temp = new URLClassLoader(new URL[0]); Thread.currentThread().setContextClassLoader(original); LambdaUtil.withContextClassLoader(temp, () -> assertSame(temp, Thread.currentThread().getContextClassLoader())); assertSame(original, Thread.currentThread().getContextClassLoader()); } finally { Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader); } }
@Test public void testRunWithContextClassLoaderSupplier() throws Exception { final ClassLoader aPrioriContextClassLoader = Thread.currentThread().getContextClassLoader(); try { final ClassLoader original = new URLClassLoader(new URL[0]); final ClassLoader temp = new URLClassLoader(new URL[0]); Thread.currentThread().setContextClassLoader(original); LambdaUtil.withContextClassLoader(temp, () -> { assertSame(temp, Thread.currentThread().getContextClassLoader()); return true; }); assertSame(original, Thread.currentThread().getContextClassLoader()); } finally { Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader); } } |
### Question:
SystemProcessingTimeService extends ProcessingTimeService { @Override public ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target) { long delay = Math.max(timestamp - getCurrentProcessingTime(), 0); try { return timerService.schedule( new TriggerTask(status, task, checkpointLock, target, timestamp), delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { final int status = this.status.get(); if (status == STATUS_QUIESCED) { return new NeverCompleteFuture(delay); } else if (status == STATUS_SHUTDOWN) { throw new IllegalStateException("Timer service is shut down"); } else { throw e; } } } SystemProcessingTimeService(AsyncExceptionHandler failureHandler, Object checkpointLock); SystemProcessingTimeService(
AsyncExceptionHandler task,
Object checkpointLock,
ThreadFactory threadFactory); @Override long getCurrentProcessingTime(); @Override ScheduledFuture<?> registerTimer(long timestamp, ProcessingTimeCallback target); @Override ScheduledFuture<?> scheduleAtFixedRate(ProcessingTimeCallback callback, long initialDelay, long period); @Override boolean isTerminated(); @Override void quiesce(); @Override void awaitPendingAfterQuiesce(); @Override void shutdownService(); @Override boolean shutdownAndAwaitPending(long time, TimeUnit timeUnit); @Override boolean shutdownServiceUninterruptible(long timeoutMs); }### Answer:
@Test public void testExceptionReporting() throws InterruptedException { final AtomicBoolean exceptionWasThrown = new AtomicBoolean(false); final OneShotLatch latch = new OneShotLatch(); final Object lock = new Object(); ProcessingTimeService timeServiceProvider = new SystemProcessingTimeService( new AsyncExceptionHandler() { @Override public void handleAsyncException(String message, Throwable exception) { exceptionWasThrown.set(true); latch.trigger(); } }, lock); timeServiceProvider.registerTimer(System.currentTimeMillis(), new ProcessingTimeCallback() { @Override public void onProcessingTime(long timestamp) throws Exception { throw new Exception("Exception in Timer"); } }); latch.await(); assertTrue(exceptionWasThrown.get()); } |
### Question:
RocksDBKeySerializationUtils { public static boolean isAmbiguousKeyPossible(TypeSerializer keySerializer, TypeSerializer namespaceSerializer) { return (keySerializer.getLength() < 0) && (namespaceSerializer.getLength() < 0); } static int readKeyGroup(int keyGroupPrefixBytes, DataInputView inputView); static K readKey(
TypeSerializer<K> keySerializer,
ByteArrayInputStreamWithPos inputStream,
DataInputView inputView,
boolean ambiguousKeyPossible); static N readNamespace(
TypeSerializer<N> namespaceSerializer,
ByteArrayInputStreamWithPos inputStream,
DataInputView inputView,
boolean ambiguousKeyPossible); static void writeNameSpace(
N namespace,
TypeSerializer<N> namespaceSerializer,
ByteArrayOutputStreamWithPos keySerializationStream,
DataOutputView keySerializationDataOutputView,
boolean ambiguousKeyPossible); static boolean isAmbiguousKeyPossible(TypeSerializer keySerializer, TypeSerializer namespaceSerializer); static void writeKeyGroup(
int keyGroup,
int keyGroupPrefixBytes,
DataOutputView keySerializationDateDataOutputView); static void writeKey(
K key,
TypeSerializer<K> keySerializer,
ByteArrayOutputStreamWithPos keySerializationStream,
DataOutputView keySerializationDataOutputView,
boolean ambiguousKeyPossible); }### Answer:
@Test public void testIsAmbiguousKeyPossible() { Assert.assertFalse(RocksDBKeySerializationUtils.isAmbiguousKeyPossible( IntSerializer.INSTANCE, StringSerializer.INSTANCE)); Assert.assertTrue(RocksDBKeySerializationUtils.isAmbiguousKeyPossible( StringSerializer.INSTANCE, StringSerializer.INSTANCE)); } |
### Question:
AkkaRpcService implements RpcService { @Override public ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit) { checkNotNull(runnable, "runnable"); checkNotNull(unit, "unit"); checkArgument(delay >= 0L, "delay must be zero or larger"); return internalScheduledExecutor.schedule(runnable, delay, unit); } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect(
final String address,
final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer:
@Test public void testScheduleRunnable() throws Exception { final OneShotLatch latch = new OneShotLatch(); final long delay = 100; final long start = System.nanoTime(); ScheduledFuture<?> scheduledFuture = akkaRpcService.scheduleRunnable(new Runnable() { @Override public void run() { latch.trigger(); } }, delay, TimeUnit.MILLISECONDS); scheduledFuture.get(); assertTrue(latch.isTriggered()); final long stop = System.nanoTime(); assertTrue("call was not properly delayed", ((stop - start) / 1000000) >= delay); } |
### Question:
AkkaRpcService implements RpcService { @Override public void execute(Runnable runnable) { actorSystem.dispatcher().execute(runnable); } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect(
final String address,
final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer:
@Test public void testExecuteRunnable() throws Exception { final OneShotLatch latch = new OneShotLatch(); akkaRpcService.execute(() -> latch.trigger()); latch.await(30L, TimeUnit.SECONDS); }
@Test public void testExecuteCallable() throws InterruptedException, ExecutionException, TimeoutException { final OneShotLatch latch = new OneShotLatch(); final int expected = 42; CompletableFuture<Integer> result = akkaRpcService.execute(new Callable<Integer>() { @Override public Integer call() throws Exception { latch.trigger(); return expected; } }); int actual = result.get(30L, TimeUnit.SECONDS); assertEquals(expected, actual); assertTrue(latch.isTriggered()); } |
### Question:
AkkaRpcService implements RpcService { @Override public String getAddress() { return address; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect(
final String address,
final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer:
@Test public void testGetAddress() { assertEquals(AkkaUtils.getAddress(actorSystem).host().get(), akkaRpcService.getAddress()); } |
### Question:
AkkaRpcService implements RpcService { @Override public int getPort() { return port; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect(
final String address,
final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer:
@Test public void testGetPort() { assertEquals(AkkaUtils.getAddress(actorSystem).port().get(), akkaRpcService.getPort()); } |
### Question:
AkkaRpcService implements RpcService { @Override public CompletableFuture<Void> getTerminationFuture() { return terminationFuture; } AkkaRpcService(final ActorSystem actorSystem, final Time timeout); ActorSystem getActorSystem(); @Override String getAddress(); @Override int getPort(); @Override CompletableFuture<C> connect(
final String address,
final Class<C> clazz); @Override CompletableFuture<C> connect(String address, F fencingToken, Class<C> clazz); @Override RpcServer startServer(C rpcEndpoint); @Override RpcServer fenceRpcServer(RpcServer rpcServer, F fencingToken); @Override void stopServer(RpcServer selfGateway); @Override CompletableFuture<Void> stopService(); @Override CompletableFuture<Void> getTerminationFuture(); @Override Executor getExecutor(); @Override ScheduledExecutor getScheduledExecutor(); @Override ScheduledFuture<?> scheduleRunnable(Runnable runnable, long delay, TimeUnit unit); @Override void execute(Runnable runnable); @Override CompletableFuture<T> execute(Callable<T> callable); }### Answer:
@Test(timeout = 60000) public void testTerminationFuture() throws Exception { final ActorSystem actorSystem = AkkaUtils.createDefaultActorSystem(); final AkkaRpcService rpcService = new AkkaRpcService(actorSystem, Time.milliseconds(1000)); CompletableFuture<Void> terminationFuture = rpcService.getTerminationFuture(); assertFalse(terminationFuture.isDone()); CompletableFuture.runAsync(rpcService::stopService, actorSystem.dispatcher()); terminationFuture.get(); } |
### Question:
SubtaskIndexPathParameter extends MessagePathParameter<Integer> { @Override protected Integer convertFromString(final String value) throws ConversionException { final int subtaskIndex = Integer.parseInt(value); if (subtaskIndex >= 0) { return subtaskIndex; } else { throw new ConversionException("subtaskindex must be positive, was: " + subtaskIndex); } } SubtaskIndexPathParameter(); static final String KEY; }### Answer:
@Test public void testConversionFromString() throws Exception { assertThat(subtaskIndexPathParameter.convertFromString("2147483647"), equalTo(Integer.MAX_VALUE)); }
@Test public void testConversionFromStringNegativeNumber() throws Exception { try { subtaskIndexPathParameter.convertFromString("-2147483648"); fail("Expected exception not thrown"); } catch (final ConversionException e) { assertThat(e.getMessage(), equalTo("subtaskindex must be positive, was: " + Integer .MIN_VALUE)); } } |
### Question:
SubtaskIndexPathParameter extends MessagePathParameter<Integer> { @Override protected String convertToString(final Integer value) { return value.toString(); } SubtaskIndexPathParameter(); static final String KEY; }### Answer:
@Test public void testConvertToString() throws Exception { assertThat(subtaskIndexPathParameter.convertToString(Integer.MAX_VALUE), equalTo("2147483647")); } |
### Question:
HandlerRequestUtils { public static <X, P extends MessageQueryParameter<X>, R extends RequestBody, M extends MessageParameters> X getQueryParameter( final HandlerRequest<R, M> request, final Class<P> queryParameterClass) throws RestHandlerException { return getQueryParameter(request, queryParameterClass, null); } static X getQueryParameter(
final HandlerRequest<R, M> request,
final Class<P> queryParameterClass); static X getQueryParameter(
final HandlerRequest<R, M> request,
final Class<P> queryParameterClass,
final X defaultValue); }### Answer:
@Test public void testGetQueryParameter() throws Exception { final Boolean queryParameter = HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Collections.singletonList("true"))), TestBooleanQueryParameter.class); assertThat(queryParameter, equalTo(true)); }
@Test public void testGetQueryParameterRepeated() throws Exception { try { HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Arrays.asList("true", "false"))), TestBooleanQueryParameter.class); } catch (final RestHandlerException e) { assertThat(e.getMessage(), containsString("Expected only one value")); } }
@Test public void testGetQueryParameterDefaultValue() throws Exception { final Boolean allowNonRestoredState = HandlerRequestUtils.getQueryParameter( new HandlerRequest<>( EmptyRequestBody.getInstance(), new TestMessageParameters(), Collections.emptyMap(), Collections.singletonMap("key", Collections.emptyList())), TestBooleanQueryParameter.class, true); assertThat(allowNonRestoredState, equalTo(true)); } |
### Question:
FileUtils { public static void deleteDirectory(File directory) throws IOException { checkNotNull(directory, "directory"); guardIfWindows(FileUtils::deleteDirectoryInternal, directory); } private FileUtils(); static String getRandomFilename(final String prefix); static String readFile(File file, String charsetName); static String readFileUtf8(File file); static void writeFile(File file, String contents, String encoding); static void writeFileUtf8(File file, String contents); static void deleteFileOrDirectory(File file); static void deleteDirectory(File directory); static void deleteDirectoryQuietly(File directory); static void cleanDirectory(File directory); static boolean deletePathIfEmpty(FileSystem fileSystem, Path path); }### Answer:
@Test public void testDeleteDirectory() throws Exception { File doesNotExist = new File(tmp.newFolder(), "abc"); FileUtils.deleteDirectory(doesNotExist); File cannotDeleteParent = tmp.newFolder(); File cannotDeleteChild = new File(cannotDeleteParent, "child"); try { assumeTrue(cannotDeleteChild.createNewFile()); assumeTrue(cannotDeleteParent.setWritable(false)); assumeTrue(cannotDeleteChild.setWritable(false)); FileUtils.deleteDirectory(cannotDeleteParent); fail("this should fail with an exception"); } catch (AccessDeniedException ignored) { } finally { cannotDeleteParent.setWritable(true); cannotDeleteChild.setWritable(true); } }
@Test public void testDeleteDirectoryWhichIsAFile() throws Exception { File file = tmp.newFile(); try { FileUtils.deleteDirectory(file); fail("this should fail with an exception"); } catch (IOException ignored) { } } |
### Question:
ExceptionUtils { public static String stringifyException(final Throwable e) { if (e == null) { return STRINGIFIED_NULL_EXCEPTION; } try { StringWriter stm = new StringWriter(); PrintWriter wrt = new PrintWriter(stm); e.printStackTrace(wrt); wrt.close(); return stm.toString(); } catch (Throwable t) { return e.getClass().getName() + " (error while printing stack trace)"; } } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer:
@Test public void testStringifyNullException() { assertNotNull(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION); assertEquals(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION, ExceptionUtils.stringifyException(null)); } |
### Question:
ExceptionUtils { public static boolean isJvmFatalError(Throwable t) { return (t instanceof InternalError) || (t instanceof UnknownError) || (t instanceof ThreadDeath); } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer:
@Test public void testJvmFatalError() { assertFalse(ExceptionUtils.isJvmFatalError(new Error())); assertFalse(ExceptionUtils.isJvmFatalError(new LinkageError())); assertTrue(ExceptionUtils.isJvmFatalError(new InternalError())); assertTrue(ExceptionUtils.isJvmFatalError(new UnknownError())); } |
### Question:
ExceptionUtils { public static void rethrowIfFatalError(Throwable t) { if (isJvmFatalError(t)) { throw (Error) t; } } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer:
@Test public void testRethrowFatalError() { try { ExceptionUtils.rethrowIfFatalError(new InternalError()); fail(); } catch (InternalError ignored) {} ExceptionUtils.rethrowIfFatalError(new NoClassDefFoundError()); } |
### Question:
ExceptionUtils { public static <T extends Throwable> Optional<T> findThrowable(Throwable throwable, Class<T> searchType) { if (throwable == null || searchType == null) { return Optional.empty(); } Throwable t = throwable; while (t != null) { if (searchType.isAssignableFrom(t.getClass())) { return Optional.of(searchType.cast(t)); } else { t = t.getCause(); } } return Optional.empty(); } private ExceptionUtils(); static String stringifyException(final Throwable e); static boolean isJvmFatalError(Throwable t); static boolean isJvmFatalOrOutOfMemoryError(Throwable t); static void rethrowIfFatalError(Throwable t); static void rethrowIfFatalErrorOrOOM(Throwable t); static T firstOrSuppressed(T newException, @Nullable T previous); static void rethrow(Throwable t); static void rethrow(Throwable t, String parentMessage); static void rethrowException(Throwable t, String parentMessage); static void rethrowException(Throwable t); static void tryRethrowIOException(Throwable t); static void rethrowIOException(Throwable t); static Optional<T> findThrowable(Throwable throwable, Class<T> searchType); static Optional<Throwable> findThrowable(Throwable throwable, Predicate<Throwable> predicate); static Optional<Throwable> findThrowableWithMessage(Throwable throwable, String searchMessage); static Throwable stripExecutionException(Throwable throwable); static Throwable stripCompletionException(Throwable throwable); static void tryDeserializeAndThrow(Throwable throwable, ClassLoader classLoader); static void checkInterrupted(Throwable e); static void suppressExceptions(RunnableWithException action); static final String STRINGIFIED_NULL_EXCEPTION; }### Answer:
@Test public void testFindThrowableByType() { assertTrue(ExceptionUtils.findThrowable( new RuntimeException(new IllegalStateException()), IllegalStateException.class).isPresent()); } |
### Question:
JobVertexBackPressureHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, JobVertexBackPressureInfo, JobVertexMessageParameters> { @Override protected CompletableFuture<JobVertexBackPressureInfo> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { final JobID jobId = request.getPathParameter(JobIDPathParameter.class); final JobVertexID jobVertexId = request.getPathParameter(JobVertexIdPathParameter.class); return gateway .requestOperatorBackPressureStats(jobId, jobVertexId) .thenApply( operatorBackPressureStats -> operatorBackPressureStats.getOperatorBackPressureStats().map( JobVertexBackPressureHandler::createJobVertexBackPressureInfo).orElse( JobVertexBackPressureInfo.deprecated())); } JobVertexBackPressureHandler(
CompletableFuture<String> localRestAddress,
GatewayRetriever<? extends RestfulGateway> leaderRetriever,
Time timeout,
Map<String, String> responseHeaders,
MessageHeaders<EmptyRequestBody, JobVertexBackPressureInfo, JobVertexMessageParameters> messageHeaders); }### Answer:
@Test public void testAbsentBackPressure() throws Exception { final Map<String, String> pathParameters = new HashMap<>(); pathParameters.put(JobIDPathParameter.KEY, TEST_JOB_ID_BACK_PRESSURE_STATS_ABSENT.toString()); pathParameters.put(JobVertexIdPathParameter.KEY, new JobVertexID().toString()); final HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request = new HandlerRequest<>( EmptyRequestBody.getInstance(), new JobVertexMessageParameters(), pathParameters, Collections.emptyMap()); final CompletableFuture<JobVertexBackPressureInfo> jobVertexBackPressureInfoCompletableFuture = jobVertexBackPressureHandler.handleRequest(request, restfulGateway); final JobVertexBackPressureInfo jobVertexBackPressureInfo = jobVertexBackPressureInfoCompletableFuture.get(); assertThat(jobVertexBackPressureInfo.getStatus(), equalTo(VertexBackPressureStatus.DEPRECATED)); } |
### Question:
RestServerEndpoint implements AutoCloseableAsync { @VisibleForTesting static void createUploadDir(final Path uploadDir, final Logger log) throws IOException { if (!Files.exists(uploadDir)) { log.warn("Upload directory {} does not exist, or has been deleted externally. " + "Previously uploaded files are no longer available.", uploadDir); checkAndCreateUploadDir(uploadDir, log); } } RestServerEndpoint(RestServerEndpointConfiguration configuration); final void start(); @Nullable InetSocketAddress getServerAddress(); String getRestBaseUrl(); @Override CompletableFuture<Void> closeAsync(); }### Answer:
@Test public void testCreateUploadDir() throws Exception { final File file = temporaryFolder.newFolder(); final Path testUploadDir = file.toPath().resolve("testUploadDir"); assertFalse(Files.exists(testUploadDir)); RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER); assertTrue(Files.exists(testUploadDir)); }
@Test public void testCreateUploadDirFails() throws Exception { final File file = temporaryFolder.newFolder(); Assume.assumeTrue(file.setWritable(false)); final Path testUploadDir = file.toPath().resolve("testUploadDir"); assertFalse(Files.exists(testUploadDir)); try { RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER); fail("Expected exception not thrown."); } catch (IOException e) { } } |
### Question:
MetricRegistryImpl implements MetricRegistry { public boolean isShutdown() { synchronized (lock) { return isShutdown; } } MetricRegistryImpl(MetricRegistryConfiguration config); void startQueryService(ActorSystem actorSystem, ResourceID resourceID); @Override @Nullable String getMetricQueryServicePath(); @Override char getDelimiter(); @Override char getDelimiter(int reporterIndex); @Override int getNumberReporters(); @VisibleForTesting List<MetricReporter> getReporters(); boolean isShutdown(); CompletableFuture<Void> shutdown(); @Override ScopeFormats getScopeFormats(); @Override void register(Metric metric, String metricName, AbstractMetricGroup group); @Override void unregister(Metric metric, String metricName, AbstractMetricGroup group); @VisibleForTesting @Nullable ActorRef getQueryService(); }### Answer:
@Test public void testIsShutdown() throws Exception { MetricRegistryImpl metricRegistry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration()); Assert.assertFalse(metricRegistry.isShutdown()); metricRegistry.shutdown().get(); Assert.assertTrue(metricRegistry.isShutdown()); } |
### Question:
AbstractMetricGroup implements MetricGroup { public Map<String, String> getAllVariables() { if (variables == null) { synchronized (this) { if (variables == null) { variables = new HashMap<>(); putVariables(variables); if (parent != null) { variables.putAll(parent.getAllVariables()); } } } } return variables; } AbstractMetricGroup(MetricRegistry registry, String[] scope, A parent); Map<String, String> getAllVariables(); String getLogicalScope(CharacterFilter filter); String getLogicalScope(CharacterFilter filter, char delimiter); String[] getScopeComponents(); QueryScopeInfo getQueryServiceMetricInfo(CharacterFilter filter); String getMetricIdentifier(String metricName); String getMetricIdentifier(String metricName, CharacterFilter filter); String getMetricIdentifier(String metricName, CharacterFilter filter, int reporterIndex); void close(); final boolean isClosed(); @Override Counter counter(int name); @Override Counter counter(String name); @Override C counter(int name, C counter); @Override C counter(String name, C counter); @Override G gauge(int name, G gauge); @Override G gauge(String name, G gauge); @Override H histogram(int name, H histogram); @Override H histogram(String name, H histogram); @Override M meter(int name, M meter); @Override M meter(String name, M meter); @Override MetricGroup addGroup(int name); @Override MetricGroup addGroup(String name); @Override MetricGroup addGroup(String key, String value); }### Answer:
@Test public void testGetAllVariables() throws Exception { MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration()); AbstractMetricGroup group = new AbstractMetricGroup<AbstractMetricGroup<?>>(registry, new String[0], null) { @Override protected QueryScopeInfo createQueryServiceMetricInfo(CharacterFilter filter) { return null; } @Override protected String getGroupName(CharacterFilter filter) { return ""; } }; assertTrue(group.getAllVariables().isEmpty()); registry.shutdown().get(); } |
### Question:
TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { @Override protected QueryScopeInfo.TaskQueryScopeInfo createQueryServiceMetricInfo(CharacterFilter filter) { return new QueryScopeInfo.TaskQueryScopeInfo( this.parent.jobId.toString(), String.valueOf(this.vertexId), this.subtaskIndex); } TaskMetricGroup(
MetricRegistry registry,
TaskManagerJobMetricGroup parent,
@Nullable JobVertexID vertexId,
AbstractID executionId,
@Nullable String taskName,
int subtaskIndex,
int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer:
@Test public void testCreateQueryServiceMetricInfo() { JobID jid = new JobID(); JobVertexID vid = new JobVertexID(); AbstractID eid = new AbstractID(); TaskManagerMetricGroup tm = new TaskManagerMetricGroup(registry, "host", "id"); TaskManagerJobMetricGroup job = new TaskManagerJobMetricGroup(registry, tm, jid, "jobname"); TaskMetricGroup task = new TaskMetricGroup(registry, job, vid, eid, "taskName", 4, 5); QueryScopeInfo.TaskQueryScopeInfo info = task.createQueryServiceMetricInfo(new DummyCharacterFilter()); assertEquals("", info.scope); assertEquals(jid.toString(), info.jobID); assertEquals(vid.toString(), info.vertexID); assertEquals(4, info.subtaskIndex); } |
### Question:
TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { @Override public void close() { super.close(); parent.removeTaskMetricGroup(executionId); } TaskMetricGroup(
MetricRegistry registry,
TaskManagerJobMetricGroup parent,
@Nullable JobVertexID vertexId,
AbstractID executionId,
@Nullable String taskName,
int subtaskIndex,
int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer:
@Test public void testTaskMetricGroupCleanup() throws Exception { CountingMetricRegistry registry = new CountingMetricRegistry(new Configuration()); TaskManagerMetricGroup taskManagerMetricGroup = new TaskManagerMetricGroup(registry, "localhost", "0"); TaskManagerJobMetricGroup taskManagerJobMetricGroup = new TaskManagerJobMetricGroup(registry, taskManagerMetricGroup, new JobID(), "job"); TaskMetricGroup taskMetricGroup = new TaskMetricGroup(registry, taskManagerJobMetricGroup, new JobVertexID(), new AbstractID(), "task", 0, 0); assertTrue(registry.getNumberRegisteredMetrics() > 0); taskMetricGroup.close(); assertEquals(0, registry.getNumberRegisteredMetrics()); registry.shutdown().get(); } |
### Question:
TaskMetricGroup extends ComponentMetricGroup<TaskManagerJobMetricGroup> { public OperatorMetricGroup addOperator(String name) { return addOperator(OperatorID.fromJobVertexID(vertexId), name); } TaskMetricGroup(
MetricRegistry registry,
TaskManagerJobMetricGroup parent,
@Nullable JobVertexID vertexId,
AbstractID executionId,
@Nullable String taskName,
int subtaskIndex,
int attemptNumber); final TaskManagerJobMetricGroup parent(); AbstractID executionId(); @Nullable AbstractID vertexId(); @Nullable String taskName(); int subtaskIndex(); int attemptNumber(); TaskIOMetricGroup getIOMetricGroup(); OperatorMetricGroup addOperator(String name); OperatorMetricGroup addOperator(OperatorID operatorID, String name); @Override void close(); }### Answer:
@Test public void testOperatorNameTruncation() throws Exception { Configuration cfg = new Configuration(); cfg.setString(MetricOptions.SCOPE_NAMING_OPERATOR, ScopeFormat.SCOPE_OPERATOR_NAME); MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.fromConfiguration(cfg)); TaskManagerMetricGroup tm = new TaskManagerMetricGroup(registry, "host", "id"); TaskManagerJobMetricGroup job = new TaskManagerJobMetricGroup(registry, tm, new JobID(), "jobname"); TaskMetricGroup taskMetricGroup = new TaskMetricGroup(registry, job, new JobVertexID(), new AbstractID(), "task", 0, 0); String originalName = new String(new char[100]).replace("\0", "-"); OperatorMetricGroup operatorMetricGroup = taskMetricGroup.addOperator(originalName); String storedName = operatorMetricGroup.getScopeComponents()[0]; Assert.assertEquals(TaskMetricGroup.METRICS_OPERATOR_NAME_MAX_LENGTH, storedName.length()); Assert.assertEquals(originalName.substring(0, TaskMetricGroup.METRICS_OPERATOR_NAME_MAX_LENGTH), storedName); registry.shutdown().get(); } |
### Question:
TaskEventDispatcher { public void registerPartition(ResultPartitionID partitionId) { checkNotNull(partitionId); synchronized (registeredHandlers) { LOG.debug("registering {}", partitionId); if (registeredHandlers.put(partitionId, new TaskEventHandler()) != null) { throw new IllegalStateException( "Partition " + partitionId + " already registered at task event dispatcher."); } } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent(
ResultPartitionID partitionId,
EventListener<TaskEvent> eventListener,
Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer:
@Test public void registerPartitionTwice() throws Exception { ResultPartitionID partitionId = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); ted.registerPartition(partitionId); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("already registered at task event dispatcher"); ted.registerPartition(partitionId); } |
### Question:
TaskEventDispatcher { public void subscribeToEvent( ResultPartitionID partitionId, EventListener<TaskEvent> eventListener, Class<? extends TaskEvent> eventType) { checkNotNull(partitionId); checkNotNull(eventListener); checkNotNull(eventType); TaskEventHandler taskEventHandler; synchronized (registeredHandlers) { taskEventHandler = registeredHandlers.get(partitionId); } if (taskEventHandler == null) { throw new IllegalStateException( "Partition " + partitionId + " not registered at task event dispatcher."); } taskEventHandler.subscribe(eventListener, eventType); } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent(
ResultPartitionID partitionId,
EventListener<TaskEvent> eventListener,
Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer:
@Test public void subscribeToEventNotRegistered() throws Exception { TaskEventDispatcher ted = new TaskEventDispatcher(); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("not registered at task event dispatcher"); ted.subscribeToEvent(new ResultPartitionID(), new ZeroShotEventListener(), TaskEvent.class); } |
### Question:
TaskEventDispatcher { public void unregisterPartition(ResultPartitionID partitionId) { checkNotNull(partitionId); synchronized (registeredHandlers) { LOG.debug("unregistering {}", partitionId); registeredHandlers.remove(partitionId); } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent(
ResultPartitionID partitionId,
EventListener<TaskEvent> eventListener,
Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer:
@Test public void unregisterPartition() throws Exception { ResultPartitionID partitionId1 = new ResultPartitionID(); ResultPartitionID partitionId2 = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); AllWorkersDoneEvent event = new AllWorkersDoneEvent(); assertFalse(ted.publish(partitionId1, event)); ted.registerPartition(partitionId1); ted.registerPartition(partitionId2); OneShotEventListener eventListener1a = new OneShotEventListener(event); ZeroShotEventListener eventListener1b = new ZeroShotEventListener(); OneShotEventListener eventListener2 = new OneShotEventListener(event); ted.subscribeToEvent(partitionId1, eventListener1a, AllWorkersDoneEvent.class); ted.subscribeToEvent(partitionId2, eventListener1b, AllWorkersDoneEvent.class); ted.subscribeToEvent(partitionId1, eventListener2, AllWorkersDoneEvent.class); ted.unregisterPartition(partitionId2); assertTrue(ted.publish(partitionId1, event)); assertTrue("listener should have fired for AllWorkersDoneEvent", eventListener1a.fired); assertTrue("listener should have fired for AllWorkersDoneEvent", eventListener2.fired); assertFalse(ted.publish(partitionId2, event)); } |
### Question:
TaskEventDispatcher { public void clearAll() { synchronized (registeredHandlers) { registeredHandlers.clear(); } } void registerPartition(ResultPartitionID partitionId); void unregisterPartition(ResultPartitionID partitionId); void subscribeToEvent(
ResultPartitionID partitionId,
EventListener<TaskEvent> eventListener,
Class<? extends TaskEvent> eventType); boolean publish(ResultPartitionID partitionId, TaskEvent event); void clearAll(); }### Answer:
@Test public void clearAll() throws Exception { ResultPartitionID partitionId = new ResultPartitionID(); TaskEventDispatcher ted = new TaskEventDispatcher(); ted.registerPartition(partitionId); ZeroShotEventListener eventListener1 = new ZeroShotEventListener(); ted.subscribeToEvent(partitionId, eventListener1, AllWorkersDoneEvent.class); ted.clearAll(); assertFalse(ted.publish(partitionId, new AllWorkersDoneEvent())); } |
### Question:
PipelinedSubpartition extends ResultSubpartition { @Override public PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener) throws IOException { synchronized (buffers) { checkState(!isReleased); checkState(readView == null, "Subpartition %s of is being (or already has been) consumed, " + "but pipelined subpartitions can only be consumed once.", index, parent.getPartitionId()); LOG.debug("Creating read view for subpartition {} of partition {}.", index, parent.getPartitionId()); readView = new PipelinedSubpartitionView(this, availabilityListener); if (!buffers.isEmpty()) { notifyDataAvailable(); } } return readView; } PipelinedSubpartition(int index, ResultPartition parent); @Override boolean add(BufferConsumer bufferConsumer); @Override void flush(); @Override void finish(); @Override void release(); @Override int releaseMemory(); @Override boolean isReleased(); @Override PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener); boolean isAvailable(); @Override String toString(); @Override int unsynchronizedGetNumberOfQueuedBuffers(); }### Answer:
@Test public void testIllegalReadViewRequest() throws Exception { final PipelinedSubpartition subpartition = createSubpartition(); assertNotNull(subpartition.createReadView(new NoOpBufferAvailablityListener())); try { subpartition.createReadView(new NoOpBufferAvailablityListener()); fail("Did not throw expected exception after duplicate notifyNonEmpty view request."); } catch (IllegalStateException expected) { } } |
### Question:
PipelinedSubpartition extends ResultSubpartition { @Override public boolean isReleased() { return isReleased; } PipelinedSubpartition(int index, ResultPartition parent); @Override boolean add(BufferConsumer bufferConsumer); @Override void flush(); @Override void finish(); @Override void release(); @Override int releaseMemory(); @Override boolean isReleased(); @Override PipelinedSubpartitionView createReadView(BufferAvailabilityListener availabilityListener); boolean isAvailable(); @Override String toString(); @Override int unsynchronizedGetNumberOfQueuedBuffers(); }### Answer:
@Test public void testIsReleasedChecksParent() throws Exception { PipelinedSubpartition subpartition = mock(PipelinedSubpartition.class); PipelinedSubpartitionView reader = new PipelinedSubpartitionView( subpartition, mock(BufferAvailabilityListener.class)); assertFalse(reader.isReleased()); verify(subpartition, times(1)).isReleased(); when(subpartition.isReleased()).thenReturn(true); assertTrue(reader.isReleased()); verify(subpartition, times(2)).isReleased(); } |
### Question:
RemoteInputChannel extends InputChannel implements BufferRecycler, BufferListener { public void onFailedPartitionRequest() { inputGate.triggerPartitionStateCheck(partitionId); } RemoteInputChannel(
SingleInputGate inputGate,
int channelIndex,
ResultPartitionID partitionId,
ConnectionID connectionId,
ConnectionManager connectionManager,
TaskIOMetricGroup metrics); RemoteInputChannel(
SingleInputGate inputGate,
int channelIndex,
ResultPartitionID partitionId,
ConnectionID connectionId,
ConnectionManager connectionManager,
int initialBackOff,
int maxBackoff,
TaskIOMetricGroup metrics); @VisibleForTesting @Override void requestSubpartition(int subpartitionIndex); @Override boolean isReleased(); @Override String toString(); @Override void recycle(MemorySegment segment); int getNumberOfAvailableBuffers(); int getNumberOfRequiredBuffers(); int getSenderBacklog(); @Override boolean notifyBufferAvailable(Buffer buffer); @Override void notifyBufferDestroyed(); int getUnannouncedCredit(); int getAndResetUnannouncedCredit(); int getNumberOfQueuedBuffers(); int unsynchronizedGetNumberOfQueuedBuffers(); InputChannelID getInputChannelId(); int getInitialCredit(); BufferProvider getBufferProvider(); @Nullable Buffer requestBuffer(); void onBuffer(Buffer buffer, int sequenceNumber, int backlog); void onEmptyBuffer(int sequenceNumber, int backlog); void onFailedPartitionRequest(); void onError(Throwable cause); }### Answer:
@Test public void testOnFailedPartitionRequest() throws Exception { final ConnectionManager connectionManager = mock(ConnectionManager.class); when(connectionManager.createPartitionRequestClient(any(ConnectionID.class))) .thenReturn(mock(PartitionRequestClient.class)); final ResultPartitionID partitionId = new ResultPartitionID(); final SingleInputGate inputGate = mock(SingleInputGate.class); final RemoteInputChannel ch = new RemoteInputChannel( inputGate, 0, partitionId, mock(ConnectionID.class), connectionManager, UnregisteredMetricGroups.createUnregisteredTaskMetricGroup().getIOMetricGroup()); ch.onFailedPartitionRequest(); verify(inputGate).triggerPartitionStateCheck(eq(partitionId)); } |
### Question:
SpanningRecordSerializer implements RecordSerializer<T> { @Override public boolean hasSerializedData() { return lengthBuffer.hasRemaining() || dataBuffer.hasRemaining(); } SpanningRecordSerializer(); @Override SerializationResult addRecord(T record); @Override SerializationResult continueWritingWithNextBufferBuilder(BufferBuilder buffer); @Override void clear(); @Override boolean hasSerializedData(); }### Answer:
@Test public void testHasSerializedData() throws IOException { final int segmentSize = 16; final SpanningRecordSerializer<SerializationTestType> serializer = new SpanningRecordSerializer<>(); final SerializationTestType randomIntRecord = Util.randomRecord(SerializationTestTypeFactory.INT); Assert.assertFalse(serializer.hasSerializedData()); serializer.addRecord(randomIntRecord); Assert.assertTrue(serializer.hasSerializedData()); serializer.continueWritingWithNextBufferBuilder(createBufferBuilder(segmentSize)); Assert.assertFalse(serializer.hasSerializedData()); serializer.continueWritingWithNextBufferBuilder(createBufferBuilder(8)); serializer.addRecord(randomIntRecord); Assert.assertFalse(serializer.hasSerializedData()); serializer.addRecord(randomIntRecord); Assert.assertTrue(serializer.hasSerializedData()); } |
### Question:
CoLocationConstraint { public AbstractID getGroupId() { return this.group.getId(); } CoLocationConstraint(CoLocationGroup group); SharedSlot getSharedSlot(); AbstractID getGroupId(); boolean isAssigned(); boolean isAssignedAndAlive(); TaskManagerLocation getLocation(); void setSharedSlot(SharedSlot newSlot); void lockLocation(); void lockLocation(TaskManagerLocation taskManagerLocation); void setSlotRequestId(@Nullable SlotRequestId slotRequestId); @Nullable SlotRequestId getSlotRequestId(); @Override String toString(); }### Answer:
@Test public void testCreateConstraints() { try { JobVertexID id1 = new JobVertexID(); JobVertexID id2 = new JobVertexID(); JobVertex vertex1 = new JobVertex("vertex1", id1); vertex1.setParallelism(2); JobVertex vertex2 = new JobVertex("vertex2", id2); vertex2.setParallelism(3); CoLocationGroup group = new CoLocationGroup(vertex1, vertex2); AbstractID groupId = group.getId(); assertNotNull(groupId); CoLocationConstraint constraint1 = group.getLocationConstraint(0); CoLocationConstraint constraint2 = group.getLocationConstraint(1); CoLocationConstraint constraint3 = group.getLocationConstraint(2); assertFalse(constraint1 == constraint2); assertFalse(constraint1 == constraint3); assertFalse(constraint2 == constraint3); assertEquals(groupId, constraint1.getGroupId()); assertEquals(groupId, constraint2.getGroupId()); assertEquals(groupId, constraint3.getGroupId()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } |
### Question:
EmbeddedHaServices extends AbstractNonHaServices { @Override public LeaderElectionService getResourceManagerLeaderElectionService() { return resourceManagerLeaderService.createLeaderElectionService(); } EmbeddedHaServices(Executor executor); @Override LeaderRetrievalService getResourceManagerLeaderRetriever(); @Override LeaderRetrievalService getDispatcherLeaderRetriever(); @Override LeaderElectionService getResourceManagerLeaderElectionService(); @Override LeaderElectionService getDispatcherLeaderElectionService(); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID, String defaultJobManagerAddress); @Override LeaderRetrievalService getWebMonitorLeaderRetriever(); @Override LeaderElectionService getJobManagerLeaderElectionService(JobID jobID); @Override LeaderElectionService getWebMonitorLeaderElectionService(); @Override void close(); }### Answer:
@Test public void testResourceManagerLeaderElection() throws Exception { LeaderContender leaderContender1 = mock(LeaderContender.class); LeaderContender leaderContender2 = mock(LeaderContender.class); LeaderElectionService leaderElectionService1 = embeddedHaServices.getResourceManagerLeaderElectionService(); LeaderElectionService leaderElectionService2 = embeddedHaServices.getResourceManagerLeaderElectionService(); leaderElectionService1.start(leaderContender1); leaderElectionService2.start(leaderContender2); ArgumentCaptor<UUID> leaderIdArgumentCaptor1 = ArgumentCaptor.forClass(UUID.class); ArgumentCaptor<UUID> leaderIdArgumentCaptor2 = ArgumentCaptor.forClass(UUID.class); verify(leaderContender1, atLeast(0)).grantLeadership(leaderIdArgumentCaptor1.capture()); verify(leaderContender2, atLeast(0)).grantLeadership(leaderIdArgumentCaptor2.capture()); assertTrue(leaderIdArgumentCaptor1.getAllValues().isEmpty() ^ leaderIdArgumentCaptor2.getAllValues().isEmpty()); } |
### Question:
SnapshotDirectory { public boolean mkdirs() throws IOException { return fileSystem.mkdirs(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer:
@Test public void mkdirs() throws Exception { File folderRoot = temporaryFolder.getRoot(); File newFolder = new File(folderRoot, String.valueOf(UUID.randomUUID())); File innerNewFolder = new File(newFolder, String.valueOf(UUID.randomUUID())); Path path = new Path(innerNewFolder.toURI()); Assert.assertFalse(newFolder.isDirectory()); Assert.assertFalse(innerNewFolder.isDirectory()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertFalse(snapshotDirectory.exists()); Assert.assertFalse(newFolder.isDirectory()); Assert.assertFalse(innerNewFolder.isDirectory()); Assert.assertTrue(snapshotDirectory.mkdirs()); Assert.assertTrue(newFolder.isDirectory()); Assert.assertTrue(innerNewFolder.isDirectory()); Assert.assertTrue(snapshotDirectory.exists()); } |
### Question:
SnapshotDirectory { public boolean exists() throws IOException { return fileSystem.exists(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer:
@Test public void exists() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertFalse(folderA.isDirectory()); Path path = new Path(folderA.toURI()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertFalse(snapshotDirectory.exists()); Assert.assertTrue(folderA.mkdirs()); Assert.assertTrue(snapshotDirectory.exists()); Assert.assertTrue(folderA.delete()); Assert.assertFalse(snapshotDirectory.exists()); } |
### Question:
SnapshotDirectory { public FileStatus[] listStatus() throws IOException { return fileSystem.listStatus(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer:
@Test public void listStatus() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); File folderB = new File(folderA, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folderB.mkdirs()); File file = new File(folderA, "test.txt"); Assert.assertTrue(file.createNewFile()); Path path = new Path(folderA.toURI()); FileSystem fileSystem = path.getFileSystem(); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertTrue(snapshotDirectory.exists()); Assert.assertEquals( Arrays.toString(fileSystem.listStatus(path)), Arrays.toString(snapshotDirectory.listStatus())); } |
### Question:
SnapshotDirectory { @Nullable public abstract DirectoryStateHandle completeSnapshotAndGetHandle() throws IOException; private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer:
@Test public void completeSnapshotAndGetHandle() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folderA.mkdirs()); Path folderAPath = new Path(folderA.toURI()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(folderAPath); DirectoryStateHandle handle = snapshotDirectory.completeSnapshotAndGetHandle(); Assert.assertNotNull(handle); Assert.assertTrue(snapshotDirectory.cleanup()); Assert.assertTrue(folderA.isDirectory()); Assert.assertEquals(folderAPath, handle.getDirectory()); handle.discardState(); Assert.assertFalse(folderA.isDirectory()); Assert.assertTrue(folderA.mkdirs()); snapshotDirectory = SnapshotDirectory.permanent(folderAPath); Assert.assertTrue(snapshotDirectory.cleanup()); try { snapshotDirectory.completeSnapshotAndGetHandle(); Assert.fail(); } catch (IOException ignore) { } } |
### Question:
SnapshotDirectory { public static SnapshotDirectory temporary(@Nonnull Path directory) throws IOException { return new TemporarySnapshotDirectory(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer:
@Test public void temporary() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folder = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folder.mkdirs()); Path folderPath = new Path(folder.toURI()); SnapshotDirectory tmpSnapshotDirectory = SnapshotDirectory.temporary(folderPath); Assert.assertNull(tmpSnapshotDirectory.completeSnapshotAndGetHandle()); Assert.assertTrue(tmpSnapshotDirectory.cleanup()); Assert.assertFalse(folder.exists()); } |
### Question:
FsCheckpointStorage extends AbstractFsCheckpointStorage { @Override public CheckpointStateOutputStream createTaskOwnedStateStream() throws IOException { return new FsCheckpointStateOutputStream( taskOwnedStateDirectory, fileSystem, FsCheckpointStreamFactory.DEFAULT_WRITE_BUFFER_SIZE, fileSizeThreshold); } FsCheckpointStorage(
Path checkpointBaseDirectory,
@Nullable Path defaultSavepointDirectory,
JobID jobId,
int fileSizeThreshold); Path getCheckpointsDirectory(); @Override boolean supportsHighlyAvailableStorage(); @Override CheckpointStorageLocation initializeLocationForCheckpoint(long checkpointId); @Override CheckpointStreamFactory resolveCheckpointStorageLocation(
long checkpointId,
CheckpointStorageLocationReference reference); @Override CheckpointStateOutputStream createTaskOwnedStateStream(); }### Answer:
@Test public void testTaskOwnedStateStream() throws Exception { final List<String> state = Arrays.asList("Flopsy", "Mopsy", "Cotton Tail", "Peter"); final FsCheckpointStorage storage = new FsCheckpointStorage( Path.fromLocalFile(tmp.newFolder()), null, new JobID(), 10); final StreamStateHandle stateHandle; try (CheckpointStateOutputStream stream = storage.createTaskOwnedStateStream()) { assertTrue(stream instanceof FsCheckpointStateOutputStream); new ObjectOutputStream(stream).writeObject(state); stateHandle = stream.closeAndGetHandle(); } FileStateHandle fileStateHandle = (FileStateHandle) stateHandle; String parentDirName = fileStateHandle.getFilePath().getParent().getName(); assertEquals(FsCheckpointStorage.CHECKPOINT_TASK_OWNED_STATE_DIR, parentDirName); try (ObjectInputStream in = new ObjectInputStream(stateHandle.openInputStream())) { assertEquals(state, in.readObject()); } } |
### Question:
FileStateHandle implements StreamStateHandle { @Override public void discardState() throws Exception { FileSystem fs = getFileSystem(); fs.delete(filePath, false); } FileStateHandle(Path filePath, long stateSize); Path getFilePath(); @Override FSDataInputStream openInputStream(); @Override void discardState(); @Override long getStateSize(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testDisposeDeletesFile() throws Exception { File file = tempFolder.newFile(); writeTestData(file); assertTrue(file.exists()); FileStateHandle handle = new FileStateHandle(Path.fromLocalFile(file), file.length()); handle.discardState(); assertFalse(file.exists()); }
@Test public void testDisposeDoesNotDeleteParentDirectory() throws Exception { File parentDir = tempFolder.newFolder(); assertTrue(parentDir.exists()); File file = new File(parentDir, "test"); writeTestData(file); assertTrue(file.exists()); FileStateHandle handle = new FileStateHandle(Path.fromLocalFile(file), file.length()); handle.discardState(); assertFalse(file.exists()); assertTrue(parentDir.exists()); } |
### Question:
ResourceProfile implements Serializable, Comparable<ResourceProfile> { public boolean isMatching(ResourceProfile required) { if (cpuCores >= required.getCpuCores() && heapMemoryInMB >= required.getHeapMemoryInMB() && directMemoryInMB >= required.getDirectMemoryInMB() && nativeMemoryInMB >= required.getNativeMemoryInMB() && networkMemoryInMB >= required.getNetworkMemoryInMB()) { for (Map.Entry<String, Resource> resource : required.extendedResources.entrySet()) { if (!extendedResources.containsKey(resource.getKey()) || !extendedResources.get(resource.getKey()).getResourceAggregateType().equals(resource.getValue().getResourceAggregateType()) || extendedResources.get(resource.getKey()).getValue() < resource.getValue().getValue()) { return false; } } return true; } return false; } ResourceProfile(
double cpuCores,
int heapMemoryInMB,
int directMemoryInMB,
int nativeMemoryInMB,
int networkMemoryInMB,
Map<String, Resource> extendedResources); ResourceProfile(double cpuCores, int heapMemoryInMB); ResourceProfile(ResourceProfile other); double getCpuCores(); int getHeapMemoryInMB(); int getDirectMemoryInMB(); int getNativeMemoryInMB(); int getNetworkMemoryInMB(); int getMemoryInMB(); int getOperatorsMemoryInMB(); Map<String, Resource> getExtendedResources(); boolean isMatching(ResourceProfile required); @Override int compareTo(@Nonnull ResourceProfile other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourceProfile UNKNOWN; }### Answer:
@Test public void testUnknownMatchesUnknown() { assertTrue(ResourceProfile.UNKNOWN.isMatching(ResourceProfile.UNKNOWN)); } |
### Question:
MiniDispatcher extends Dispatcher { public CompletableFuture<ApplicationStatus> getJobTerminationFuture() { return jobTerminationFuture; } MiniDispatcher(
RpcService rpcService,
String endpointId,
Configuration configuration,
HighAvailabilityServices highAvailabilityServices,
ResourceManagerGateway resourceManagerGateway,
BlobServer blobServer,
HeartbeatServices heartbeatServices,
JobManagerMetricGroup jobManagerMetricGroup,
@Nullable String metricQueryServicePath,
ArchivedExecutionGraphStore archivedExecutionGraphStore,
JobManagerRunnerFactory jobManagerRunnerFactory,
FatalErrorHandler fatalErrorHandler,
@Nullable String restAddress,
HistoryServerArchivist historyServerArchivist,
JobGraph jobGraph,
JobClusterEntrypoint.ExecutionMode executionMode); CompletableFuture<ApplicationStatus> getJobTerminationFuture(); @Override CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout); @Override CompletableFuture<JobResult> requestJobResult(JobID jobId, Time timeout); }### Answer:
@Test public void testTerminationAfterJobCompletion() throws Exception { final MiniDispatcher miniDispatcher = createMiniDispatcher(ClusterEntrypoint.ExecutionMode.DETACHED); miniDispatcher.start(); try { dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get(); jobGraphFuture.get(); resultFuture.complete(archivedExecutionGraph); miniDispatcher.getJobTerminationFuture().get(); } finally { RpcUtils.terminateRpcEndpoint(miniDispatcher, timeout); } } |
### Question:
FileArchivedExecutionGraphStore implements ArchivedExecutionGraphStore { @Override @Nullable public ArchivedExecutionGraph get(JobID jobId) { try { return archivedExecutionGraphCache.get(jobId); } catch (ExecutionException e) { LOG.debug("Could not load archived execution graph for job id {}.", jobId, e); return null; } } FileArchivedExecutionGraphStore(
File rootDir,
Time expirationTime,
long maximumCacheSizeBytes,
ScheduledExecutor scheduledExecutor,
Ticker ticker); @Override int size(); @Override @Nullable ArchivedExecutionGraph get(JobID jobId); @Override void put(ArchivedExecutionGraph archivedExecutionGraph); @Override JobsOverview getStoredJobsOverview(); @Override Collection<JobDetails> getAvailableJobDetails(); @Nullable @Override JobDetails getAvailableJobDetails(JobID jobId); @Override void close(); }### Answer:
@Test public void testUnknownGet() throws IOException { final File rootDir = temporaryFolder.newFolder(); try (final FileArchivedExecutionGraphStore executionGraphStore = createDefaultExecutionGraphStore(rootDir)) { assertThat(executionGraphStore.get(new JobID()), Matchers.nullValue()); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.