auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public TableMetadata toTableMetadata() { Preconditions.checkState(!rowNameComponents.isEmpty(), "No row name components defined."); if (explicitCompressionRequested && explicitCompressionBlockSizeKB == 0) { if (rangeScanAllowed) { explicitCompressionBlockSizeKB = AtlasDbConstants.DEFAULT_TABLE_WITH_RANGESCANS_COMPRESSION_BLOCK_SIZE_KB; } else { explicitCompressionBlockSizeKB = AtlasDbConstants.DEFAULT_TABLE_COMPRESSION_BLOCK_SIZE_KB; } } return new TableMetadata( NameMetadataDescription.create(rowNameComponents, hashFirstRowComponent), getColumnMetadataDescription(), conflictHandler, cachePriority, partitionStrategy, rangeScanAllowed, explicitCompressionBlockSizeKB, negativeLookups, sweepStrategy, expirationStrategy, appendHeavyAndReadLight, <START> tableNameSafety.isSafeForLogging()); <END> }</code><technical_language>unwrapping enum avoid breaking previous PR? I released 0.49.0 TableMetadata NameComponentDescription boolean args. so, is args yet</technical_language>

Target:
public TableMetadata toTableMetadata() { Preconditions.checkState(!rowNameComponents.isEmpty(), "No row name components defined."); if (explicitCompressionRequested && explicitCompressionBlockSizeKB == 0) { if (rangeScanAllowed) { explicitCompressionBlockSizeKB = AtlasDbConstants.DEFAULT_TABLE_WITH_RANGESCANS_COMPRESSION_BLOCK_SIZE_KB; } else { explicitCompressionBlockSizeKB = AtlasDbConstants.DEFAULT_TABLE_COMPRESSION_BLOCK_SIZE_KB; } } return new TableMetadata( NameMetadataDescription.create(rowNameComponents, hashFirstRowComponent), getColumnMetadataDescription(), conflictHandler, cachePriority, partitionStrategy, rangeScanAllowed, explicitCompressionBlockSizeKB, negativeLookups, sweepStrategy, expirationStrategy, appendHeavyAndReadLight, tableNameSafety); }
Source:
<code>public void testCopyFileReadException(final Path file) throws IOException { final Path outFile = Files.createTempFile("tmp", ".tmp"); outFile.toFile().deleteOnExit(); file.toFile().setReadable(false); try { IOUtil.copyFile(file.toFile(), outFile.toFile()); } catch (SAMException e) { <START> file.toFile().setReadable(true); <END> throw e; } }</code><technical_language>change readability status here</technical_language>

Target:
public void testCopyFileReadException(final Path file) throws IOException { final Path outFile = Files.createTempFile("tmp", ".tmp"); outFile.toFile().deleteOnExit(); file.toFile().setReadable(false); try { IOUtil.copyFile(file.toFile(), outFile.toFile()); } finally { file.toFile().setReadable(true); } }
Source:
<code>public static void invokeWithRetry(int maxRetries, long wait, Runnable runnable) throws Exception { Throwable last = null; for (int i=0; i<maxRetries; i++) { try { SwingUtilities.invokeAndWait(runnable); return; } catch (Exception | AssertionError e) { last = e; Thread.sleep(wait); } } <START> throw new RuntimeException("Giving up invoke and retry", last); <END> }</code><technical_language>I wrap this in a RuntimeException - matter this is in tests, in general want exception pass caller. stacktrace includes runnable. bothers throwing Error, if want pass exception catch AssertionError specifically wrap in a RuntimeException</technical_language>

Target:
public static void invokeWithRetry(int maxRetries, long wait, Runnable runnable) throws Exception { Exception last = null; for (int i=0; i<maxRetries; i++) { try { SwingUtilities.invokeAndWait(runnable); return; } catch (Exception e) { last = e; Thread.sleep(wait); } catch (AssertionError e) { last = new RuntimeException(e); Thread.sleep(wait); } } throw last; }
Source:
<code>private void parseModuleName() throws IOException { <START> Pattern regexPattern = Pattern.compile("module \"?([\\w\\.@:%_\\+-.~#?&]+/?.+\\w)"); <END> Path modPath = Paths.get(path.toString(), "go.mod"); Stream<String> stream = Files.lines(modPath, StandardCharsets.UTF_8); stream.forEach(line -> { if (regexPattern.matcher(line).matches()) { moduleName = line; } }); moduleName = StringUtils.split(moduleName, " ")[1]; }</code><technical_language>compiling a reg exp is expensive operation. do once. I suggest declare this pattern static final initialise declaration</technical_language>

Target:
private void parseModuleName() throws IOException { Path modPath = Paths.get(path.toString(), LOCAL_GO_MOD_FILENAME); Stream<String> stream = Files.lines(modPath, StandardCharsets.UTF_8); stream.forEach(line -> { if (MODULE_NAME_REGEX_PATTERN.matcher(line).matches()) { moduleName = line; } }); moduleName = StringUtils.split(moduleName, " ")[1]; }
Source:
<code>private void addOutputNodes(RenderGraph renderGraph) { Node outputToVRFrameBufferNode = new OutputToHMDNode(context); renderGraph.addNode(outputToVRFrameBufferNode, "outputToVRFrameBufferNode"); Node outputToScreenNode = new OutputToScreenNode(context); renderGraph.addNode(outputToScreenNode, "outputToScreenNode"); Node finalPostProcessingNode = renderGraph.findNode(new SimpleUri("engine:finalPostProcessingNode")); renderGraph.connect(finalPostProcessingNode, outputToVRFrameBufferNode); <START> renderGraph.connect(outputToVRFrameBufferNode, outputToScreenNode); <END> }</code><technical_language>sketchboard.io graph VR Screen output nodes in parallel, dependent finalPostProcessingNode processed them</technical_language>

