auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateServiceCatalogEntries(LinkedHashMap endpointConfig) { Map<String, Boolean> productionEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_PRODUCTION_ENDPOINTS); Map<String, Boolean> sandboxEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_SANDBOX_ENDPOINTS); Map<String, Boolean> productionFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_PRODUCTION_FAILOVERS); Map<String, Boolean> sandboxFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_SANDBOX_FAILOVERS); if (!productionEndpointStatus.get("hasEndpoints") && !sandboxEndpointStatus.get("hasEndpoints")) { RestApiUtil.handleBadRequest("At least one endpoint from Production Endpoint or " + "Sandbox Endpoint must be defined.", log); } <START> if (!(productionEndpointStatus.get("validCatalogEndpoints") && <END> sandboxEndpointStatus.get("validCatalogEndpoints") && productionFailoverStatus.get("validCatalogEndpoints") && sandboxFailoverStatus.get("validCatalogEndpoints"))) { RestApiUtil.handleBadRequest("'id' is missing in Service Catalog type endpoints", log); } }</code><technical_language>"validCatalogEndpoints" is repetitively, add a constant field</technical_language>

Target:
private void validateServiceCatalogEntries(LinkedHashMap endpointConfig) { Map<String, Boolean> productionEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_PRODUCTION_ENDPOINTS); Map<String, Boolean> sandboxEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_SANDBOX_ENDPOINTS); Map<String, Boolean> productionFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_PRODUCTION_FAILOVERS); Map<String, Boolean> sandboxFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_SANDBOX_FAILOVERS); if (!productionEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_HAS_ENDPOINTS) && !sandboxEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_HAS_ENDPOINTS)) { RestApiUtil.handleBadRequest("At least one endpoint from Production Endpoint or " + "Sandbox Endpoint must be defined.", log); } if (!(productionEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && sandboxEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && productionFailoverStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && sandboxFailoverStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS))) { RestApiUtil.handleBadRequest("'id' is missing in Service Catalog type endpoints", log); } }
Source:
<code>public Set<Capability> getCapabilities(FileSystem fs, Path path) throws AccessControlException { if (logger.isDebugEnabled()) logger.debug("path:" + path.toUri().getPath()); DataFileStream<Object> avroDataStream = null; try { avroDataStream = getAvroDataStream(fs, path); Schema schema = avroDataStream.getSchema(); return (schema != null) ? EnumSet.of(Capability.READ, Capability.SCHEMA) : EnumSet.noneOf(Capability.class); } catch (AccessControlException e) { throw e; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug(path.toUri().getPath() + " is not an avro file."); logger.debug("Error in getting avro schema: " <START> + e.getLocalizedMessage()); <END> } return EnumSet.noneOf(Capability.class); } finally { try { if (avroDataStream != null) { avroDataStream.close(); } } catch (IOException e) { logger.error(e); } } }</code><technical_language>add exception log statement easier debug problem</technical_language>

Target:
public Set<Capability> getCapabilities(FileSystem fs, Path path) throws AccessControlException { if (logger.isDebugEnabled()) { logger.debug("path:" + path.toUri().getPath()); } DataFileStream<Object> avroDataStream = null; try { avroDataStream = getAvroDataStream(fs, path); Schema schema = avroDataStream.getSchema(); return (schema != null) ? EnumSet.of(Capability.READ, Capability.SCHEMA) : EnumSet.noneOf(Capability.class); } catch (AccessControlException e) { throw e; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug(path.toUri().getPath() + " is not an avro file."); logger.debug("Error in getting avro schema: ", e); } return EnumSet.noneOf(Capability.class); } finally { try { if (avroDataStream != null) { avroDataStream.close(); } } catch (IOException e) { logger.error(e); } } }
Source:
<code>private static void ensurePositive(float value, String name) { if (value <= 0) { <START> throw new IllegalArgumentException(format("Value of '%s' must be positive.", name)); <END> } }</code><technical_language>This _is_ a DeveloperError :D</technical_language>

Target:
private static void ensurePositive(float value, String name) { if (value <= 0) { throw new DeveloperError("Value of '%s' must be positive.", name); } }
Source:
<code>public void setMTUOverrideSupported(boolean mtuOverrideSupported) { if (!mtuOverrideSupported) { getHasMtu().setChangeProhibitionReason(ConstantsManager.getInstance().getMessages() .mtuOverrideNotSupported(getSelectedDc().getcompatibility_version().toString())); getHasMtu().setIsChangable(false); getHasMtu().setEntity(false); } else { if (this.mtuOverrideSupported != mtuOverrideSupported) { initMtu(); } <START> getHasMtu().setIsChangable(true); <END> } this.mtuOverrideSupported = mtuOverrideSupported; }</code><technical_language>I suspect a bug here. this is triggered model is constructed, in EditNetwork case override non-changeability of external network</technical_language>

Target:
public void setMTUOverrideSupported(boolean mtuOverrideSupported) { this.mtuOverrideSupported = mtuOverrideSupported; updateMtuSelectorsVisibility(); }
Source:
<code>void addPredecessor(PhpCfgBlock predecessor) { <START> this.predecessors.add(predecessor); <END> }</code><technical_language>consistent this usages (use never)</technical_language>

