auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized Environment findOne(String application, String profile, String label) { NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( getEnvironment()); Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); Environment result = delegate.findOne(application, profile, ""); result.setVersion(locations.getVersion()); result.setLabel(label); StringBuilder state = new StringBuilder(); if(locations.getTimestamp() > 0) { Date date = new Date(locations.getTimestamp()); state.append(DateFormat.getDateTimeInstance().format(date)); state.append(" "); } state.append(locations.getInfo()); result.setState(state.toString()); return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri()); }

Target:
public synchronized Environment findOne(String application, String profile, String label) { NativeEnvironmentRepository delegate = new NativeEnvironmentRepository( getEnvironment()); Locations locations = getLocations(application, profile, label); delegate.setSearchLocations(locations.getLocations()); Environment result = delegate.findOne(application, profile, ""); result.setVersion(locations.getVersion()); result.setLabel(label); StringBuilder additionalInfo = new StringBuilder(); if(locations.getTimestamp() > 0) { Date date = new Date(locations.getTimestamp()); additionalInfo.append(DateFormat.getDateTimeInstance().format(date)); additionalInfo.append(" "); } additionalInfo.append(locations.getInfo()); result.setDescription(additionalInfo.toString()); return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(), getUri()); }
Source:
public void registersExpectedExceptionMetrics() throws Exception { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", 0)); final HttpGet get = new HttpGet("http://localhost:" + server.getLocalPort() + "/"); final MetricName requestMetricName = MetricName.build("request"); final MetricName exceptionMetricName = MetricName.build("exception"); Thread serverThread = new Thread(() -> { try { final Socket socket = server.accept(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }); serverThread.start(); when(metricNameStrategy.getNameFor(anyString(), any(HttpRequest.class))) .thenReturn(requestMetricName); when(metricNameStrategy.getNameFor(anyString(), any(Exception.class))) .thenReturn(exceptionMetricName); try { client.execute(get); fail(); } catch (NoHttpResponseException expected) { } serverThread.interrupt(); serverThread.join(); assertThat(metricRegistry.getMeters()).containsKey(new MetricName("exception")); }

Target:
public void registersExpectedExceptionMetrics() throws Exception { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress("localhost", 0)); final HttpGet get = new HttpGet("http://localhost:" + server.getLocalPort() + "/"); final MetricName requestMetricName = MetricName.build("request"); final MetricName exceptionMetricName = MetricName.build("exception"); Thread serverThread = new Thread(() -> { try { final Socket socket = server.accept(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }); serverThread.start(); when(metricNameStrategy.getNameFor(anyString(), any(HttpRequest.class))) .thenReturn(requestMetricName); when(metricNameStrategy.getNameFor(anyString(), any(Exception.class))) .thenReturn(exceptionMetricName); try { client.execute(get); fail(); } catch (NoHttpResponseException expected) { assertThat(metricRegistry.getMeters()).containsKey(new MetricName("exception")); } finally { serverThread.interrupt(); serverThread.join(); } }
Source:
private Collection<Container> distributeForRequestedCount(List<Container> candidates, int count) { int candidateCount = candidates.size(); if (candidateCount == 0) { return candidates; } if (count <= 0 || count >= candidateCount) { return candidates; } else if (count == 1) { Collection<Container> targets = Collections.singleton(candidates.get(getAndRotateIndex(candidateCount))); return targets; } else { List<Container> targets = new ArrayList<Container>(); while (targets.size() < count) { targets.add(candidates.get(getAndRotateIndex(candidateCount))); } return targets; } }

Target:
private Collection<Container> distributeForRequestedCount(List<Container> candidates, int count) { int candidateCount = candidates.size(); if (candidateCount == 0) { return candidates; } if (count <= 0 || count >= candidateCount) { return candidates; } else if (count == 1) { return Collections.singleton(candidates.get(getAndRotateIndex(candidateCount))); } else { List<Container> targets = new ArrayList<Container>(); while (targets.size() < count) { targets.add(candidates.get(getAndRotateIndex(candidateCount))); } return targets; } }
Source:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { if (x instanceof KItem && ((KItem) x).klabel().toString().equals(KLabels.AND)) { flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }

Target:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { if (x instanceof KItem && ((KItem) x).klabel().name().equals(KLabels.AND)) { flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = cacheConfiguration(); dcc.clustering().cacheMode(cacheMode).partitionHandling().whenSplit(partitionHandling); createClusteredCaches(numMembersInCluster, dcc, new TransportFlags().withFD(true).withMerge(true)); waitForClusterToForm(CLUSTERED_LOCK_CACHE_NAME); }

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder dcc = cacheConfiguration(); dcc.clustering().cacheMode(CacheMode.REPL_SYNC).partitionHandling().whenSplit(partitionHandling); createClusteredCaches(numMembersInCluster, dcc, new TransportFlags().withFD(true).withMerge(true)); waitForClusterToForm(CLUSTERED_LOCK_CACHE_NAME); }
Source:
private <Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readSequentially( StreamStateHandle streamStateHandle, List<Handle> channelStateHandles, RecoveredChannelStateHandler<Info, Context> stateHandler) throws IOException { try (FSDataInputStream is = streamStateHandle.openInputStream()) { serializer.readHeader(is); for (Tuple2<Long, Info> offsetAndChannelInfo : extractOffsetsSorted(channelStateHandles)) { chunkReader.readChunk(is, offsetAndChannelInfo.f0, stateHandler, offsetAndChannelInfo.f1); } } }

Target:
private <Info, Context, Handle extends AbstractChannelStateHandle<Info>> void readSequentially( StreamStateHandle streamStateHandle, List<Handle> channelStateHandles, RecoveredChannelStateHandler<Info, Context> stateHandler) throws IOException, InterruptedException { try (FSDataInputStream is = streamStateHandle.openInputStream()) { serializer.readHeader(is); for (Tuple2<Long, Info> offsetAndChannelInfo : extractOffsetsSorted(channelStateHandles)) { chunkReader.readChunk(is, offsetAndChannelInfo.f0, stateHandler, offsetAndChannelInfo.f1); } } }
Source:
public ArrayList<Pojo> getResults(String query) { query = StringNormalizer.normalize(query); ArrayList<Pojo> records = new ArrayList<>(); int relevance; String appNameNormalized; for (Pojo pojo : pojos) { relevance = 0; appNameNormalized = pojo.nameNormalized; ArrayList<Pair<Integer, Integer>> matchPositions = new ArrayList<>(); int queryPos = 0; int appPos = 0; int beginMatch = 0; int matchedWordStarts = 0; int totalWordStarts = 0; boolean match = false; for (char cApp : appNameNormalized.toCharArray()) { if (queryPos < query.length() && query.charAt(queryPos) == cApp) { if (!match) { beginMatch = appPos; match = true; } if (Character.isUpperCase(pojo.name.charAt(appPos)) || appPos == 0 || Character.isWhitespace(pojo.name.charAt(appPos - 1))) matchedWordStarts += 1; queryPos++; } else if (match) { matchPositions.add(Pair.create(beginMatch, appPos)); match = false; } if (Character.isUpperCase(pojo.name.charAt(appPos)) || appPos == 0 || Character.isWhitespace(pojo.name.charAt(appPos - 1))) totalWordStarts += 1; appPos++; } if (match) { matchPositions.add(Pair.create(beginMatch, appPos)); } if (queryPos == query.length()) { relevance += 20; relevance += (int)(((double)queryPos / appNameNormalized.length()) * 30); relevance += (int)(((double)matchedWordStarts / totalWordStarts) * 50); relevance *= (0.2 + 0.8 * (1.0 / matchPositions.size())); } if (relevance > 0) { pojo.setDisplayNameHighlightRegion(matchPositions); pojo.relevance = relevance; records.add(pojo); } } return records; }

Target:
public ArrayList<Pojo> getResults(String query) { query = StringNormalizer.normalize(query); ArrayList<Pojo> records = new ArrayList<>(); int relevance; String appNameNormalized; ArrayList<Pair<Integer, Integer>> matchPositions; for (Pojo pojo : pojos) { relevance = 0; appNameNormalized = pojo.nameNormalized; matchPositions = null; int queryPos = 0; int appPos = 0; int beginMatch = 0; int matchedWordStarts = 0; int totalWordStarts = 0; boolean match = false; for (char cApp : appNameNormalized.toCharArray()) { if (queryPos < query.length() && query.charAt(queryPos) == cApp) { if (!match) { beginMatch = appPos; match = true; } if (Character.isUpperCase(pojo.name.charAt(appPos)) || appPos == 0 || Character.isWhitespace(pojo.name.charAt(appPos - 1))) matchedWordStarts += 1; queryPos++; } else if (match) { if (matchPositions == null) matchPositions = new ArrayList<>(); matchPositions.add(Pair.create(beginMatch, appPos)); match = false; } if (Character.isUpperCase(pojo.name.charAt(appPos)) || appPos == 0 || Character.isWhitespace(pojo.name.charAt(appPos - 1))) totalWordStarts += 1; appPos++; } if (match) { if (matchPositions == null) matchPositions = new ArrayList<>(); matchPositions.add(Pair.create(beginMatch, appPos)); } if (queryPos == query.length() && matchPositions != null) { relevance += (int)(((double)queryPos / appNameNormalized.length()) * 40); relevance += (int)(((double)matchedWordStarts / totalWordStarts) * 60); relevance *= (0.2 + 0.8 * (1.0 / matchPositions.size())); } if (relevance > 0) { pojo.setDisplayNameHighlightRegion(matchPositions); pojo.relevance = relevance; records.add(pojo); } } return records; }
Source:
public synchronized boolean tryLock() { _baseDataAccessor.subscribeDataChanges(_lockPath, this); LockUpdater updater = new LockUpdater( new LockInfo(_userId, _lockMsg, getNonOverflowTimestamp(_leaseTimeout), _priority, _waitingTimeout, _cleanupTimeout, null, 0, 0, 0)); boolean updateResult = _baseDataAccessor.update(_lockPath, updater, AccessOption.PERSISTENT); if (_isPending) { try { wait(_pendingTimeout); } catch (InterruptedException e) { throw new HelixException( String.format("Interruption happened while %s is waiting for the " + "lock", _userId), e); } if (!_isLocked) { if (_isPreempted) { return false; } else { if (_isForceful) { ZNRecord znRecord = composeNewOwnerRecord(); LOG.info("Updating Zookeeper with new owner information", _userId); _baseDataAccessor .update(_lockPath, new ZNRecordUpdater(znRecord), AccessOption.PERSISTENT); return true; } else { throw new HelixException("Cleanup has not been finished by lock owner"); } } } } return updateResult; }

Target:
public boolean tryLock() { _baseDataAccessor.subscribeDataChanges(_lockPath, this); LockUpdater updater = new LockUpdater( new LockInfo(_userId, _lockMsg, getNonOverflowTimestamp(_leaseTimeout), _priority, _waitingTimeout, _cleanupTimeout, null, 0, 0, 0)); boolean updateResult = _baseDataAccessor.update(_lockPath, updater, AccessOption.PERSISTENT); ENDING. if (_lockStatus != LockConstants.LockStatus.PENDING) { if (!updateResult) { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); } return updateResult; } try { _countDownLatch.await(_pendingTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new HelixException( String.format("Interruption happened while %s is waiting for the lock", _userId), e); } if (_lockStatus != LockConstants.LockStatus.LOCKED) { if (_lockStatus == LockConstants.LockStatus.PREEMPTED) { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); return false; } if (_isForceful) { ZNRecord znRecord = composeNewOwnerRecord(); ForcefulUpdater forcefulUpdater = new ForcefulUpdater(new LockInfo(znRecord)); LOG.info("Updating Zookeeper with new owner information", _userId); _baseDataAccessor.update(_lockPath, forcefulUpdater, AccessOption.PERSISTENT); return true; } else { _baseDataAccessor.unsubscribeDataChanges(_lockPath, this); throw new HelixException("Cleanup has not been finished by lock owner"); } } return true; }
Source:
public String getName() { String name = super.getName(); if (name == null || name.isEmpty()) { return ""; } else { return name; } }

Target:
public String getName() { String name = super.getName(); if (StringUtils.isEmpty(name)) { return ""; } else { return name; } }
Source:
public void testListDroplets() { List<Droplet> droplets = api.getDropletApi().list(); assertTrue(droplets.size() > 0, "Droplet list should not be empty"); }

Target:
public void testListDroplets() { List<Droplet> droplets = api.getDropletApi().list(); assertFalse(droplets.isEmpty(), "Droplet list should not be empty"); }
Source:
public List<String> listAllConsumers() { long now = System.currentTimeMillis(); if (allConsumers == null || (now - allConsumersTime) > ALL_CONSUMERS_CACHE_TIMEOUT_MS) { try { allConsumers = getAdminClient().listConsumerGroups() .all() .get() .stream() .map(group -> group.groupId()) .collect(Collectors.toList()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { throw new StreamRuntimeException(e); } if (!allConsumers.isEmpty()) { allConsumersTime = now; } } return allConsumers; }

Target:
public synchronized List<String> listAllConsumers() { long now = System.currentTimeMillis(); if (allConsumers == null || (now - allConsumersTime) > ALL_CONSUMERS_CACHE_TIMEOUT_MS) { try { allConsumers = adminClient.listConsumerGroups() .all() .get() .stream() .map(ConsumerGroupListing::groupId) .collect(Collectors.toList()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { throw new StreamRuntimeException(e); } if (!allConsumers.isEmpty()) { allConsumersTime = now; } } return allConsumers; }
Source:
public void populateEntityDictionary(EntityDictionary dictionary) { if (dynamicCompiledClasses != null && dynamicCompiledClasses.size() != 0) { dynamicCompiledClasses.forEach(dynamicLoadedClass -> dictionary.bindEntity(dynamicLoadedClass, Collections.singleton(Join.class))); } ClassScanner.getAnnotatedClasses(AGGREGATION_STORE_CLASSES).forEach( cls -> dictionary.bindEntity(getType(cls), Collections.singleton(Join.class)) ); }

Target:
public void populateEntityDictionary(EntityDictionary dictionary) { if (dynamicCompiledClasses != null && dynamicCompiledClasses.size() != 0) { dynamicCompiledClasses.forEach(dynamicLoadedClass -> dictionary.bindEntity(dynamicLoadedClass, Collections.singleton(Join.class))); } ClassScanner.getAnnotatedClasses(AGGREGATION_STORE_CLASSES).forEach( cls -> dictionary.bindEntity(cls, Collections.singleton(Join.class)) ); }
Source:
public void postLoadingHook(ResourceSet resourceSet, Collection<? extends URI> uris) { for (Resource resource : resourceSet.getResources()) { if ((resource.getURI().fileExtension()).equals("notation")) { EList<EObject> contents = resource.getContents(); for (EObject object : contents) { if (object instanceof CSSDiagramImpl) { Diagram diagram = (Diagram)object; diagramMigration(getEditingDomain(resourceSet), diagram); } } } } }

Target:
public void postLoadingHook(ResourceSet resourceSet, Collection<? extends URI> uris) { for (Resource resource : resourceSet.getResources()) { if ("notation".equals(resource.getURI().fileExtension())) { EList<EObject> contents = resource.getContents(); for (EObject object : contents) { if (object instanceof Diagram) { Diagram diagram = (Diagram)object; diagramMigration(getEditingDomain(resourceSet), diagram); } } } } }
Source:
public void testFoldLeftWithDirectionDependentOperationOnNonEmptyList() { assertEquals( new Integer(0), ListOps.foldLeft( Arrays.asList(2, 5), 5, (accumulation, current) -> accumulation / current)); }

Target:
public void testFoldLeftWithDirectionDependentOperationOnNonEmptyList() { assertEquals( new Integer(0), ListOps.foldLeft( Arrays.asList(2, 5), 5, (x, y) -> x / y)); }
Source:
public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events cursors events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(PUT, "/event-types/**").access(hasScope(eventTypeWriteScope)) .antMatchers(POST, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }

Target:
public void configure(final HttpSecurity http) throws Exception { LOG.info("Authentication mode: " + settings.getAuthMode()); if (settings.getAuthMode() == SecuritySettings.AuthMode.FULL) { http.authorizeRequests() .antMatchers(GET, "/event-types events events cursors cursors events **").access(hasScope(nakadiAdminScope)) .antMatchers(POST, "/event-types **").access(hasScope(eventStreamReadScope)) .antMatchers(POST, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/subscriptions/**").access(hasScope(eventStreamReadScope)) .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else if (settings.getAuthMode() == SecuritySettings.AuthMode.BASIC) { http.authorizeRequests() .antMatchers(GET, "/health/**").permitAll() .anyRequest().access(hasScope(uidScope)); } else { http.authorizeRequests() .anyRequest().permitAll(); } }
Source:
public void sweep(Collection<WriteInfo> writes, Sweeper sweeper) { Map<TableReference, Map<Cell, Long>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, Long>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, Long> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, false); } else { kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, true); } }); } catch (IllegalArgumentException e) { if (e.getCause() instanceof TableMappingNotFoundException || e.getMessage().endsWith("does not exist")) { log.debug("Could not resolve full name for table reference {}, " + "assuming table has been deleted and therefore relevant cells as well.", LoggingArgs.tableRef(entry.getKey())); log.trace("Stack trace follows:", e); } else { throw e; } } } }

Target:
public void sweep(Collection<WriteInfo> writes, Sweeper sweeper) { Map<TableReference, Map<Cell, Long>> maxTimestampByCell = writesPerTable(writes, sweeper); for (Map.Entry<TableReference, Map<Cell, Long>> entry : maxTimestampByCell.entrySet()) { try { Iterables.partition(entry.getValue().keySet(), SweepQueueUtils.BATCH_SIZE_KVS) .forEach(cells -> { Map<Cell, Long> maxTimestampByCellPartition = cells.stream() .collect(Collectors.toMap(Function.identity(), entry.getValue()::get)); follower.run(entry.getKey(), maxTimestampByCellPartition.keySet()); if (sweeper.shouldAddSentinels()) { kvs.addGarbageCollectionSentinelValues(entry.getKey(), maxTimestampByCellPartition.keySet()); kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, false); } else { kvs.deleteAllTimestamps(entry.getKey(), maxTimestampByCellPartition, true); } }); } catch (IllegalArgumentException e) { if (e.getCause() instanceof TableMappingNotFoundException || e.getMessage().endsWith("does not exist")) { log.warn("Could not resolve full name for table reference {}, " + "assuming table has been deleted and therefore relevant cells as well.", LoggingArgs.tableRef(entry.getKey())); log.debug("Stack trace follows:", e); } else { throw e; } } } }
Source:
public static List<IpNode> fromString(String addrString, int defaultPort) { List<IpNode> ipNodes = new ArrayList<IpNode>(); int port; for (String singleAddrString : addrString.split(",")) { Matcher addrMatch = ADDR_PATTERN.matcher(singleAddrString); if (addrMatch.matches()) { port = (addrMatch.group(2).isEmpty()) ? defaultPort : Integer.valueOf(addrMatch.group(2)); ipNodes.add(new IpNode(addrMatch.group(1), port)); } else { logger.warn("Node definition is not valid.", singleAddrString); } } return ipNodes; }

Target:
public static List<IpNode> fromString(String addrString, int defaultPort) throws IllegalArgumentException { List<IpNode> ipNodes = new ArrayList<IpNode>(); int port; for (String singleAddrString : addrString.split(",")) { Matcher addrMatch = ADDR_PATTERN.matcher(singleAddrString); if (addrMatch.matches()) { port = (addrMatch.group(2).isEmpty()) ? defaultPort : Integer.valueOf(addrMatch.group(2)); ipNodes.add(new IpNode(addrMatch.group(1), port)); } else { throw new IllegalArgumentException(String.format("Node definition is not valid.", singleAddrString)); } } return ipNodes; }
Source:
public NodeSelectionStrategy getNodeSelectionStrategy() { return NodeSelectionStrategy.HARD_AFFINITY; }

Target:
public NodeSelectionStrategy getNodeSelectionStrategy() { return HARD_AFFINITY; }
Source:
private ValidationResult hostExists() { if (getVds() == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST); } return ValidationResult.VALID; }

Target:
private ValidationResult hostExists() { return getVds() == null ? new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_HOST_NOT_EXIST) : ValidationResult.VALID; }
Source:
private Optional<Class<Event>> getEventForTransition(ChargeStatus fromChargeStatus, ChargeEventEntity chargeEventEntity) { Optional<Class<Event>> eventForTransition = paymentGatewayStateTransitions .getEventForTransition(fromChargeStatus, chargeEventEntity.getStatus()); if (eventForTransition.isEmpty()) { Optional<ChargeStatus> intermediateChargeStatus = paymentGatewayStateTransitions .getIntermediateChargeStatus(fromChargeStatus, chargeEventEntity.getStatus()); if (intermediateChargeStatus.isPresent() && INTEMEDIATE_READY_STATES.contains(intermediateChargeStatus.get())) { eventForTransition = paymentGatewayStateTransitions .getEventForTransition(intermediateChargeStatus.get(), chargeEventEntity.getStatus()); } else { logger.info("Historical Event emitter for Charge and Event - Couldn't derive event for transition from to [{}]", chargeEventEntity.getChargeEntity().getId(), chargeEventEntity.getId(), fromChargeStatus, chargeEventEntity.getStatus() ); } } return eventForTransition; }

Target:
private Optional<Class<Event>> getEventForTransition(ChargeStatus fromChargeStatus, ChargeEventEntity chargeEventEntity) { Optional<Class<Event>> eventForTransition = paymentGatewayStateTransitions .getEventForTransition(fromChargeStatus, chargeEventEntity.getStatus()); if (eventForTransition.isEmpty()) { Optional<ChargeStatus> intermediateChargeStatus = paymentGatewayStateTransitions .getIntermediateChargeStatus(fromChargeStatus, chargeEventEntity.getStatus()); if (intermediateChargeStatus.isPresent() && INTERMEDIATE_READY_STATES.contains(intermediateChargeStatus.get())) { eventForTransition = paymentGatewayStateTransitions .getEventForTransition(intermediateChargeStatus.get(), chargeEventEntity.getStatus()); } else { logger.info("Historical Event emitter for Charge and Event - Couldn't derive event for transition from to [{}]", chargeEventEntity.getChargeEntity().getId(), chargeEventEntity.getId(), fromChargeStatus, chargeEventEntity.getStatus() ); } } return eventForTransition; }
Source:
public void optionalAbsent() { Optional<Integer> shouldBeAbsent = db.getSharedHandle().createQuery("select intValue from something where intValue = 100") .mapTo(int.class) .collect(GuavaCollectors.toOptional()); assertThat(shouldBeAbsent.isPresent()).isFalse(); }

Target:
public void optionalAbsent() { Optional<Integer> shouldBeAbsent = db.getSharedHandle().createQuery("select intValue from something where intValue = 100") .mapTo(int.class) .collect(GuavaCollectors.toOptional()); assertThat(shouldBeAbsent).isAbsent(); }
Source:
public LogReplicationEntry read(UUID logEntryRequestId) throws TrimmedException, IllegalTransactionStreamsException { List<OpaqueEntry> opaqueEntryList = new ArrayList<>(); int currentEntrySize = 0; int currentMsgSize = 0; try { while (currentMsgSize < maxDataSizePerMsg && !hasNoiseData) { if (lastOpaqueEntry != null && shouldProcess(lastOpaqueEntry)) { currentEntrySize = ReaderUtility.calculateOpaqueEntrySize(lastOpaqueEntry); if (!checkSizeOK(lastOpaqueEntry, currentMsgSize, currentEntrySize)) { break; } opaqueEntryList.add(lastOpaqueEntry); currentMsgSize += currentEntrySize; lastOpaqueEntry = null; } if (hasNoiseData) { break; } if (!txOpaqueStream.hasNext()) { break; } lastOpaqueEntry = txOpaqueStream.next(); } log.trace("Generate LogEntryDataMessage size with entries for maxDataSizePerMsg {}. lastEnry size {}", currentMsgSize, opaqueEntryList.size(), maxDataSizePerMsg, lastOpaqueEntry == null? 0 : currentEntrySize); if (opaqueEntryList.size() == 0 && hasNoiseData) { throw new IllegalTransactionStreamsException("There are noisy streams in the transaction log entry"); } if (opaqueEntryList.size() == 0) { return null; } LogReplicationEntry txMessage = generateMessageWithOpaqueEntryList(opaqueEntryList, logEntryRequestId); return txMessage; } catch (Exception e) { log.warn("Caught an exception {}", e); throw e; } }

Target:
public LogReplicationEntry read(UUID logEntryRequestId) throws TrimmedException, IllegalTransactionStreamsException { List<OpaqueEntry> opaqueEntryList = new ArrayList<>(); int currentEntrySize = 0; int currentMsgSize = 0; try { while (currentMsgSize < maxDataSizePerMsg && !hasNoiseData) { if (lastOpaqueEntry != null && shouldProcess(lastOpaqueEntry)) { currentEntrySize = ReaderUtility.calculateOpaqueEntrySize(lastOpaqueEntry); if (!checkValidSize(lastOpaqueEntry, currentMsgSize, currentEntrySize)) { break; } opaqueEntryList.add(lastOpaqueEntry); currentMsgSize += currentEntrySize; lastOpaqueEntry = null; } if (hasNoiseData) { break; } if (!txOpaqueStream.hasNext()) { break; } lastOpaqueEntry = txOpaqueStream.next(); } log.trace("Generate LogEntryDataMessage size with entries for maxDataSizePerMsg {}. lastEnry size {}", currentMsgSize, opaqueEntryList.size(), maxDataSizePerMsg, lastOpaqueEntry == null? 0 : currentEntrySize); if (opaqueEntryList.size() == 0 && hasNoiseData) { throw new IllegalTransactionStreamsException("There are noisy streams in the transaction log entry"); } if (opaqueEntryList.size() == 0) { return null; } LogReplicationEntry txMessage = generateMessageWithOpaqueEntryList(opaqueEntryList, logEntryRequestId); return txMessage; } catch (Exception e) { log.warn("Caught an exception {}", e); throw e; } }
Source:
public Transceiver getCommentCount(Article article) { return new Transceiver() { @Override protected Object getData() throws IOException { Object result = hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT NEW MAP(COUNT(*) AS all, SUM(CASE WHEN ann.parentID IS NULL THEN 1 ELSE 0 END) AS root) " + "FROM Annotation ann " + "WHERE ann.articleID = :articleID "); query.setParameter("articleID", article.getID()); return query.uniqueResult(); }); return result; } @Override protected Calendar getLastModifiedDate() throws IOException { return null; } }; }

Target:
public Transceiver getCommentCount(Article article) { return new Transceiver() { @Override protected Map<String, Object> getData() throws IOException { Map<String, Object> result = (Map<String, Object>) hibernateTemplate.execute(session -> { Query query = session.createQuery("" + "SELECT NEW MAP(COUNT(*) AS all, SUM(CASE WHEN ann.parentID IS NULL THEN 1 ELSE 0 END) AS root) " + "FROM Annotation ann " + "WHERE ann.articleID = :articleID "); query.setParameter("articleID", article.getID()); return query.uniqueResult(); }); return result; } @Override protected Calendar getLastModifiedDate() throws IOException { return null; } }; }
Source:
public PagingResponse<CandidateApplicationDTO> getApplicationsByCandidateId( Long candidateId, int page, int size) { Assert.notNull(candidateId); CandidateEntity candidateEntity = candidateRepository.findOne(candidateId); Pageable pageRequest = new PageRequest(page, size); Page<ApplicationEntity> pageResult = applicationsRepository.findByCandidateEntity(candidateEntity, pageRequest); List<ApplicationEntity> applicationEntities = pageResult.getContent(); List<CandidateApplicationDTO> candidateApplicationDTOs = converterService.convert(applicationEntities, CandidateApplicationDTO.class); Long total = pageResult.getTotalElements(); PagingResponse<CandidateApplicationDTO> response = new PagingResponse<>(total, candidateApplicationDTOs); return response; }

Target:
public PagingResponse<CandidateApplicationDTO> getApplicationsByCandidateId( Long candidateId, int page, int size) { Assert.notNull(candidateId); CandidateEntity candidateEntity = candidateRepository.findOne(candidateId); Pageable pageRequest = new PageRequest(page, size); final Page<ApplicationEntity> pageResult = applicationsRepository.findByCandidateEntity(candidateEntity, pageRequest); List<CandidateApplicationDTO> candidateApplicationDTOs = converterService.convert(pageResult.getContent(), CandidateApplicationDTO.class); candidateApplicationDTOs = candidateApplicationDTOs.stream() .sorted((m1, m2) -> m2.getModificationDate().compareTo(m1.getModificationDate())) .collect(Collectors.toList()); return new PagingResponse<>(pageResult.getTotalElements(), candidateApplicationDTOs); }
Source:
public void dismiss() { DialogFragment dialog = (DialogFragment) activity.getSupportFragmentManager().findFragmentByTag(BOTTOM_SHEET_FRAGMENT_TAG); if (dialog != null) { dialog.dismiss(); } if (currentDialog != null && currentDialog.isShowing()) { currentDialog.dismiss(); } currentDialog = null; }

Target:
public void dismiss() { DialogFragment dialog = (DialogFragment) activity.getSupportFragmentManager().findFragmentByTag(BOTTOM_SHEET_FRAGMENT_TAG); if (dialog != null) { dialog.dismiss(); } if (currentDialog != null) { currentDialog.setOnDismissListener(null); currentDialog.dismiss(); } currentDialog = null; }
Source:
public static <T> void checkPresence(Optional<T> opt, String errorMessage) { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }

Target:
private static <T> void checkPresence(Optional<T> opt, String errorMessage) { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }
Source:
public void setup() { this.map = targetInstance.getMap(name); generatedIds = generateStrings(keyCount, idLength); }

Target:
public void setup() { this.map = targetInstance.getMap(name); }
Source:
public static void main(String[] args) { FormTrainingAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https://{endpoint}.cognitiveservices.azure.com/") .buildAsyncClient().getFormTrainingAsyncClient(); String trainingSetSource = "https://training-SAS-URL"; PollerFlux<OperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingSetSource, true); CustomFormModel customFormModel = trainingPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().equals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)) { return trainingOperationResponse.getFinalResult(); } else { System.out.println("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus()); return Mono.empty(); } }).block(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }

Target:
public static void main(String[] args) { FormTrainingAsyncClient client = new FormRecognizerClientBuilder() .apiKey(new AzureKeyCredential("{api_Key}")) .endpoint("https://{endpoint}.cognitiveservices.azure.com/") .buildAsyncClient().getFormTrainingAsyncClient(); String trainingSetSource = "{training-set-SAS-URL}"; PollerFlux<OperationResult, CustomFormModel> trainingPoller = client.beginTraining(trainingSetSource, true); CustomFormModel customFormModel = trainingPoller .last() .flatMap(trainingOperationResponse -> { if (trainingOperationResponse.getStatus().equals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED)) { return trainingOperationResponse.getFinalResult(); } else { return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:" + trainingOperationResponse.getStatus())); } }).block(); System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }
Source:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { Thread.sleep( 1000 ); population.flip(); populations.remove( population ); } catch ( Throwable t ) { fail( population, t ); } } }

Target:
void flipAfterPopulation() { for ( IndexPopulation population : populations ) { try { population.flip(); } catch ( Throwable t ) { fail( population, t ); } } }
Source:
private void increaseComplexity(Tree tree, int increase) { complexity += increase; if(!ignored.contains(tree)) { int reportedValue = increase - nestingAdjustment; String message = "+" + reportedValue; if (reportedValue > 1) { message += " (incl " + (reportedValue - 1) + " for nesting)"; } nestingAdjustment = 0; flow.add(new JavaFileScannerContext.Location(message, tree)); } }

Target:
private void increaseComplexity(Tree tree, int increase) { complexity += increase; if (ignoreNesting) { flow.add(new JavaFileScannerContext.Location("+1", tree)); ignoreNesting = false; } else if (!ignored.contains(tree)) { String message = "+" + increase; if (increase > 1) { message += " (incl " + (increase - 1) + " for nesting)"; } flow.add(new JavaFileScannerContext.Location(message, tree)); } }
Source:
public void exact_match_in_one_qualifier() throws IOException { ComponentDto project = db.components().insertComponent(newProjectDto(organization)); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project); SuggestionsWsResponse response = SuggestionsWsResponse.parseFrom(actionTester.newRequest() .setMethod("POST") .setMediaType(PROTOBUF) .setParam(URL_PARAM_QUERY, project.getKey()) .execute() .getInputStream()); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(SuggestionsWsResponse.Qualifier::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(SuggestionsWsResponse.Qualifier::getItemsList) .extracting(WsComponents.Component::getKey, WsComponents.Component::getOrganization) .containsExactly(tuple(project.getKey(), organization.getKey())); }

Target:
public void exact_match_in_one_qualifier() throws Exception { ComponentDto project = db.components().insertComponent(newProjectDto(organization)); componentIndexer.indexOnStartup(null); authorizationIndexerTester.allowOnlyAnyone(project); SuggestionsWsResponse response = actionTester.newRequest() .setMethod("POST") .setParam(PARAM_QUERY, project.getKey()) .executeProtobuf(SuggestionsWsResponse.class); assertThat(response.getResultsList()) .filteredOn(q -> q.getItemsCount() > 0) .extracting(Category::getQ) .containsExactly(Qualifiers.PROJECT); assertThat(response.getResultsList()) .flatExtracting(Category::getItemsList) .extracting(Suggestion::getKey, Suggestion::getOrganization) .containsExactly(tuple(project.getKey(), organization.getKey())); }
Source:
public AuditProto.AttemptAuditEventResult convert(AttemptAuditEventResult source) { AuditProto.AttemptAuditEventResult.Builder attemptAuditEventResultBuilder = builderProvider.prepareBuilderForCreateAuditEvent(source); updateResultEventData(attemptAuditEventResultBuilder, source.getResultEventData()); return attemptAuditEventResultBuilder.build(); }

Target:
public AuditProto.AttemptAuditEventResult convert(AttemptAuditEventResult source) { AuditProto.AttemptAuditEventResult.Builder builder = builderProvider.getNewAttemptAuditEventResultBuilder() .setId(source.getId()) .setResultCode(source.getResultCode()); doIfTrue(source.getResultMessage(), StringUtils::isNotEmpty, builder::setResultMessage); updateResultEventData(builder, source.getResultEventData()); return builder.build(); }
Source:
public static void checkTableIsWritable(Table table, boolean writesToNonManagedTablesEnabled) { if (!writesToNonManagedTablesEnabled && !table.getTableType().equals(MANAGED_TABLE.toString()) && !table.isTemporary()) { throw new PrestoException(NOT_SUPPORTED, "Cannot write to non-managed Hive table"); } checkWritable( new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), getProtectMode(table), table.getParameters(), table.getStorage()); }

Target:
public static void checkTableIsWritable(Table table, boolean writesToNonManagedTablesEnabled) { PrestoTableType tableType = table.getTableType(); if (!writesToNonManagedTablesEnabled && !tableType.equals(MANAGED_TABLE) && !tableType.equals(TEMPORARY_TABLE)) { throw new PrestoException(NOT_SUPPORTED, "Cannot write to non-managed Hive table"); } checkWritable( new SchemaTableName(table.getDatabaseName(), table.getTableName()), Optional.empty(), getProtectMode(table), table.getParameters(), table.getStorage()); }
Source:
private ResponseEntity<String> sendPasswordLostMail(User parsedUser, String oneTimePassword) throws MessagingException, IOException { Optional<String> email = RegistrationHelper.extractSendToEmail(parsedUser); if (!email.isPresent()) { LOGGER.log(Level.WARNING, "No primary email found!"); return new ResponseEntity<>("{\"error\":\"No primary email found!\"}", HttpStatus.BAD_REQUEST); } StringBuilder activateURL = new StringBuilder(passwordlostLinkPrefix); activateURL.append("userId=").append(parsedUser.getId()); activateURL.append("&oneTimePassword=").append(oneTimePassword); Map<String, String> vars = new HashMap<>(); vars.put("$PASSWORDLOSTURL", activateURL.toString()); InputStream mailContentStream = mailSender.getEmailContentAsStream("/WEB-INF/registration/passwordlostmail-content.txt", pathToEmailContent, context); if (mailContentStream == null) { LOGGER.log(Level.SEVERE, "Cant open registermail-content.txt on classpath! Please configure!"); return new ResponseEntity<>( "{\"error\":\"Cant open registermail-content.txt on classpath! Please configure!\"}", HttpStatus.INTERNAL_SERVER_ERROR); } mailSender.sendMail(passwordlostMailFrom, email.get(), passwordlostMailSubject, mailContentStream, vars); return new ResponseEntity<>(HttpStatus.OK); }

Target:
private ResponseEntity<String> sendPasswordLostMail(User parsedUser, String oneTimePassword) throws MessagingException, IOException { Optional<String> email = RegistrationHelper.extractSendToEmail(parsedUser); if (!email.isPresent()) { LOGGER.log(Level.WARNING, "Could not change password. No email of user " + parsedUser.getUserName() + " found!"); return new ResponseEntity<>("{\"error\":\"Could not change password. No email of user " + parsedUser.getUserName() + " found!\"}", HttpStatus.BAD_REQUEST); } StringBuilder activateURL = new StringBuilder(passwordlostLinkPrefix); activateURL.append("userId=").append(parsedUser.getId()); activateURL.append("&oneTimePassword=").append(oneTimePassword); Map<String, String> vars = new HashMap<>(); vars.put("$PASSWORDLOSTURL", activateURL.toString()); InputStream mailContentStream = mailSender.getEmailContentAsStream("/WEB-INF/registration/passwordlostmail-content.txt", pathToEmailContent, context); if (mailContentStream == null) { LOGGER.log(Level.SEVERE, "Cant open registermail-content.txt on classpath! Please configure!"); return new ResponseEntity<>( "{\"error\":\"Cant open registermail-content.txt on classpath! Please configure!\"}", HttpStatus.INTERNAL_SERVER_ERROR); } mailSender.sendMail(passwordlostMailFrom, email.get(), passwordlostMailSubject, mailContentStream, vars); return new ResponseEntity<>(HttpStatus.OK); }
Source:
public synchronized void init(ByteBuffer buffer, int position) { MergingDigest emptyDigest = new MergingDigest(compression); addToMap(buffer, position, emptyDigest); }

Target:
public void init(ByteBuffer buffer, int position) { MergingDigest emptyDigest = new MergingDigest(compression); addToCache(buffer, position, emptyDigest); }
Source:
public static Object[][] adsVUAPTopDesktop() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), ImmutableMap.of("src", "gpt", "slotName", AdsContent.TOP_LB) } }; }

Target:
public static Object[][] adsVUAPTopDesktop() { return new Object[][]{ { new Page("project43", "SyntheticTests/VUAP"), AdsContent.TOP_LB, String.format( "google_ads_iframe_/5441/wka.life/_project43 AdsContent.TOP_LB ) } }; }
Source:
public void expireDynamicConfigWithCustomExpiration() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); Thread.sleep(6000); HeisenbergExtension anotherConfig = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); assertExpired(config, 5000, 1000); assertInitialised(config); }

Target:
public void expireDynamicConfigWithCustomExpiration() throws Exception { HeisenbergExtension config = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); try { assertExpired(config, 5000, 1000); } catch (AssertionError e) { HeisenbergExtension anotherConfig = invokeDynamicConfig("dynamicWithCustomExpiration", "heisenbergWithCustomExpiration", "Walter Jr."); } assertExpired(config, 5000, 1000); assertInitialised(config); }
Source:
public static boolean isWikimediaHost(String host) { int MAX_REFERER_LENGTH = 5000; if(host.length() > MAX_REFERER_LENGTH) return false; return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }

Target:
public static boolean isWikimediaHost(String host) { if (host.length() > MAX_ADDRESS_LENGTH) return false; return ( Utilities.patternIsFound(URI_HOST_WIKIMEDIA_DOMAIN_PATTERN, host) || Utilities.patternIsFound(URI_HOST_OTHER_PROJECTS_PATTERN, host) || Utilities.patternIsFound(URI_HOST_PROJECT_DOMAIN_PATTERN, host) ); }
Source:
private void generateAPIResponse(ServletRequest request, ServletResponse response) throws IOException { response.setContentType(request.getContentType()); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", "Server is under maintenance mode, please try later."); response.getWriter().print(jsonObject); ((HttpServletResponse) response).setStatus(503); }

Target:
private void generateAPIResponse(ServletRequest request, ServletResponse response) { try { HttpServletRequest httpRequest = (HttpServletRequest) request; String message = "Server is under maintenance mode, please try later."; if (requestIsOfType(JSON, httpRequest)) { response.setContentType("application/json"); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("message", message); response.getWriter().print(jsonObject); } else if (requestIsOfType(XML, httpRequest)) { response.setContentType("application/xml"); String xml = String.format("<message> %s </message>", message); response.getWriter().print(xml); } else { generateHTMLResponse(response); } } catch (IOException e) { LOGGER.error(String.format("General IOException", e.getMessage())); } ((HttpServletResponse) response).setStatus(503); }
Source:
public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { Transaction tx = getFromOperation(get); if (tx != null) { boolean excludeCurrentWritePtr = isAttributeSet(get, TxConstants.TX_EXCLUDE_CURRENT_WRITE); projectFamilyDeletes(get); get.setMaxVersions(); get.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = Filters.combine(getTransactionFilter(tx, ScanType.USER_SCAN, excludeCurrentWritePtr), get.getFilter()); get.setFilter(newFilter); } }

Target:
public void preGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { Transaction tx = getFromOperation(get); if (tx != null) { projectFamilyDeletes(get); get.setMaxVersions(); get.setTimeRange(TxUtils.getOldestVisibleTimestamp(ttlByFamily, tx), TxUtils.getMaxVisibleTimestamp(tx)); Filter newFilter = Filters.combine(getTransactionFilter(tx, ScanType.USER_SCAN), get.getFilter()); get.setFilter(newFilter); } }
Source:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); startDefaultAgent(testHost()); awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES); final JobId jobId = createJob(testJobName, testJobVersion, BUSYBOX, IDLE_COMMAND, DateTime.now().plusSeconds(10).toDate()); deployJob(jobId, testHost()); TaskStatus taskStatus = awaitJobState( client, testHost(), jobId, RUNNING, WAIT_TIMEOUT_SECONDS, SECONDS); Polling.await(3, MINUTES, new Callable<JobId>() { @Override public JobId call() throws Exception { if (client.jobs().get().containsKey(jobId)) { return null; } else { return jobId; } } }); final ContainerExit exit1 = docker.waitContainer(taskStatus.getContainerId()); assertThat(exit1.statusCode(), is(-1)); }

Target:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); startDefaultAgent(testHost()); awaitHostStatus(client, testHost(), UP, LONG_WAIT_MINUTES, MINUTES); final JobId jobId = createJob(testJobName, testJobVersion, BUSYBOX, IDLE_COMMAND, DateTime.now().plusSeconds(10).toDate()); deployJob(jobId, testHost()); TaskStatus taskStatus = awaitJobState( client, testHost(), jobId, RUNNING, WAIT_TIMEOUT_SECONDS, SECONDS); Polling.await(3, MINUTES, new Callable<JobId>() { @Override public JobId call() throws Exception { if (client.jobs().get().containsKey(jobId)) { return null; } else { return jobId; } } }); final ContainerExit exit = docker.waitContainer(taskStatus.getContainerId()); assertThat(exit.statusCode(), is(-1)); }