Target:
private void addOutputNodes(RenderGraph renderGraph) { Node finalPostProcessingNode = renderGraph.findNode("engine:finalPostProcessingNode"); Node outputToVRFrameBufferNode = new OutputToHMDNode(context); renderGraph.addNode(outputToVRFrameBufferNode, "outputToVRFrameBufferNode"); renderGraph.connect(finalPostProcessingNode, outputToVRFrameBufferNode); Node outputToScreenNode = new OutputToScreenNode(context); renderGraph.addNode(outputToScreenNode, "outputToScreenNode"); renderGraph.connect(finalPostProcessingNode, outputToScreenNode); }
Source:
<code>private static Expression extractJoinPredicate(JoinNode joinNode) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (JoinNode.EquiJoinClause equiJoinClause : joinNode.getCriteria()) { builder.add(JoinNodeUtil.toExpression(equiJoinClause)); } <START> joinNode.getFilter().ifPresent(builder::add); <END> return combineConjuncts(builder.build()); }</code><technical_language>static import</technical_language>

Target:
private static Expression extractJoinPredicate(JoinNode joinNode) { ImmutableList.Builder<Expression> builder = ImmutableList.builder(); for (JoinNode.EquiJoinClause equiJoinClause : joinNode.getCriteria()) { builder.add(JoinNodeUtils.toExpression(equiJoinClause)); } joinNode.getFilter().map(OriginalExpressionUtils::castToExpression).ifPresent(builder::add); return combineConjuncts(builder.build()); }
Source:
<code><START> public void visit(LayerGroupInfo layerGroup) { <END> if (layerGroup.getWorkspace() != null) { layerGroup.setWorkspace( getById(layerGroup.getWorkspace().getId(), WorkspaceInfo.class)); } for (int i = 0; i < layerGroup.getLayers().size(); i++) { if (layerGroup.getLayers().get(i) != null) { layerGroup .getLayers() .set( i, getById( layerGroup.getLayers().get(i).getId(), PublishedInfo.class)); } } }</code><technical_language>Do RootLayer, RootLayerStyle Styles need updated</technical_language>

Target:
public void visit(LayerGroupInfo layerGroup) { if (layerGroup.getWorkspace() != null) { layerGroup.setWorkspace( getById(layerGroup.getWorkspace().getId(), WorkspaceInfo.class)); } for (int i = 0; i < layerGroup.getLayers().size(); i++) { if (layerGroup.getLayers().get(i) != null) { layerGroup .getLayers() .set( i, getById( layerGroup.getLayers().get(i).getId(), PublishedInfo.class)); } } if (layerGroup.getRootLayer() != null) { layerGroup.setRootLayer( getById(layerGroup.getRootLayer().getId(), LayerInfo.class)); } if (layerGroup.getRootLayerStyle() != null) { layerGroup.setRootLayerStyle( getById(layerGroup.getRootLayerStyle().getId(), StyleInfo.class)); } for (int i = 0; i < layerGroup.getStyles().size(); i++) { if (layerGroup.getStyles().get(i) != null) { layerGroup .getStyles() .set( i, getById( layerGroup.getStyles().get(i).getId(), StyleInfo.class)); } } }
Source:
<code>public void startSignIn(@NonNull PhoneAuthCredential credential, @NonNull final IdpResponse response) { if (!response.isSuccessful()) { setResult(Resource.<IdpResponse>forFailure(response.getError())); return; } if (!response.getProviderType().equals(PhoneAuthProvider.PROVIDER_ID)) { throw new IllegalStateException( "This handler cannot be used without a phone response."); } setResult(Resource.<IdpResponse>forLoading()); AnonymousUpgradeUtils.signInAndLinkWithPhoneNumber(getAuth(), getArguments(), credential) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { handleSuccess(response, result); } }) <START> .addOnFailureListener(new OnFailureListener() { <END> @Override public void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthUserCollisionException) { handleMergeFailure(((FirebaseAuthUserCollisionException) e).getUpdatedCredential()); } else { setResult(Resource.<IdpResponse>forFailure(e)); } } }); }</code><technical_language>optional: if PR notice I a type of Task type system force handle merge exceptions call sites. pretty constantly instanceof checks exceptions for operations want consider that</technical_language>

Target:
public void startSignIn(@NonNull PhoneAuthCredential credential, @NonNull final IdpResponse response) { if (!response.isSuccessful()) { setResult(Resource.<IdpResponse>forFailure(response.getError())); return; } if (!response.getProviderType().equals(PhoneAuthProvider.PROVIDER_ID)) { throw new IllegalStateException( "This handler cannot be used without a phone response."); } setResult(Resource.<IdpResponse>forLoading()); AuthOperationManager.getInstance() .signInAndLinkWithCredential(getAuth(), getArguments(), credential) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { handleSuccess(response, result); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthUserCollisionException) { handleMergeFailure(((FirebaseAuthUserCollisionException) e).getUpdatedCredential()); } else { setResult(Resource.<IdpResponse>forFailure(e)); } } }); }
Source:
<code>public void jobUpdate(final JobEntity jobEntity) { final JobStatus currentState = jobEntity.getStatus(); final JobStatus previouslyNotifiedState = jobEntity.getNotifiedJobStatus(); final String jobId = jobEntity.getUniqueId(); if (currentState != previouslyNotifiedState) { log.info( "Detected state change for job: from: to: {}", jobId, previouslyNotifiedState, currentState ); <START> if (this.persistedJobStatusObserver != null) { <END> this.persistedJobStatusObserver.notify(jobId, previouslyNotifiedState, currentState); } jobEntity.setNotifiedJobStatus(currentState); } }</code><technical_language>If observer is null bother anything? change null constructor is modifier short circuit other logic return</technical_language>

Target:
public void jobUpdate(final JobEntity jobEntity) { final JobStatus currentState = jobEntity.getStatus(); final JobStatus previouslyNotifiedState = jobEntity.getNotifiedJobStatus(); final String jobId = jobEntity.getUniqueId(); if (currentState != previouslyNotifiedState) { log.info( "Detected state change for job: from: to: {}", jobId, previouslyNotifiedState, currentState ); this.persistedJobStatusObserver.notify(jobId, previouslyNotifiedState, currentState); jobEntity.setNotifiedJobStatus(currentState); } }
Source:
<code>@Test public void testCopyCorrelVariable() { final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); final RexBuilder builder = new RexBuilder(typeFactory); final RelDataType type = typeFactory.createSqlType(SqlTypeName.INTEGER); final RexCorrelVariable node = (RexCorrelVariable) builder.makeCorrel(type, new CorrelationId(0)); final RexNode copy = builder.copy(node); assertTrue(copy instanceof RexCorrelVariable); final RexCorrelVariable result = (RexCorrelVariable) copy; assertThat(result.id, is(node.id)); <START> assertThat(result.getType(), is(node.getType())); <END> }</code><technical_language>I understand code, main advantage of RexCopier (over RexShuttle) is copy a RexNode copying type factory other. tests good do verify typeFactory is correctly</technical_language>