Target:
void addPredecessor(PhpCfgBlock predecessor) { predecessors.add(predecessor); }
Source:
<code>private <T, O extends AbstractOptions<O>> Call getFindCoordinatorCall(ConsumerGroupOperationContext<T, O> context, <START> Supplier<Call> nextCall) { <END> return new Call("findCoordinator", context.deadline(), new LeastLoadedNodeProvider()) { @Override FindCoordinatorRequest.Builder createRequest(int timeoutMs) { return new FindCoordinatorRequest.Builder( new FindCoordinatorRequestData() .setKeyType(CoordinatorType.GROUP.id()) .setKey(context.groupId())); } @Override void handleResponse(AbstractResponse abstractResponse) { final FindCoordinatorResponse response = (FindCoordinatorResponse) abstractResponse; if (handleGroupRequestError(response.error(), context.future())) return; context.node(response.node()); runnable.call(nextCall.get(), time.milliseconds()); } @Override void handleFailure(Throwable throwable) { context.future().completeExceptionally(throwable); } }; }</code><technical_language>nit: fix indentation</technical_language>

Target:
private <T, O extends AbstractOptions<O>> Call getFindCoordinatorCall(ConsumerGroupOperationContext<T, O> context, Supplier<Call> nextCall) { return new Call("findCoordinator", context.deadline(), new LeastLoadedNodeProvider()) { @Override FindCoordinatorRequest.Builder createRequest(int timeoutMs) { return new FindCoordinatorRequest.Builder( new FindCoordinatorRequestData() .setKeyType(CoordinatorType.GROUP.id()) .setKey(context.groupId())); } @Override void handleResponse(AbstractResponse abstractResponse) { final FindCoordinatorResponse response = (FindCoordinatorResponse) abstractResponse; if (handleGroupRequestError(response.error(), context.future())) return; context.setNode(response.node()); runnable.call(nextCall.get(), time.milliseconds()); } @Override void handleFailure(Throwable throwable) { context.future().completeExceptionally(throwable); } }; }
Source:
<code>public Status scan(final String table, final String startkey, final int recordcount, final Set<String> fields, final Vector<HashMap<String, ByteIterator>> result) { try { if (!COLUMN_FAMILIES.containsKey(table)) { createColumnFamily(table); } final ColumnFamilyHandle cf = COLUMN_FAMILIES.get(table).getHandle(); try(final RocksIterator iterator = rocksDb.newIterator(cf)) { int iterations = 0; for (iterator.seek(startkey.getBytes(UTF_8)); iterator.isValid() && iterations < recordcount; iterator.next()) { final HashMap<String, ByteIterator> values = new HashMap<>(); deserializeValues(iterator.value(), fields, values); result.add(values); iterations++; } } return Status.OK; <START> } catch(final RocksDBException e) { <END> e.printStackTrace(); return Status.ERROR; } }</code><technical_language>final Map<String, ByteIterator></technical_language>

Target:
public Status scan(final String table, final String startkey, final int recordcount, final Set<String> fields, final Vector<HashMap<String, ByteIterator>> result) { try { if (!COLUMN_FAMILIES.containsKey(table)) { createColumnFamily(table); } final ColumnFamilyHandle cf = COLUMN_FAMILIES.get(table).getHandle(); try(final RocksIterator iterator = rocksDb.newIterator(cf)) { int iterations = 0; for (iterator.seek(startkey.getBytes(UTF_8)); iterator.isValid() && iterations < recordcount; iterator.next()) { final HashMap<String, ByteIterator> values = new HashMap<>(); deserializeValues(iterator.value(), fields, values); result.add(values); iterations++; } } return Status.OK; } catch(final RocksDBException e) { LOGGER.error(e.getMessage(), e); return Status.ERROR; } }
Source:
<code>public void testSourceTopicsWithGlobalTopics() { builder.setApplicationId("X"); builder.addSource(null, "source-1", null, null, null, "topic-1"); builder.addSource(null, "source-2", null, null, null, "topic-2"); <START> builder.addGlobalStore(new MockKeyValueStoreBuilder("global-store", false).withLoggingDisabled(), "globalSource", null, null, null, "globalTopic", "global-processor", new MockProcessorSupplier()); <END> final Pattern expectedPattern = Pattern.compile("topic-1|topic-2"); assertEquals(expectedPattern.pattern(), builder.sourceTopicPattern().pattern()); }</code><technical_language>nit: line long builder.addGlobalStore( new MockKeyValueStoreBuilder("global-store", false).withLoggingDisabled(), "globalSource", null, null, null, "globalTopic", "global-processor", new MockProcessorSupplier());</technical_language>

Target:
public void testSourceTopicsWithGlobalTopics() { builder.setApplicationId("X"); builder.addSource(null, "source-1", null, null, null, "topic-1"); builder.addSource(null, "source-2", null, null, null, "topic-2"); builder.addGlobalStore( new MockKeyValueStoreBuilder("global-store", false).withLoggingDisabled(), "globalSource", null, null, null, "globalTopic", "global-processor", new MockProcessorSupplier()); final Pattern expectedPattern = Pattern.compile("topic-1|topic-2"); assertThat(builder.sourceTopicPattern().pattern(), equalTo(expectedPattern.pattern())); }
Source:
<code>private void parse() throws IOException { <START> stream.mark(0); <END> try { final byte[] formatIdentifier = new byte[BPM_IDENTIFIER.length()]; for (int i = 0; i < formatIdentifier.length; i++) { formatIdentifier[i] = parseByte(); } final String identifier = new String(formatIdentifier); setIdentifier(identifier); if (!identifier.equals(BPM_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for BPM file"); } setFileVersion(parseByte()); if (getFileVersion() != 1) { throw new PicardException("Unknown BPM version (" + getFileVersion() + ")"); } int version = parseInt(); final int versionFlag = 0x1000; if ((version & versionFlag) == versionFlag) { version ^= versionFlag; } if (version > 5 || version < 3) { throw new PicardException("Unsupported BPM version (" + version + ")"); } manifestName = parseString(); if (version > 1) { controlConfig = parseString(); } numLoci = parseInt(); readData(); } finally { stream.close(); } }</code><technical_language>Is this necessary</technical_language>

Target:
private void parse() throws IOException { try { final byte[] formatIdentifier = new byte[BPM_IDENTIFIER.length()]; for (int i = 0; i < formatIdentifier.length; i++) { formatIdentifier[i] = parseByte(); } final String identifier = new String(formatIdentifier); setIdentifier(identifier); if (!identifier.equals(BPM_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for BPM file"); } setFileVersion(parseByte()); if (getFileVersion() != 1) { throw new PicardException("Unknown BPM version (" + getFileVersion() + ")"); } int version = parseInt(); final int versionFlag = 0x1000; if ((version & versionFlag) == versionFlag) { version ^= versionFlag; } if (version > 5 || version < 3) { throw new PicardException("Unsupported BPM version (" + version + ")"); } manifestName = parseString(); controlConfig = parseString(); numLoci = parseInt(); readData(); } finally { stream.close(); } }
Source:
<code>private void validateBindArguments(boolean hasPoolQuantities, String poolIdString, Integer quantity, String[] productIds, List<String> fromPools, Date entitleDate, Consumer consumer, boolean async) { short parameters = 0; <START> if (consumer.getType().isType(ConsumerTypeEnum.SHARE) && StringUtils.isBlank(poolIdString)) { <END> throw new BadRequestException(i18n.tr("Share consumers must be bound to a specific pool")); } if (hasPoolQuantities) { parameters++; } if (poolIdString != null) { parameters++; } if (ArrayUtils.isNotEmpty(productIds) || CollectionUtils.isNotEmpty(fromPools) || entitleDate != null) { parameters++; } if (parameters > 1) { throw new BadRequestException(i18n.tr("Cannot bind by multiple parameters.")); } if (hasPoolQuantities) { if (quantity != null) { throw new BadRequestException( i18n.tr("Cannot specify a single quantity when binding a batch of " + " exact pools. Please specify a quantity for each pool")); } else if (!async) { throw new BadRequestException(i18n.tr("Batch bind can only be performed asynchronously")); } } if (poolIdString == null && quantity != null) { throw new BadRequestException(i18n.tr("Cannot specify a quantity when auto-binding.")); } }</code><technical_language>this force share consumers bind pool a time. I shares excellent candidates for batch bind. allow hasPoolQuantities well</technical_language>

Target:
private void validateBindArguments(boolean hasPoolQuantities, String poolIdString, Integer quantity, String[] productIds, List<String> fromPools, Date entitleDate, Consumer consumer, boolean async) { short parameters = 0; if (consumer.isShare() && StringUtils.isBlank(poolIdString) && !hasPoolQuantities) { throw new BadRequestException(i18n.tr("Share consumers must be bound to a specific pool")); } if (hasPoolQuantities) { parameters++; } if (poolIdString != null) { parameters++; } if (ArrayUtils.isNotEmpty(productIds) || CollectionUtils.isNotEmpty(fromPools) || entitleDate != null) { parameters++; } if (parameters > 1) { throw new BadRequestException(i18n.tr("Cannot bind by multiple parameters.")); } if (hasPoolQuantities) { if (quantity != null) { throw new BadRequestException( i18n.tr("Cannot specify a single quantity when binding a batch of " + " exact pools. Please specify a quantity for each pool")); } else if (!async) { throw new BadRequestException(i18n.tr("Batch bind can only be performed asynchronously")); } } if (poolIdString == null && quantity != null) { throw new BadRequestException(i18n.tr("Cannot specify a quantity when auto-binding.")); } }
Source:
<code>public Object evaluate(Object feature) { String arg0; JSONObject arg1; try { arg0 = getExpression(0).evaluate(feature, String.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function mbHas argument #1 - expected type String"); } try { arg1 = getExpression(1).evaluate(feature, JSONObject.class); } catch (Exception e) { throw new IllegalArgumentException( <START> "Filter Function problem for function mbHas argument #0 - expected type JSONObject"); <END> } return arg1.containsKey(arg0); }</code><technical_language>mbHas in exceptions..</technical_language>

Target:
public Object evaluate(Object feature) { String arg0; JSONObject arg1; try { arg0 = getExpression(0).evaluate(feature, String.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function \"has\" argument #1 - expected type String"); } try { arg1 = getExpression(1).evaluate(feature, JSONObject.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function \"has\" argument #0 - expected type JSONObject"); } return arg1.containsKey(arg0); }
Source:
<code>public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; <START> relativeDateInChangeTable = true; <END> }</code><technical_language>I if this false. default false for existing users, defaulting true for new users. default consistent for users</technical_language>

Target:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; relativeDateInChangeTable = false; }
Source:
<code>public void testGroupImageMessageRequest() { try { Id groupId = new Id(12); Group g = new Group("", groupId, new ArrayList<Id>(), YieldsApplication.getDefaultGroupImage()); Id senderId = new Id(11); String text = "Apple pie is best pie !"; Bitmap newImage = YieldsApplication.getDefaultGroupImage(); ImageContent imageContent = new ImageContent(newImage, text); <START> String imageEncoded = ImageSerialization.serializeImage(newImage, 800); <END> ServerRequest serverRequest = RequestBuilder.nodeMessageRequest(senderId, groupId, Group.GroupVisibility.PRIVATE, imageContent, new Date()); JSONObject json = new JSONObject(serverRequest.message()); assertEquals(json.getString(RequestBuilder.Fields.KIND.getValue()), ServiceRequest.RequestKind.GROUP_MESSAGE.getValue()); assertEquals(json.getJSONObject("metadata").getString("client"), senderId .getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.NID.getValue()), groupId.getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT_TYPE.getValue()), imageContent.getType().toString().toLowerCase()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.TEXT.getValue()), text); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT.getValue()), imageEncoded); } catch (JSONException e) { fail("Request was not built correctly !"); } }</code><technical_language>factor out images sizes a new xml</technical_language>

Target:
public void testGroupImageMessageRequest() { try { Id groupId = new Id(12); Group g = new Group("", groupId, new ArrayList<Id>(), YieldsApplication.getDefaultGroupImage()); Id senderId = new Id(11); String text = "Apple pie is best pie !"; Bitmap newImage = YieldsApplication.getDefaultGroupImage(); ImageContent imageContent = new ImageContent(newImage, text); String imageEncoded = ImageSerialization.serializeImage(newImage, ImageSerialization.SIZE_IMAGE); ServerRequest serverRequest = RequestBuilder.nodeMessageRequest(senderId, groupId, Group.GroupVisibility.PRIVATE, imageContent, new Date()); JSONObject json = new JSONObject(serverRequest.message()); assertEquals(json.getString(RequestBuilder.Fields.KIND.getValue()), ServiceRequest.RequestKind.GROUP_MESSAGE.getValue()); assertEquals(json.getJSONObject("metadata").getString("client"), senderId .getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.NID.getValue()), groupId.getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT_TYPE.getValue()), imageContent.getType().toString().toLowerCase()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.TEXT.getValue()), text); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT.getValue()), imageEncoded); } catch (JSONException e) { fail("Request was not built correctly !"); } }
Source:
<code>boolean wouldPushProject(Project.NameKey project) { <START> if (projectMatch != null) { <END> if (isRE(projectMatch)) { return (new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get()); } else if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); } else { return project.get().equals(projectMatch); } } return true; }</code><technical_language>a bit nicer avoid extra indenting elses returning branch</technical_language>