Target:
@Test public void testCopyCorrelVariable() { final RelDataTypeFactory sourceTypeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); RelDataType type = sourceTypeFactory.createSqlType(SqlTypeName.VARCHAR, 65536); final RelDataTypeFactory targetTypeFactory = new MySqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT); final RexBuilder builder = new RexBuilder(targetTypeFactory); final RexCorrelVariable node = (RexCorrelVariable) builder.makeCorrel(type, new CorrelationId(0)); final RexNode copy = builder.copy(node); assertTrue(copy instanceof RexCorrelVariable); final RexCorrelVariable result = (RexCorrelVariable) copy; assertThat(result.id, is(node.id)); assertThat(result.getType().getSqlTypeName(), is(SqlTypeName.VARCHAR)); assertThat(result.getType().getPrecision(), is(PRECISION)); }
Source:
<code>private String getAbsoluteConfDirPath(String dir, YamlConfig config) { String result = null, response = null; if (dir == null || dir.trim().isEmpty() || !dir.contains("/")) { throw new IllegalArgumentException(error_message); } response = RemotingUtil.executeCommand(config, LS_PREFIX_PART + dir + LS_CDH_POSTFIX_PART); <START> if (response != null && !response.isEmpty() && response.indexOf(">")!=-1) { <END> result = response.substring((response.indexOf(">") + 1), response.length()); result = result.endsWith(File.separator)?result:result.trim()+File.separator; } LOGGER.debug("Found linked Hadoop conf path:"+result); if(result!=null){ String recursiveResponse = getAbsoluteConfDirPath(result, config); if(recursiveResponse!=null){ result = recursiveResponse; } } return result; }</code><technical_language>indexOf(">") in a variable reuse internally</technical_language>

Target:
private String getAbsoluteConfDirPath(String dir, YamlConfig config) { String result = null, response = null; if (dir == null || dir.trim().isEmpty() || !dir.contains("/")) { throw new IllegalArgumentException(error_message); } response = RemotingUtil.executeCommand(config, LS_PREFIX_PART + dir + LS_CDH_POSTFIX_PART); int responseIndex=response.indexOf(">"); if (response != null && !response.isEmpty() && responseIndex!=-1) { result = response.substring((responseIndex + 1), response.length()); result = result.endsWith(File.separator)?result:result.trim()+File.separator; } LOGGER.debug("Found linked Hadoop conf path:"+result); if(result!=null){ String recursiveResponse = getAbsoluteConfDirPath(result, config); if(recursiveResponse!=null){ result = recursiveResponse; } } return result; }
Source:
<code>public static ImmutableWorkerInfo selectWorker( final Task task, final Map<String, ImmutableWorkerInfo> allWorkers, final WorkerTaskRunnerConfig workerTaskRunnerConfig, @Nullable final WorkerCategorySpec workerCategorySpec, final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector ) { final Map<String, ImmutableWorkerInfo> runnableWorkers = getRunnableWorkers( task, allWorkers, workerTaskRunnerConfig ); <START> if (workerCategorySpec != null) { <END> String preferredCategory = getTaskCategory(task, workerCategorySpec, null); if (preferredCategory != null) { final ImmutableMap<String, ImmutableWorkerInfo> categoryWorkers = getCategoryWorkers( preferredCategory, runnableWorkers ); final ImmutableWorkerInfo selected = workerSelector.apply(categoryWorkers); if (selected != null) { return selected; } else if (workerCategorySpec.isStrong()) { return null; } } } return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers)); }</code><technical_language>this check is done in getTaskCategory(..) is redundant</technical_language>

Target:
public static ImmutableWorkerInfo selectWorker( final Task task, final Map<String, ImmutableWorkerInfo> allWorkers, final WorkerTaskRunnerConfig workerTaskRunnerConfig, @Nullable final WorkerCategorySpec workerCategorySpec, final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector ) { final Map<String, ImmutableWorkerInfo> runnableWorkers = getRunnableWorkers( task, allWorkers, workerTaskRunnerConfig ); String preferredCategory = getTaskCategory(task, workerCategorySpec, null); if (preferredCategory != null) { final ImmutableMap<String, ImmutableWorkerInfo> categoryWorkers = getCategoryWorkers( preferredCategory, runnableWorkers ); final ImmutableWorkerInfo selected = workerSelector.apply(categoryWorkers); if (selected != null) { return selected; } else if (workerCategorySpec.isStrong()) { return null; } } return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers)); }
Source:
<code>public LongDictionaryStreamReader(Type type, StreamDescriptor streamDescriptor, LocalMemoryContext systemMemoryContext) throws OrcCorruptionException { requireNonNull(type, "type is null"); <START> verifyStreamType(streamDescriptor, type, t -> t instanceof BigintType || t instanceof IntegerType || t instanceof SmallintType || t instanceof DateType || t instanceof TimeType || t instanceof TimestampType); <END> this.type = type; this.streamDescriptor = requireNonNull(streamDescriptor, "stream is null"); this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); }</code><technical_language>original checking bypassing for Raptor. ok some hacky workaround in presto-raptor presto-orc. chat @jessesleeping solve this issue</technical_language>

Target:
public LongDictionaryStreamReader(Type type, StreamDescriptor streamDescriptor, LocalMemoryContext systemMemoryContext) throws OrcCorruptionException { requireNonNull(type, "type is null"); verifyStreamType(streamDescriptor, type, t -> t instanceof BigintType || t instanceof IntegerType || t instanceof SmallintType || t instanceof DateType); this.type = type; this.streamDescriptor = requireNonNull(streamDescriptor, "stream is null"); this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); }
Source:
<code><START> DialogueAdaptingMultiClientConjureTimelockService getMultiClientConjureTimelockService() { <END> MultiClientConjureTimelockServiceBlocking blockingService = dialogueClientFactory.get(MultiClientConjureTimelockServiceBlocking.class, TIMELOCK_SHORT_TIMEOUT); MultiClientConjureTimelockServiceBlocking instrumentedService = AtlasDbMetrics.instrumentWithTaggedMetrics( taggedMetricRegistry, MultiClientConjureTimelockServiceBlocking.class, FastFailoverProxy.newProxyInstance( MultiClientConjureTimelockServiceBlocking.class, () -> blockingService)); return new DialogueAdaptingMultiClientConjureTimelockService(instrumentedService); }</code><technical_language>This depend concrete type</technical_language>

Target:
MultiClientConjureTimelockServiceBlocking getMultiClientConjureTimelockService() { MultiClientConjureTimelockServiceBlocking blockingService = dialogueClientFactory.get(MultiClientConjureTimelockServiceBlocking.class, TIMELOCK_SHORT_TIMEOUT); return AtlasDbMetrics.instrumentWithTaggedMetrics( taggedMetricRegistry, MultiClientConjureTimelockServiceBlocking.class, FastFailoverProxy.newProxyInstance( MultiClientConjureTimelockServiceBlocking.class, () -> blockingService)); }
Source:
<code>public void registerModule(IAnalysisModule module) { if (module == null) { throw new IllegalArgumentException(); } ITmfTrace selectedTrace = TmfTraceManager.getInstance().getActiveTrace(); if (selectedTrace == null) { fModule = module; return; } <START> @SuppressWarnings("resource") <END> IAnalysisModule selectedModule = selectedTrace.getAnalysisModule(module.getId()); if (selectedModule == module) { fModule = module; } }</code><technical_language>put this, a "real" warning atm, get rid of ;)</technical_language>

Target:
public void registerModule(IAnalysisModule module) { if (module == null) { throw new IllegalArgumentException(); } ITmfTrace selectedTrace = TmfTraceManager.getInstance().getActiveTrace(); if (selectedTrace == null) { fModule = module; return; } IAnalysisModule selectedModule = selectedTrace.getAnalysisModule(module.getId()); if (selectedModule == module) { fModule = module; } }
Source:
<code>public static DatanodeDetails readDatanodeIdFile(File path) throws IOException { Preconditions.checkNotNull(path); DatanodeDetails datanodeDetails; try (FileInputStream inputFileStream = new FileInputStream(path)) { Yaml yaml = new Yaml(); DatanodeDetailsYaml datanodeDetailsYaml; try { datanodeDetailsYaml = yaml.loadAs(inputFileStream, DatanodeDetailsYaml.class); } catch (Exception e) { throw new IOException("Unable to parse yaml file.", e); } <START> <END> DatanodeDetails.Builder builder = DatanodeDetails.newBuilder(); builder.setUuid(datanodeDetailsYaml.getUuid().toString()) .setIpAddress(datanodeDetailsYaml.getIpAddress()) .setHostName(datanodeDetailsYaml.getHostName()) .setCertSerialId(datanodeDetailsYaml.getCertSerialId()); if (!MapUtils.isEmpty(datanodeDetailsYaml.getPortDetails())) { for (Map.Entry<String, Integer> portEntry : datanodeDetailsYaml.getPortDetails().entrySet()) { builder.addPort(DatanodeDetails.newPort( DatanodeDetails.Port.Name.valueOf(portEntry.getKey()), portEntry.getValue())); } } datanodeDetails = builder.build(); } return datanodeDetails; }</code><technical_language>whitespace:end of line</technical_language>