Target:
boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { if ((new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }
Source:
<code>public void testCount() { SWTBotNatTable nattable = bot.nattable(); <START> assertEquals("Twenty four rows are visible", 24, nattable.rowCount()); <END> assertEquals("Two columns are visible", 2, nattable.columnCount()); assertEquals("Total thirty two rows are created", 32, nattable.preferredRowCount()); assertEquals("Total two columns are created", 2, nattable.preferredColumnCount()); }</code><technical_language>This fails for me, I get 25 visible rows. I rows columns visible, set a fixed size for Shell. cells fit depends OS graphical toolkit (probably due system font sizes). careful cell interact is visible bounds. For example in this file row 14, rows visible 14..</technical_language>

Target:
public void testCount() { SWTBotNatTable nattable = bot.nattable(); int rowCount = nattable.rowCount(); int totalRowCount = nattable.preferredRowCount(); assertThat(rowCount, allOf(lessThan(totalRowCount), greaterThanOrEqualTo(14))); assertEquals("Two columns are visible", 2, nattable.columnCount()); assertEquals("Total thirty two rows are created", 32, totalRowCount); assertEquals("Total two columns are created", 2, nattable.preferredColumnCount()); }
Source:
<code>private void addMessageToMap(String classPackageName, IdentifierTree classNameTree) { AnalyzerMessageReporter reporter = (AnalyzerMessageReporter) context; <START> AnalyzerMessage analyzerMessage = reporter.createAnalyzerMessage(this, classNameTree, String.format(MESSAGE_FORMAT, classNameTree)); <END> messagesPerClassPrefix.computeIfAbsent(classPackageName, k -> new ArrayList<>()).add(analyzerMessage); }</code><technical_language>message formatting relying classnameTree.name toString of tree</technical_language>

Target:
private void addMessageToMap(String classPackageName, IdentifierTree classNameTree) { DefaultJavaFileScannerContext defaultContext = (DefaultJavaFileScannerContext) context; AnalyzerMessage analyzerMessage = defaultContext.createAnalyzerMessage(this, classNameTree, String.format(MESSAGE_FORMAT, classNameTree.name())); messagesPerPackage.computeIfAbsent(classPackageName, k -> new ArrayList<>()).add(analyzerMessage); }
Source:
<code>public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" <START> + this.dataLen + ", cause=" + this.cause + ", clientAddress=" <END> + getSession().getClientAddress() + "]"; }</code><technical_language>I conditional null. explicit StringBuilder instead</technical_language>

Target:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" + this.dataLen + (this.cause == null ? "" : ", cause=" + this.cause) + ", clientAddress=" + getSession().getClientAddress() + "]"; }
Source:
<code>protected void ExecuteVmCommand() { this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); List<VmNetworkInterface> interfaces = DbFacade.getInstance().getVmNetworkInterfaceDAO() .getAllForVm(getParameters().getVmId()); VmNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface i) { return i.getId().equals(getParameters().getInterfaceId()); } }); if (iface != null) { MacPoolManager.getInstance().freeMac(iface.getMacAddress()); _interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getInterfaceTranslation().toString(); if (interType != null) { AddCustomValue("InterfaceType", interType); } } DbFacade.getInstance().getVmNetworkInterfaceDAO().remove(getParameters().getInterfaceId()); DbFacade.getInstance().getVmNetworkStatisticsDAO().remove(getParameters().getInterfaceId()); DbFacade.getInstance() .getVmDeviceDAO() <START> .remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); <END> setSucceeded(true); }</code><technical_language>reuse DbFacade.getInstance()</technical_language>