Target:
public static DatanodeDetails readDatanodeIdFile(File path) throws IOException { DatanodeDetails datanodeDetails; try (FileInputStream inputFileStream = new FileInputStream(path)) { Yaml yaml = new Yaml(); DatanodeDetailsYaml datanodeDetailsYaml; try { datanodeDetailsYaml = yaml.loadAs(inputFileStream, DatanodeDetailsYaml.class); } catch (Exception e) { throw new IOException("Unable to parse yaml file.", e); } DatanodeDetails.Builder builder = DatanodeDetails.newBuilder(); builder.setUuid(datanodeDetailsYaml.getUuid()) .setIpAddress(datanodeDetailsYaml.getIpAddress()) .setHostName(datanodeDetailsYaml.getHostName()) .setCertSerialId(datanodeDetailsYaml.getCertSerialId()); if (!MapUtils.isEmpty(datanodeDetailsYaml.getPortDetails())) { for (Map.Entry<String, Integer> portEntry : datanodeDetailsYaml.getPortDetails().entrySet()) { builder.addPort(DatanodeDetails.newPort( DatanodeDetails.Port.Name.valueOf(portEntry.getKey()), portEntry.getValue())); } } datanodeDetails = builder.build(); } return datanodeDetails; }
Source:
<code>public final Response createType(@Context final HttpServletRequest req, final ContentTypeForm form) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); Response response = null; try { Iterable<ContentTypeForm.ContentTypeFormEntry> typesToSave = form.getIterable(); final List<ContentType> retTypes = new ArrayList<>(); for (ContentTypeForm.ContentTypeFormEntry entry : typesToSave) { ContentType type = entry.contentType; List<String> workflowsIds = entry.workflowsIds; if (UtilMethods.isSet(type.id()) && !UUIDUtil.isUUID(type.id())) { <START> return ExceptionMapperUtil.createResponse(null, "ContentType 'id' if set, should be a uuid"); <END> } ContentType contentTypeSaved = APILocator.getContentTypeAPI(user, true).save(type); retTypes.add(contentTypeSaved); this.workflowHelper.saveSchemesByContentType(contentTypeSaved.inode(), user, workflowsIds); } response = Response.ok(new ResponseEntityView(new JsonContentTypeTransformer(retTypes).mapList())).build(); } catch (DotStateException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (DotDataException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }</code><technical_language>add some log</technical_language>

Target:
public final Response createType(@Context final HttpServletRequest req, final ContentTypeForm form) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); Response response = null; try { Logger.debug(this, String.format("Saving new content type", form.getRequestJson())); final Iterable<ContentTypeForm.ContentTypeFormEntry> typesToSave = form.getIterable(); final List<ContentType> retTypes = new ArrayList<>(); for (final ContentTypeForm.ContentTypeFormEntry entry : typesToSave) { final ContentType type = entry.contentType; final List<String> workflowsIds = entry.workflowsIds; if (UtilMethods.isSet(type.id()) && !UUIDUtil.isUUID(type.id())) { return ExceptionMapperUtil.createResponse(null, "ContentType 'id' if set, should be a uuid"); } final ContentType contentTypeSaved = APILocator.getContentTypeAPI(user, true).save(type); retTypes.add(contentTypeSaved); this.workflowHelper.saveSchemesByContentType(contentTypeSaved.inode(), user, workflowsIds); } response = Response.ok(new ResponseEntityView(new JsonContentTypeTransformer(retTypes).mapList())).build(); } catch (DotStateException | DotDataException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
Source:
<code>private static TimeLockDialogueServiceProvider createTimeLockDialogueServiceProvider( MetricsManager metricsManager, TimeLockInstallConfiguration install, UserAgent userAgent) { DialogueClients.ReloadingFactory baseFactory = DialogueClients.create( Refreshable.only(ServicesConfigBlock.builder().build())); ServerListConfig timeLockServerListConfig = ImmutableServerListConfig.builder() .addAllServers(PaxosRemotingUtils.getRemoteServerPaths(install)) .sslConfiguration(install.cluster().cluster().security()) .proxyConfiguration(install.cluster().cluster().proxyConfiguration()) .build(); return TimeLockDialogueServiceProvider.create( metricsManager.getTaggedRegistry(), baseFactory, timeLockServerListConfig, AuxiliaryRemotingParameters.builder() .userAgent(userAgent) .shouldLimitPayload(false) <START> .shouldRetry(false) END> .remotingClientConfig(() -> RemotingClientConfigs.DEFAULT) .shouldUseExtendedTimeout(false) .build()); }</code><technical_language>Fair enough, live this</technical_language>

Target:
private static TimeLockDialogueServiceProvider createTimeLockDialogueServiceProvider( MetricsManager metricsManager, TimeLockInstallConfiguration install, UserAgent userAgent) { DialogueClients.ReloadingFactory baseFactory = DialogueClients.create( Refreshable.only(ServicesConfigBlock.builder().build())); ServerListConfig timeLockServerListConfig = ImmutableServerListConfig.builder() .addAllServers(PaxosRemotingUtils.getRemoteServerPaths(install)) .sslConfiguration(install.cluster().cluster().security()) .proxyConfiguration(install.cluster().cluster().proxyConfiguration()) .build(); return TimeLockDialogueServiceProvider.create( metricsManager.getTaggedRegistry(), baseFactory, timeLockServerListConfig, AuxiliaryRemotingParameters.builder() .userAgent(userAgent) .shouldLimitPayload(false) .remotingClientConfig(() -> RemotingClientConfigs.DEFAULT) .shouldUseExtendedTimeout(false) .build()); }
Source:
<code>static void copyErrors(PipelineConfig from, PipelineConfig to) { copy(from, to); copyCollectionErrors(from.materialConfigs(), to.materialConfigs()); copyCollectionErrors(from.getVariables(), to.getVariables()); copyCollectionErrors(from.getParams(), to.getParams()); copy(from.getTrackingTool(), to.getTrackingTool()); for (StageConfig fromStage : from.getStages()) { StageConfig toStage = to.findBy(fromStage.name()); copy(fromStage, toStage); copyCollectionErrors(fromStage.getVariables(), toStage.getVariables()); <START> for (JobConfig fromJob : fromStage.getJobs()) { <END> JobConfig toJob = toStage.jobConfigByConfigName(fromJob.name()); copy(fromJob, toJob); copyCollectionErrors(fromJob.getTasks(), toJob.getTasks()); copyCollectionErrors(fromJob.artifactPlans(), toJob.artifactPlans()); copyCollectionErrors(fromJob.getTabs(), toJob.getTabs()); copyCollectionErrors(fromJob.getProperties(), toJob.getProperties()); copyCollectionErrors(fromJob.getVariables(), toJob.getVariables()); } } }</code><technical_language>I this work for pipelines templates, toStage null</technical_language>

Target:
static void copyErrors(PipelineConfig from, PipelineConfig to) { copy(from, to); copyCollectionErrors(from.materialConfigs(), to.materialConfigs()); copyCollectionErrors(from.getVariables(), to.getVariables()); copyCollectionErrors(from.getParams(), to.getParams()); copy(from.getTrackingTool(), to.getTrackingTool()); for (StageConfig toStage : to.getStages()) { StageConfig fromStage = from.findBy(toStage.name()); copy(fromStage, toStage); copyCollectionErrors(fromStage.getVariables(), toStage.getVariables()); for (JobConfig toJob : toStage.getJobs()) { JobConfig fromJob = fromStage.jobConfigByConfigName(toJob.name()); copy(toJob, fromJob); copyCollectionErrors(fromJob.getTasks(), toJob.getTasks()); copyCollectionErrors(fromJob.artifactPlans(), toJob.artifactPlans()); copyCollectionErrors(fromJob.getTabs(), toJob.getTabs()); copyCollectionErrors(fromJob.getProperties(), toJob.getProperties()); copyCollectionErrors(fromJob.getVariables(), toJob.getVariables()); } } }
Source:
<code>GHMarketplaceListAccountBuilder(GitHub root, long planId) { this.root = root; <START> this.builder = new Requester(root); <END> this.planId = planId; }</code><technical_language>suggestion this.builder = root.createRequest();</technical_language>

Target:
GHMarketplaceListAccountBuilder(GitHub root, long planId) { this.root = root; this.builder = root.createRequest(); this.planId = planId; }
Source:
<code>protected InternalCache createCacheAndCreateJdbcMapping(String cacheXmlTestName) throws Exception { InternalCache cache = (InternalCache) new CacheFactory().set("locators", "").set("mcast-port", "0").create(); Set<DistributedMember> targetMembers = findMembers(cache, null, null); <START> CliFunctionResult createRegionFuncResult = executeCreateRegionFunction(targetMembers); <END> System.out.println("createRegionFuncResult=" + createRegionFuncResult); CliFunctionResult createDataStoreFuncResult = executeCreateJndiBindingFunction(targetMembers, dbRule.getConnectionUrl()); System.out.println("createDataStoreFuncArgs=" + createDataStoreFuncResult); CliFunctionResult createMappingFuncResult = executeCreateMappingFunction(Employee.class.getName(), targetMembers); System.out.println("createMappingFuncResult=" + createMappingFuncResult); return cache; }</code><technical_language>create region, data store mapping etc, I recommend GfshRule execute gfsh commands, instead of calling internal functions implement gfsh commands</technical_language>

Target:
protected InternalCache createCacheAndCreateJdbcMapping(String cacheXmlTestName) throws Exception { InternalCache cache = (InternalCache) new CacheFactory().set("locators", "").set("mcast-port", "0").create(); Set<DistributedMember> targetMembers = findMembers(cache, null, null); CliFunctionResult createRegionFuncResult = executeCreateRegionFunction(targetMembers); CliFunctionResult createDataStoreFuncResult = executeCreateJndiBindingFunction(targetMembers, dbRule.getConnectionUrl()); CliFunctionResult createMappingFuncResult = executeCreateMappingFunction(Employee.class.getName(), targetMembers); return cache; }
Source:
<code>private void checkRssTimeNode(Node firstBuild, String nodeName) throws ParseException { String pubDate = getSingleNode(firstBuild, nodeName).getTextContent(); <START> assertNotNull(pubDate); <END> DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); Date date = formatter.parse("Sat, 24 Apr 2010 14:01:00 GMT"); assertNotNull(date); }</code><technical_language>suggestion assertThat(pubDate, not(emptyString())); getTextContent returns null. If node exist, NPE method called. prevent next suggestion throw exception if string is empty</technical_language>

Target:
private void checkRssTimeNode(Node firstBuild, String nodeName) throws ParseException { String pubDate = getSingleNode(firstBuild, nodeName).getTextContent(); assertThat(pubDate, not(emptyString())); DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); Date date = formatter.parse(pubDate); assertNotNull(date); }
Source:
<code>private void refresh() { <START> final TmfTraceManager tm = TmfTraceManager.getInstance(); <END> Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (fTimeGraphViewer.getControl().isDisposed()) { return; } ITimeGraphEntry[] entries = null; synchronized (fEntryListMap) { fEntryList = fEntryListMap.get(fTrace); if (fEntryList == null) { fEntryList = new ArrayList<TraceEntry>(); } entries = fEntryList.toArray(new ITimeGraphEntry[0]); } if (entries != null) { Arrays.sort(entries, new TraceEntryComparator()); fTimeGraphViewer.setInput(entries); fTimeGraphViewer.setTimeBounds(fStartTime, fEndTime); long timestamp = fTrace == null ? 0 : tm.getCurrentTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long startTime = fTrace == null ? 0 : tm.getCurrentRange().getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long endTime = fTrace == null ? 0 : tm.getCurrentRange().getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); startTime = Math.max(startTime, fStartTime); endTime = Math.min(endTime, fEndTime); fTimeGraphViewer.setSelectedTime(timestamp, false); fTimeGraphViewer.setStartFinishTime(startTime, endTime); startZoomThread(startTime, endTime); } } }); }</code><technical_language>move this run method</technical_language>

Target:
private void refresh() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (fTimeGraphViewer.getControl().isDisposed()) { return; } ITimeGraphEntry[] entries = null; synchronized (fEntryListMap) { fEntryList = fEntryListMap.get(fTrace); if (fEntryList == null) { fEntryList = new ArrayList<TraceEntry>(); } entries = fEntryList.toArray(new ITimeGraphEntry[0]); } if (entries != null) { Arrays.sort(entries, new TraceEntryComparator()); fTimeGraphViewer.setInput(entries); fTimeGraphViewer.setTimeBounds(fStartTime, fEndTime); final TmfTraceManager tm = TmfTraceManager.getInstance(); long timestamp = fTrace == null ? 0 : tm.getCurrentTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long startTime = fTrace == null ? 0 : tm.getCurrentRange().getStartTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); long endTime = fTrace == null ? 0 : tm.getCurrentRange().getEndTime().normalize(0, ITmfTimestamp.NANOSECOND_SCALE).getValue(); startTime = Math.max(startTime, fStartTime); endTime = Math.min(endTime, fEndTime); fTimeGraphViewer.setSelectedTime(timestamp, false); fTimeGraphViewer.setStartFinishTime(startTime, endTime); startZoomThread(startTime, endTime); } } }); }
Source:
<code>private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> dclist = new ArrayList<>(); synchronized (containerLock) { List<Container> list = null; try { list = client.listContainers(DockerClient.ListContainersParam .allContainers()); } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind( Messages.List_Docker_Containers_Failure, this.getName()), e); } for (Container c : list) { if (c.status().startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(c.id())) { loggingThreads.get(c.id()).requestStop(); loggingThreads.remove(c.id()); } } <START> dclist.add(new DockerContainer(this, c)); <END> } containers = dclist; } notifyContainerListeners(this, dclist); return dclist; }</code><technical_language>is intent decouple classes docker api? bad pass Container type DockerContainer</technical_language>