Target:
protected void ExecuteVmCommand() { this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); List<VmNetworkInterface> interfaces = DbFacade.getInstance().getVmNetworkInterfaceDAO() .getAllForVm(getParameters().getVmId()); VmNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface i) { return i.getId().equals(getParameters().getInterfaceId()); } }); if (iface != null) { MacPoolManager.getInstance().freeMac(iface.getMacAddress()); _interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getInterfaceTranslation().toString(); if (interType != null) { AddCustomValue("InterfaceType", interType); } } DbFacade dbFacade = DbFacade.getInstance(); dbFacade.getVmNetworkInterfaceDAO().remove(getParameters().getInterfaceId()); dbFacade.getVmNetworkStatisticsDAO().remove(getParameters().getInterfaceId()); dbFacade.getVmDeviceDAO() .remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); setSucceeded(true); }
Source:
<code>public Collection<DefaultIssue> create(Component component) { try (DbSession session = dbClient.openSession(false)) { return shortBranchComponentsWithIssues.getUuids(component.getKey()) .stream() <START> .flatMap(uuid -> dbClient.issueDao().selectResolvedOrConfirmedByComponentUuid(session, uuid).stream()) <END> .map(IssueDto::toDefaultIssue) .collect(Collectors.toList()); } }</code><technical_language>a good idea pass uuids dao once</technical_language>

Target:
public Collection<DefaultIssue> create(Component component) { Set<String> uuids = shortBranchComponentsWithIssues.getUuids(component.getKey()); if (uuids.isEmpty()) { return Collections.emptyList(); } try (DbSession session = dbClient.openSession(false)) { return uuids .stream() .flatMap(uuid -> dbClient.issueDao().selectResolvedOrConfirmedByComponentUuid(session, uuid).stream()) .map(IssueDto::toDefaultIssue) .collect(Collectors.toList()); } }
Source:
<code>public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); <START> <END> this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }</code><technical_language>move this line 349. need if died immediately starting</technical_language>

Target:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }
Source:
<code>public static ByteBuffer deepCloneBuffer(ByteBuffer buffer) { <START> int offset = buffer.position(); <END> int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }</code><technical_language>nit; offset is used</technical_language>