Target:
private List<IDockerContainer> listContainers() throws DockerException { final List<IDockerContainer> dclist = new ArrayList<>(); synchronized (containerLock) { List<Container> list = null; try { list = client.listContainers(DockerClient.ListContainersParam .allContainers()); } catch (com.spotify.docker.client.DockerException | InterruptedException e) { throw new DockerException( NLS.bind( Messages.List_Docker_Containers_Failure, this.getName()), e); } for (Container c : list) { if (c.status().startsWith(Messages.Exited_specifier)) { if (loggingThreads.containsKey(c.id())) { loggingThreads.get(c.id()).requestStop(); loggingThreads.remove(c.id()); } } dclist.add(new DockerContainer(this, c)); } containers = dclist; } notifyContainerListeners(dclist); return dclist; }
Source:
<code>protected List<ResourceGroupSpec> getRootGroups() { if (lastRefresh.get() == 0) { <START> throw new PrestoException(CONFIGURATION_UNAVAILABLE, "Root groups could not be fetched from database"); <END> } if (this.selectors.get().isEmpty()) { throw new PrestoException(CONFIGURATION_INVALID, "No root groups are configured"); } return rootGroups.get(); }</code><technical_language>nit: Root groups fetched database</technical_language>

Target:
protected List<ResourceGroupSpec> getRootGroups() { if (lastRefresh.get() == 0) { throw new PrestoException(CONFIGURATION_UNAVAILABLE, "Root groups cannot be fetched from database"); } if (this.selectors.get().isEmpty()) { throw new PrestoException(CONFIGURATION_INVALID, "No root groups are configured"); } return rootGroups.get(); }
Source:
<code>public ERXKey(String key, Type type) { _key = key; <START> setType(type); <END> }</code><technical_language>set variable instead of calling a non-final method (there some discussion topic mailing list I think)</technical_language>

Target:
public ERXKey(String key, Type type) { _key = key; _type = type; }
Source:
<code>private RemoteClassLoader(@CheckForNull ClassLoader parent, @Nonnull IClassLoader proxy) { super(new URL[0],parent); final Channel channel = RemoteInvocationHandler.unwrap(proxy); this.channel = channel == null ? null : channel.ref(); this.underlyingProxy = proxy; final IClassLoader targetProxy; if (channel == null || !channel.remoteCapability.supportsPrefetch() || channel.getJarCache()==null) { targetProxy = new DumbClassLoaderBridge(proxy); } else { targetProxy = proxy; } <START> this.proxy = (IClassLoader) Proxy.newProxyInstance(RemoteClassLoader.class.getClassLoader(), <END> new Class[] { IClassLoader.class }, (p, method, methodArgs) -> { Object result; boolean interrupted = false; try { while (true) { try { result = method.invoke(targetProxy, methodArgs); break; } catch (InvocationTargetException x) { Throwable e = x.getCause(); if (e instanceof RemotingSystemException && (e.getCause() instanceof InterruptedException || e.getCause() instanceof InterruptedIOException) && !"fetchJar".equals(method.getName())) { interrupted = true; } else { throw e; } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return result; }); }</code><technical_language>biggest concern this approach is deep nesting impacts readability. a number of options, try improve readability. next concern is I bitten in performance degradation reflection. of time enough concern, a worried do in this area. I this handles a central, localized place, I worth exploring if done in a more readable fashion reflection performance concerns a dynamic proxy here</technical_language>

Target:
private RemoteClassLoader(@CheckForNull ClassLoader parent, @Nonnull IClassLoader proxy) { super(new URL[0], parent); final Channel channel = RemoteInvocationHandler.unwrap(proxy); this.channel = channel == null ? null : channel.ref(); this.underlyingProxy = proxy; final IClassLoader targetProxy; if (channel == null || !channel.remoteCapability.supportsPrefetch() || channel.getJarCache() == null) { targetProxy = new DumbClassLoaderBridge(proxy); } else { targetProxy = proxy; } if (RemoteInterruptedExceptionCatcher.shouldBeEnabled()) { this.proxy = (IClassLoader) Proxy.newProxyInstance(RemoteClassLoader.class.getClassLoader(), new Class[] { IClassLoader.class }, new RemoteInterruptedExceptionCatcher(targetProxy)); } else { this.proxy = targetProxy; } }
Source:
<code>public void checkWillOnlyTakeBroadcastMatchingCandidatesNotAll() { EquivalenceResult equivalenceResult = itemsWithBroadcastAndScores( "4500", "2500", "9500", "4400", "6500", "9600", 5.0, 4.8, 4.9 ); <START> assertTrue(equivalenceResult.strongEquivalences().values().size() == 2); <END> }</code><technical_language>need check equivalences back, is of them</technical_language>

Target:
public void checkWillOnlyTakeBroadcastMatchingCandidatesNotAll() { EquivalenceResult equivalenceResult = itemsWithBroadcastAndScores( new DateTime().withHourOfDay(2), new DateTime().withHourOfDay(4), new DateTime().withHourOfDay(2), new DateTime().withHourOfDay(3), new DateTime().withHourOfDay(9), new DateTime().withHourOfDay(4), new DateTime().withHourOfDay(6), new DateTime().withHourOfDay(9).withMinuteOfHour(15), 5.0, 4.8, 4.9 ); assertTrue(equivalenceResult.strongEquivalences().values().size() == 1); }
Source:
<code>private void receivePack() throws IOException { if (timeoutIn != null) timeoutIn.setTimeout(10 * timeout * 1000); ip = IndexPack.create(db, rawIn); ip.setFixThin(true); <START> ip.setNeedNewObjectIds(needNewObjectIds); <END> ip.setNeedBaseObjectIds(needBaseObjectIds); ip.setObjectChecking(isCheckReceivedObjects()); ip.index(NullProgressMonitor.INSTANCE); String lockMsg = "jgit receive-pack"; if (getRefLogIdent() != null) lockMsg += " from " + getRefLogIdent().toExternalString(); packLock = ip.renameAndOpenPack(lockMsg); if (timeoutIn != null) timeoutIn.setTimeout(timeout * 1000); }</code><technical_language>needNewObjectIds || ensureObjectsProvidedVisible</technical_language>

Target:
private void receivePack() throws IOException { if (timeoutIn != null) timeoutIn.setTimeout(10 * timeout * 1000); ip = IndexPack.create(db, rawIn); ip.setFixThin(true); ip.setNeedNewObjectIds(needNewObjectIds || ensureObjectsProvidedVisible); ip.setNeedBaseObjectIds(needBaseObjectIds || ensureObjectsProvidedVisible); ip.setObjectChecking(isCheckReceivedObjects()); ip.index(NullProgressMonitor.INSTANCE); String lockMsg = "jgit receive-pack"; if (getRefLogIdent() != null) lockMsg += " from " + getRefLogIdent().toExternalString(); packLock = ip.renameAndOpenPack(lockMsg); if (timeoutIn != null) timeoutIn.setTimeout(timeout * 1000); }
Source:
<code>private Map<String, List<String>> generateHeaderMap () { Map<String, List<String>> headerMap = new HashMap<String, List<String>>(); List<String> bearerHeader = new ArrayList<String>(); bearerHeader.add("Bearer"); bearerHeader.add("sk_live_12345"); List<String> requestIdHeader = new ArrayList<String>(); requestIdHeader.add("req_12345"); headerMap.put("Request-Id", requestIdHeader); <START> headerMap.put("Authorization", bearerHeader); <END> headerMap.put("Empty-Header", new ArrayList<String>()); return headerMap; }</code><technical_language>I this header test get() method, I find a bit confusing Authorization header in object represents _response_'s header. mind changing else? a generic name e.g. "Some-Header" a header in responses e.g. "Stripe-Version"</technical_language>

Target:
private Map<String, List<String>> generateHeaderMap () { Map<String, List<String>> headerMap = new HashMap<String, List<String>>(); List<String> multiValueHeader = new ArrayList<String>(); multiValueHeader.add("FirstValue"); multiValueHeader.add("SecondValue"); List<String> requestIdHeader = new ArrayList<String>(); requestIdHeader.add("req_12345"); headerMap.put("Request-Id", requestIdHeader); headerMap.put("Multi-Val", multiValueHeader); headerMap.put("Empty-Header", new ArrayList<String>()); return headerMap; }
Source:
<code>public void onMatch(RelOptRuleCall call) { assert matches(call); final Join join = call.rel(0); RelNode right = join.getRight(); final RelNode left = join.getLeft(); final int leftFieldCount = left.getRowType().getFieldCount(); final RelOptCluster cluster = join.getCluster(); final RexBuilder rexBuilder = cluster.getRexBuilder(); final RelBuilder relBuilder = call.builder(); final CorrelationId correlationId = cluster.createCorrel(); final RexNode corrVar = rexBuilder.makeCorrel(left.getRowType(), correlationId); final ImmutableBitSet.Builder requiredColumns = ImmutableBitSet.builder(); final RexNode joinCondition = join.getCondition().accept(new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef input) { int field = input.getIndex(); if (field >= leftFieldCount) { return rexBuilder.makeInputRef(input.getType(), input.getIndex() - leftFieldCount); } requiredColumns.set(field); return rexBuilder.makeFieldAccess(corrVar, field); } }); relBuilder.push(right).filter(joinCondition); RelNode newRel = LogicalCorrelate.create(left, relBuilder.build(), correlationId, requiredColumns.build(), <START> join instanceof SemiJoin ? SemiJoinType.SEMI : SemiJoinType.of(join.getJoinType())); <END> call.transformTo(newRel); }</code><technical_language>avoid this cast introducing a more general method in Join bring necessary types (SEMI, ANTI, etc.)</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { assert matches(call); final Join join = call.rel(0); RelNode right = join.getRight(); final RelNode left = join.getLeft(); final int leftFieldCount = left.getRowType().getFieldCount(); final RelOptCluster cluster = join.getCluster(); final RexBuilder rexBuilder = cluster.getRexBuilder(); final RelBuilder relBuilder = call.builder(); final CorrelationId correlationId = cluster.createCorrel(); final RexNode corrVar = rexBuilder.makeCorrel(left.getRowType(), correlationId); final ImmutableBitSet.Builder requiredColumns = ImmutableBitSet.builder(); final RexNode joinCondition = join.getCondition().accept(new RexShuttle() { @Override public RexNode visitInputRef(RexInputRef input) { int field = input.getIndex(); if (field >= leftFieldCount) { return rexBuilder.makeInputRef(input.getType(), input.getIndex() - leftFieldCount); } requiredColumns.set(field); return rexBuilder.makeFieldAccess(corrVar, field); } }); relBuilder.push(right).filter(joinCondition); RelNode newRel = LogicalCorrelate.create(left, relBuilder.build(), correlationId, requiredColumns.build(), semiJoinTypeExtractor.apply(join)); call.transformTo(newRel); }
Source:
<code>private void vmUpdateStatus(final VM vm, final VM.VMStatus status, final long delay, final String msg, final boolean updateHost) throws InterruptedException { <START> Thread updateStatus = new Thread(new Runnable() { <END> @Override public void run() { try { TimeUnit.MILLISECONDS.sleep(delay); vm.setStatus(status); sendNotification(msg, vm.getId()); log.info("VM set to {}", vm.getId(), msg); if (updateHost){ VdsmManager.getInstance().updateHost(vm.getHost()); } }catch (Exception e){ log.error(e.toString()); } } }); updateStatus.start(); }</code><technical_language>I a thread pool instead of creating a thread manually</technical_language>

Target:
private void vmUpdateStatus(final VM vm, final VM.VMStatus status, final long delay, final String msg, final boolean updateHost) throws InterruptedException { service.submit(new EventHandler(vm, status, delay, msg, updateHost)); }
Source:
<code>protected ExecutorService buildFixedThreadPoolExecutorService(String key) { String stringProperty = System.getProperty(key); <START> int threadLimit = stringProperty == null ? 0 : Integer.valueOf(stringProperty); <END> if (threadLimit > 0) { return Executors.newFixedThreadPool(threadLimit, new DescriptiveThreadFactory()); } else { return Executors.newCachedThreadPool(new DescriptiveThreadFactory()); } }</code><technical_language>_NumberFormatException_ if key a text "abc"</technical_language>

Target:
protected ExecutorService buildFixedThreadPoolExecutorService(String key) { String stringProperty = System.getProperty(key); int threadLimit = stringProperty == null ? 0 : toInteger(stringProperty); if (threadLimit > 0) { return Executors.newFixedThreadPool(threadLimit, new DescriptiveThreadFactory()); } else { return Executors.newCachedThreadPool(new DescriptiveThreadFactory()); } }