Target:
private static ByteBuffer deepCloneBuffer(ByteBuffer buffer) { int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }
Source:
<code>public JSONWithPadding getUserCredentials(@QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { <START> logger.info( "UserResource.setUserPassword" ); <END> final ApiResponse response = createApiResponse(); response.setAction( "get user password" ); final UUID applicationId = getApplicationId(); final UUID targetUserId = getUserUuid(); if ( applicationId == null ) { response.setError( "Application not found" ); return new JSONWithPadding( response, callback ); } if ( targetUserId == null ) { response.setError( "User not found" ); return new JSONWithPadding( response, callback ); } final CredentialsInfo credentialsInfo = management.getAppUserCredentialsInfo( applicationId, targetUserId ); response.setProperty( "credentials", credentialsInfo ); return new JSONWithPadding( response, callback ); }</code><technical_language>this is GET path. update logging statement</technical_language>

Target:
public JSONWithPadding getUserCredentials(@QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { logger.info( "UserResource.getUserCredentials" ); final ApiResponse response = createApiResponse(); response.setAction( "get user credentials" ); final UUID applicationId = getApplicationId(); final UUID targetUserId = getUserUuid(); if ( applicationId == null ) { response.setError( "Application not found" ); return new JSONWithPadding( response, callback ); } if ( targetUserId == null ) { response.setError( "User not found" ); return new JSONWithPadding( response, callback ); } final CredentialsInfo credentialsInfo = management.getAppUserCredentialsInfo( applicationId, targetUserId ); response.setProperty( "credentials", credentialsInfo ); return new JSONWithPadding( response, callback ); }
Source:
<code>public void stop(long timeout, TimeUnit timeUnit) throws InterruptedException { executor.shutdownNow(); <START> kafkaConsumer.wakeup(); <END> running = false; executor.awaitTermination(timeout, timeUnit); }</code><technical_language>try wakeup consumer try interrupt thread? I imagine tend deal stopping more elegantly (in terms of kafka client side, code). In fact, I do shutdownNow altogether. Edit: well, okay, shutdownNow is necessary in case waiting for topics</technical_language>

Target:
public void stop(long timeout, TimeUnit timeUnit) throws InterruptedException { kafkaConsumer.wakeup(); executor.shutdownNow(); running = false; if (!executor.awaitTermination(timeout, timeUnit)) { log.error("Failed to stop KafkaController in {}", timeout, timeUnit); } }
Source:
<code>public synchronized boolean acceptMastership() { if (m_onMastership == null) { exportLog.info("Mastership Runnable not yet set for table " + getTableName() + " partition " + getPartitionId()); return false; } if (m_mastershipAccepted.get()) { exportLog.info("Export table " + getTableName() + " mastership already accepted for partition " + getPartitionId()); return true; } exportLog.info("Accepting mastership for export table " + getTableName() + " partition " + getPartitionId()); m_es.execute(new Runnable() { @Override public void run() { try { if (!m_es.isShutdown() || !m_closed) { exportLog.info("Export table " + getTableName() + " accepting mastership for partition " + getPartitionId()); if (m_onMastership != null) { if (m_mastershipAccepted.compareAndSet(false, true)) { m_onMastership.run(); } } } } catch (Exception e) { exportLog.error("Error in accepting mastership", e); } } <START> }); <END> return m_mastershipAccepted.get(); }</code><technical_language>caller expects return of acceptMastership()</technical_language>

Target:
public synchronized void acceptMastership() { if (m_onMastership == null) { exportLog.info("Mastership Runnable not yet set for table " + getTableName() + " partition " + getPartitionId()); return; } if (m_mastershipAccepted.get()) { exportLog.info("Export table " + getTableName() + " mastership already accepted for partition " + getPartitionId()); return; } exportLog.info("Accepting mastership for export table " + getTableName() + " partition " + getPartitionId()); m_es.execute(new Runnable() { @Override public void run() { try { if (!m_es.isShutdown() || !m_closed) { exportLog.info("Export table " + getTableName() + " accepting mastership for partition " + getPartitionId()); if (m_onMastership != null) { if (m_mastershipAccepted.compareAndSet(false, true)) { m_onMastership.run(); } } } } catch (Exception e) { exportLog.error("Error in accepting mastership", e); } } }); }
Source:
<code>private CompositeJobParametersValidator compositeJobParametersValidator(JobParameters jobParameters) { List<JobParametersValidator> jobParametersValidators = new ArrayList<>(); jobParametersValidators.add(new VariantLoaderStepParametersValidator()); <START> jobParametersValidators.add(new LoadFileStepParametersValidator()); <END> Boolean skipAnnotation = Boolean.valueOf(jobParameters.getString(JobParametersNames.ANNOTATION_SKIP)); if (!skipAnnotation) { jobParametersValidators.add(new VepInputGeneratorStepParametersValidator()); jobParametersValidators.add(new VepAnnotationGeneratorStepParametersValidator()); jobParametersValidators.add(new AnnotationLoaderStepParametersValidator()); } CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }</code><technical_language>in context, this validator class step renamed FileLoaderStepXXX for consistency</technical_language>

Target:
private CompositeJobParametersValidator compositeJobParametersValidator(JobParameters jobParameters) { List<JobParametersValidator> jobParametersValidators = new ArrayList<>(); jobParametersValidators.add(new VariantLoaderStepParametersValidator()); jobParametersValidators.add(new FileLoaderStepParametersValidator()); Boolean skipAnnotation = Boolean.valueOf(jobParameters.getString(JobParametersNames.ANNOTATION_SKIP)); if (!skipAnnotation) { jobParametersValidators.add(new VepInputGeneratorStepParametersValidator()); jobParametersValidators.add(new VepAnnotationGeneratorStepParametersValidator()); jobParametersValidators.add(new AnnotationLoaderStepParametersValidator()); } CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }
Source:
<code>private void startBrowser() { if (web != null) { String url = web.getURL(); if (urlText != null) { urlText.setText(url); } long now = System.nanoTime(); if (lastOpen == 0 || lastOpen + TimeUnit.MILLISECONDS.toNanos(100) < now) { <START> lastOpen = now; <END> openBrowser(url); } } }</code><technical_language>rename lastOpen lastOpenNs</technical_language>

Target:
private void startBrowser() { if (web != null) { String url = web.getURL(); if (urlText != null) { urlText.setText(url); } long now = System.nanoTime(); if (lastOpenNs == 0 || lastOpenNs + TimeUnit.MILLISECONDS.toNanos(100) < now) { lastOpenNs = now; openBrowser(url); } } }
Source:
<code>private Map<String, Serializable> addTaskVariablesAndBackupInheritedVariables(Map<String, Serializable> variables, ImmutableMap<String, TaskVariable> taskVariables) { <START> Map<String, Serializable> taskAndBackupVariables = new HashMap<>(); <END> for (TaskVariable taskVariable : taskVariables.values()) { if (!taskVariable.isJobInherited() || (taskVariable.isJobInherited() && variables.get(taskVariable.getName()) == null)) { if (variables.get(taskVariable.getName()) != null) { taskAndBackupVariables.put(SchedulerVars.PA_PROPAGATED_VARIABLE_PREFIX.toString() + taskVariable.getName(), variables.get(taskVariable.getName())); } else { taskAndBackupVariables.put(SchedulerVars.PA_TASK_VARIABLE_PREFIX.toString() + taskVariable.getName(), variables.get(taskVariable.getName())); } taskAndBackupVariables.put(taskVariable.getName(), taskVariable.getValue()); } } return taskAndBackupVariables; }</code><technical_language>variables is a Map, taskVariables is ImmutableMap</technical_language>

Target:
private void addTaskVariablesAndBackupInheritedVariables(Map<String, Serializable> variables, ImmutableMap<String, TaskVariable> taskVariables) { Map<String, Serializable> taskAndBackupVariables = new HashMap<>(); for (TaskVariable taskVariable : taskVariables.values()) { String taskName = taskVariable.getName(); if (!taskVariable.isJobInherited() || (taskVariable.isJobInherited() && variables.get(taskName) == null)) { if (variables.get(taskName) != null) { taskAndBackupVariables.put(SchedulerVars.PA_FLAG_PROPAGATED_VAR_TO_RESTORE.toString() + taskName, variables.get(taskName)); } else { taskAndBackupVariables.put(SchedulerVars.PA_FLAG_TASK_VAR_TO_CLEAR.toString() + taskName, taskVariable.getValue()); } taskAndBackupVariables.put(taskName, taskVariable.getValue()); } } variables.putAll(taskAndBackupVariables); }
Source:
<code>public HealthCheckResult getOrRunHealthChecks() { <START> int refreshSeconds = Integer.parseInt(Framework.getProperty(DEFAULT_HEALTH_CHECK_INTERVAL_SECONDS_PROPERTY, <END> DEFAULT_HEALTH_CHECK_INTERVAL_SECONDS)); for (Entry<String, ProbeInfo> es : probesForHealthCheck.entrySet()) { String probeName = es.getKey(); ProbeInfo probe = es.getValue(); if (probe == null) { log.warn("Probe:" + probeName + " does not exist, skipping it for the health check"); continue; } getStatusOrRunProbe(probe, refreshSeconds); } return new HealthCheckResult(probesForHealthCheck.values()); }</code><technical_language>initialized start of component extracted a method is (see getOrRunHealthChecek(String name)</technical_language>

Target:
public HealthCheckResult getOrRunHealthChecks() { for (Entry<String, ProbeInfo> es : probesForHealthCheck.entrySet()) { String probeName = es.getKey(); ProbeInfo probe = es.getValue(); if (probe == null) { log.warn("Probe:" + probeName + " does not exist, skipping it for the health check"); continue; } getStatusOrRunProbe(probe, getDefaultCheckInterval()); } return new HealthCheckResult(probesForHealthCheck.values()); }
Source:
<code>void closeExpiredConnections() { List<CachedConnection> expiredConnections; <START> synchronized (this) { <END> ConnectionPool pool = getConnectionPool(); expiredConnections = pool.removeExpiredConnections(killTime); synchronized (errorCount) { Iterator<Entry<ThriftTransportKey,Long>> iter = errorTime.entrySet().iterator(); while (iter.hasNext()) { Entry<ThriftTransportKey,Long> entry = iter.next(); long delta = System.currentTimeMillis() - entry.getValue(); if (delta >= STUCK_THRESHOLD) { errorCount.remove(entry.getKey()); iter.remove(); } } } } expiredConnections.forEach((c) -> c.transport.close()); }</code><technical_language>This is sync performance problems acquires locks sync block sync startCheckerThread() thread calls. threads wait other unnecessarily, able proceed independently if working keys. This is fixed in changes I in lbschanno/accumulo#3</technical_language>

Target:
void closeExpiredConnections() { List<CachedConnection> expiredConnections; ConnectionPool pool = getConnectionPool(); expiredConnections = pool.removeExpiredConnections(killTime); synchronized (errorCount) { Iterator<Entry<ThriftTransportKey,Long>> iter = errorTime.entrySet().iterator(); while (iter.hasNext()) { Entry<ThriftTransportKey,Long> entry = iter.next(); long delta = System.currentTimeMillis() - entry.getValue(); if (delta >= STUCK_THRESHOLD) { errorCount.remove(entry.getKey()); iter.remove(); } } } expiredConnections.forEach((c) -> c.transport.close()); }
Source:
<code>public InterestChannelImpl(final SourcedEurekaRegistry<InstanceInfo> registry, final MessageConnection transport, final ServerInterestChannelMetrics metrics) { super(STATE.Idle, transport, registry, metrics); this.metrics = metrics; this.notificationMultiplexer = new InterestNotificationMultiplexer(registry); this.channelSubscriptionMonitor = new ChannelSubscriptionMonitor(metrics); subscribeToTransportInput(new Action1<Object>() { @Override public void call(Object message) { if (message instanceof SnapshotRegistration) { switch (state.get()) { case Idle: moveToState(STATE.Idle, STATE.Open); sendSnapshot(((SnapshotRegistration) message).getInterests()); <START> moveToState(STATE.Idle); <END> break; case Open: sendErrorOnTransport(SNAPSHOT_REQUEST_NOT_ALLOWED); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof InterestRegistration) { Interest<InstanceInfo> interest = ((InterestRegistration) message).toComposite(); switch (state.get()) { case Idle: case Open: change(interest); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof UnregisterInterestSet) { switch (state.get()) { case Idle: case Open: change(Interests.forNone()); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else { sendErrorOnTransport(new EurekaProtocolError("Unexpected message " + message)); } } }); }</code><technical_language>Idle Closed</technical_language>

Target:
public InterestChannelImpl(final SourcedEurekaRegistry<InstanceInfo> registry, final MessageConnection transport, final ServerInterestChannelMetrics metrics) { super(STATE.Idle, transport, registry, metrics); this.metrics = metrics; this.notificationMultiplexer = new InterestNotificationMultiplexer(registry); this.channelSubscriptionMonitor = new ChannelSubscriptionMonitor(metrics); subscribeToTransportInput(new Action1<Object>() { @Override public void call(Object message) { if (message instanceof SnapshotRegistration) { switch (state.get()) { case Idle: moveToState(STATE.Idle, STATE.Open); sendSnapshot(((SnapshotRegistration) message).getInterests()); moveToState(STATE.Closed); break; case Open: sendErrorOnTransport(SNAPSHOT_REQUEST_NOT_ALLOWED); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof InterestRegistration) { Interest<InstanceInfo> interest = ((InterestRegistration) message).toComposite(); switch (state.get()) { case Idle: case Open: change(interest); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof UnregisterInterestSet) { switch (state.get()) { case Idle: case Open: change(Interests.forNone()); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else { sendErrorOnTransport(new EurekaProtocolError("Unexpected message " + message)); } } }); }
Source:
<code>public boolean onNetworkAddition(INetwork network) { <START> return NetworkHelpers.getEnergyNetwork(network).addPosition(PartPos.of(getPos(), null), 0, 0); <END> }</code><technical_language>For consistency, IChanneledNetwork.DEFAULT_CHANNEL well</technical_language>

Target:
public boolean onNetworkAddition(INetwork network) { return NetworkHelpers.getEnergyNetwork(network).addPosition(PartPos.of(getPos(), null), 0, IChanneledNetwork.DEFAULT_CHANNEL); }
Source:
<code>public Integer getUriOpenedSockets(String uri) { Integer numberOpenedSockets = 0; <START> for (WebSocketDispatcher dispatcher : dispatchers) { <END> numberOpenedSockets += dispatcher.getNumberOpenedSocketsByUri(uri); } return numberOpenedSockets; }</code><technical_language>need protected concurrent accesses</technical_language>

Target:
public Integer getUriOpenedSockets(String uri) { Integer numberOpenedSockets = 0; synchronized (this) { for (WebSocketDispatcher dispatcher : dispatchers) { numberOpenedSockets += dispatcher.getNumberOpenedSocketsByUri(uri); } } return numberOpenedSockets; }
Source:
<code>public void testContainerNotRunningVariation() throws Throwable { final ContainerInfo stopped = new ContainerInfo() { @Override public ContainerState state() { final ContainerState state = mock(ContainerState.class); when(state.running()).thenReturn(false); when(state.error()).thenReturn("container is a potato"); return state; } }; doReturn("potato").when(mockCreation).id(); doReturn(stopped).when(mockDocker).inspectContainer(anyString()); doReturn(mockImageInfo).when(mockDocker).inspectImage(IMAGE); doReturn(mockCreation).when(mockDocker) .createContainer(any(ContainerConfig.class), anyString()); doReturn(false).when(mockHealthChecker).check(anyString()); final TaskRunner tr = TaskRunner.builder() .delayMillis(0) .config(TaskConfig.builder() .namespace("test") .host(HOST) .job(JOB) .containerDecorators(ImmutableList.of(containerDecorator)) .build()) .docker(mockDocker) .listener(mockListener) .healthChecker(mockHealthChecker) .build(); tr.run(); try { tr.resultFuture().get(); <START> fail("this should throw"); <END> } catch (Exception t) { assertTrue(t instanceof ExecutionException); assertEquals(RuntimeException.class, t.getCause().getClass()); verify(mockListener).failed(t.getCause(), "container is a potato"); } }</code><technical_language>ExpectedException rule this a bit nicer in opinion. for more info: <LINK_0></technical_language>

Target:
public void testContainerNotRunningVariation() throws Throwable { final TaskRunner.NopListener mockListener = mock(TaskRunner.NopListener.class); final ImageInfo mockImageInfo = mock(ImageInfo.class); final ContainerCreation mockCreation = mock(ContainerCreation.class); final HealthChecker mockHealthChecker = mock(HealthChecker.class); final ContainerInfo stopped = new ContainerInfo() { @Override public ContainerState state() { final ContainerState state = mock(ContainerState.class); when(state.running()).thenReturn(false); when(state.error()).thenReturn("container is a potato"); return state; } }; when(mockCreation.id()).thenReturn("potato"); when(mockDocker.inspectContainer(anyString())).thenReturn(stopped); when(mockDocker.inspectImage(IMAGE)).thenReturn(mockImageInfo); when(mockDocker.createContainer(any(ContainerConfig.class), anyString())) .thenReturn(mockCreation); when(mockHealthChecker.check(anyString())).thenReturn(false); final TaskRunner tr = TaskRunner.builder() .delayMillis(0) .config(TaskConfig.builder() .namespace("test") .host(HOST) .job(JOB) .containerDecorators(ImmutableList.of(containerDecorator)) .build()) .docker(mockDocker) .listener(mockListener) .healthChecker(mockHealthChecker) .build(); tr.run(); try { tr.resultFuture().get(); fail("this should throw"); } catch (Exception t) { assertTrue(t instanceof ExecutionException); assertEquals(RuntimeException.class, t.getCause().getClass()); verify(mockListener).failed(t.getCause(), "container is a potato"); } }