auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context ) throws ProtocolException { final URI uri = getLocationURI( request, response, context ); final String method = request.getRequestLine().getMethod(); if ( method.equalsIgnoreCase( HttpHead.METHOD_NAME ) ) { return new HttpHead( uri ); } else if ( method.equalsIgnoreCase( HttpGet.METHOD_NAME ) ) { return new HttpGet( uri ); } else { <START> return RequestBuilder.copy( request ).setUri( uri ).build(); <END> } }</code><technical_language>@michael-o I suppose is need treat HEAD GET special cases. RequestBuilder.copy( request ).setUri( uri ).build(); OK for methods. good me</technical_language>

Target:
public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context ) throws ProtocolException { final URI uri = getLocationURI( request, response, context ); return RequestBuilder.copy( request ).setUri( uri ).build(); }
Source:
<code>public void afterFromProto(MessageOrBuilder proto) { condition = ZoomConvert.fromProto(proto, Condition.class); Topology.Rule rule = (Topology.Rule) proto; if (rule.getType() == Topology.Rule.Type.NAT_RULE && rule.getMatchForwardFlow()) { <START> ForwardNatRule natRule = (ForwardNatRule) this; natRule.buildFields(); <END> } validateProto(rule); }</code><technical_language>override afterFromProto in ForwardNatRule class, adding initialization code needed</technical_language>

Target:
public void afterFromProto(MessageOrBuilder proto) { condition = ZoomConvert.fromProto(proto, Condition.class); validateProto((Topology.Rule) proto); }
Source:
<code>static String getUnresolvedSchemaName(final Schema schema) { String name = schema.getProp(UR_SCHEMA_ATTR); if (name == null) { <START> throw new IllegalArgumentException("Schema " + schema + " is not a unresolved schema"); <END> } else { return name; } }</code><technical_language>record name, org.apache.avro.compiler.UnresolvedSchema, this unresolved schema? I this error message unresolved schema name missing</technical_language>

Target:
static String getUnresolvedSchemaName(final Schema schema) { if (!isUnresolvedSchema(schema)) { throw new IllegalArgumentException("Not a unresolved schema: " + schema); } return schema.getProp(UR_SCHEMA_ATTR); }
Source:
<code>public void killAll() throws IOException { <START> log.info("Deleting all segment files from Azure storage location [bucket: '%s' prefix: '%s']", segmentConfig.getContainer(), segmentConfig.getPrefix() ); <END> try { AzureUtils.deleteObjectsInPath( azureStorage, inputDataConfig, accountConfig, azureCloudBlobIterableFactory, segmentConfig.getContainer(), segmentConfig.getPrefix(), Predicates.alwaysTrue() ); } catch (Exception e) { log.error("Error occurred while deleting segment files from s3. Error: %s", e.getMessage()); throw new IOException(e); } }</code><technical_language>nit: formatting suggestion log.info( "Deleting segment files Azure storage location [bucket: '%s' prefix: '%s']", segmentConfig.getContainer(), segmentConfig.getPrefix() );</technical_language>

Target:
public void killAll() throws IOException { log.info( "Deleting all segment files from Azure storage location [bucket: '%s' prefix: '%s']", segmentConfig.getContainer(), segmentConfig.getPrefix() ); try { AzureUtils.deleteObjectsInPath( azureStorage, inputDataConfig, accountConfig, azureCloudBlobIterableFactory, segmentConfig.getContainer(), segmentConfig.getPrefix(), Predicates.alwaysTrue() ); } catch (Exception e) { log.error("Error occurred while deleting segment files from Azure. Error: %s", e.getMessage()); throw new IOException(e); } }
Source:
<code>public void getSegmentFiles(DataSegment segment, File outDir) throws SegmentLoadingException { String key = (String) segment.getLoadSpec().get("key"); log.info("Pulling index from C* at path[%s] to outDir[%s]", key, outDir); if (!outDir.exists()) { outDir.mkdirs(); } if (!outDir.isDirectory()) { throw new ISE("outDir[%s] must be a directory.", outDir); } long startTime = System.currentTimeMillis(); ObjectMetadata meta = null; try { final File outFile = new File(outDir, "index.zip"); log.info("Writing to [" + outFile.getAbsolutePath() + "]"); OutputStream os = Files.newOutputStreamSupplier(outFile).getOutput(); meta = ChunkedStorage .newReader(indexStorage, key, os) .withBatchSize(BATCH_SIZE) .withConcurrencyLevel(CONCURRENCY) .call(); os.close(); CompressionUtils.unzip(outFile, outDir); } catch (Exception e) { <START> throw Throwables.propagate(e); <END> } log.info("Pull of file[%s] completed in %,d millis (%s bytes)", key, System.currentTimeMillis() - startTime, meta.getObjectSize()); }</code><technical_language>this clean up? usages of this a caller clean directories, useful for this attempt cleanup</technical_language>

Target:
public void getSegmentFiles(DataSegment segment, File outDir) throws SegmentLoadingException { String key = (String) segment.getLoadSpec().get("key"); log.info("Pulling index from C* at path[%s] to outDir[%s]", key, outDir); if (!outDir.exists()) { outDir.mkdirs(); } if (!outDir.isDirectory()) { throw new ISE("outDir[%s] must be a directory.", outDir); } long startTime = System.currentTimeMillis(); ObjectMetadata meta = null; final File outFile = new File(outDir, "index.zip"); try { try { log.info("Writing to [%s]", outFile.getAbsolutePath()); OutputStream os = Files.newOutputStreamSupplier(outFile).getOutput(); meta = ChunkedStorage .newReader(indexStorage, key, os) .withBatchSize(BATCH_SIZE) .withConcurrencyLevel(CONCURRENCY) .call(); os.close(); CompressionUtils.unzip(outFile, outDir); } catch (Exception e) { FileUtils.deleteDirectory(outDir); } } catch (Exception e) { throw new SegmentLoadingException(e, e.getMessage()); } log.info("Pull of file[%s] completed in %,d millis (%s bytes)", key, System.currentTimeMillis() - startTime, meta.getObjectSize()); }
Source:
<code>private static InternalTask createTask(Job userJob, NativeTask task) throws JobCreationException { if (((task.getCommandLine() == null) || (task.getCommandLine().length == 0))) { String msg = "The command line is null or empty and not generated !"; logger.info(msg); throw new JobCreationException(msg); } try { String commandAndArguments = "\"" + Joiner.on("\" \"").join(task.getCommandLine()) + "\""; InternalTask scriptTask; if (isForkingTask()) { scriptTask = new InternalForkedScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(commandAndArguments, "native")))); <START> if (isRunAsMeTask()) { <END> task.setRunAsMe(true); scriptTask.setRunAsMe(true); } } else { scriptTask = new InternalScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(commandAndArguments, "native")))); } ForkEnvironment forkEnvironment = new ForkEnvironment(); scriptTask.setForkEnvironment(forkEnvironment); setTaskCommonProperties(userJob, task, scriptTask); return scriptTask; } catch (Exception e) { throw new JobCreationException(e); } }</code><technical_language>code is duplicated 3 times, please factorize a dedicated method</technical_language>

Target:
private static InternalTask createTask(Job userJob, NativeTask task) throws JobCreationException { if (((task.getCommandLine() == null) || (task.getCommandLine().length == 0))) { String msg = "The command line is null or empty and not generated !"; logger.info(msg); throw new JobCreationException(msg); } try { String commandAndArguments = "\"" + Joiner.on("\" \"").join(task.getCommandLine()) + "\""; InternalTask scriptTask; if (isForkingTask()) { scriptTask = new InternalForkedScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(commandAndArguments, "native")))); configureRunAsMe(task); } else { scriptTask = new InternalScriptTask(new ScriptExecutableContainer( new TaskScript(new SimpleScript(commandAndArguments, "native")))); } ForkEnvironment forkEnvironment = new ForkEnvironment(); scriptTask.setForkEnvironment(forkEnvironment); setTaskCommonProperties(userJob, task, scriptTask); return scriptTask; } catch (Exception e) { throw new JobCreationException(e); } }
Source:
<code>public FEELFnResult<Boolean> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern, @ParameterName("flags") String flags) { if ( input == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "input", "cannot be null" ) ); } if ( pattern == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "cannot be null" ) ); } try { int f = processFlags( flags ); Pattern p = Pattern.compile( pattern, f ); Matcher m = p.matcher( input ); return FEELFnResult.ofResult( m.find() ); } catch ( PatternSyntaxException e ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "is invalid and can not be compiled", e ) ); <START> } catch ( IllegalArgumentException t ) { <END> return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "flags", "contains unknown flags", t ) ); } }</code><technical_language>reason I Throwable is predict errors statement generate. Throwable catch avoids engine blowing in case of problems</technical_language>

Target:
public FEELFnResult<Boolean> invoke(@ParameterName("input") String input, @ParameterName("pattern") String pattern, @ParameterName("flags") String flags) { if ( input == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "input", "cannot be null" ) ); } if ( pattern == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "cannot be null" ) ); } try { int f = processFlags( flags ); Pattern p = Pattern.compile( pattern, f ); Matcher m = p.matcher( input ); return FEELFnResult.ofResult( m.find() ); } catch ( PatternSyntaxException e ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "is invalid and can not be compiled", e ) ); } catch ( IllegalArgumentException t ) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "flags", "contains unknown flags", t ) ); } catch ( Throwable t) { return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "pattern", "is invalid and can not be compiled", t ) ); } }
Source:
<code>public int compare(File a, File b) { <START> if (a.getPath().endsWith(".module.ts")) { <END> return 1; } else if (b.getPath().endsWith(".module.ts")) { return -1; } return 0; }</code><technical_language>If of (a b) end module.ts, this inconsistent: * compare(a, b) 1, compare(b, a) 1</technical_language>

Target:
public int compare(File a, File b) { boolean isAModule = a.getPath().endsWith(".module.ts"); boolean isBModule = b.getPath().endsWith(".module.ts"); if (isAModule && !isBModule) { return 1; } else if (isBModule && !isAModule) { return -1; } else { return a.getAbsolutePath().compareTo(b.getAbsolutePath()); } }
Source:
<code>private void updateCaret() { <START> if (fSourceViewer == null || fSourceViewer.getTextWidget() == null) { <END> return; } StyledText styledText= fSourceViewer.getTextWidget(); InsertMode mode= getInsertMode(); styledText.setCaret(null); disposeNonDefaultCaret(); if (getPreferenceStore() == null || !getPreferenceStore().getBoolean(PREFERENCE_USE_CUSTOM_CARETS)) { Assert.isTrue(fNonDefaultCaret == null); } else if (fIsOverwriting) { fNonDefaultCaret= createOverwriteCaret(styledText); } else if (SMART_INSERT == mode) { fNonDefaultCaret= createInsertCaret(styledText); } else if (INSERT == mode) { fNonDefaultCaret= createRawInsertModeCaret(styledText); } if (fNonDefaultCaret != null) { styledText.setCaret(fNonDefaultCaret); fNonDefaultCaretImage= fNonDefaultCaret.getImage(); } else if (fInitialCaret != styledText.getCaret()) { styledText.setCaret(fInitialCaret); } }</code><technical_language>Good brackets for new code</technical_language>

Target:
private void updateCaret() { if (fSourceViewer == null || fSourceViewer.getTextWidget() == null) { return; } StyledText styledText= fSourceViewer.getTextWidget(); InsertMode mode= getInsertMode(); styledText.setCaret(null); disposeNonDefaultCaret(); if (getPreferenceStore() == null || !getPreferenceStore().getBoolean(PREFERENCE_USE_CUSTOM_CARETS)) Assert.isTrue(fNonDefaultCaret == null); else if (fIsOverwriting) fNonDefaultCaret= createOverwriteCaret(styledText); else if (SMART_INSERT == mode) fNonDefaultCaret= createInsertCaret(styledText); else if (INSERT == mode) fNonDefaultCaret= createRawInsertModeCaret(styledText); if (fNonDefaultCaret != null) { styledText.setCaret(fNonDefaultCaret); fNonDefaultCaretImage= fNonDefaultCaret.getImage(); } else if (fInitialCaret != styledText.getCaret()) styledText.setCaret(fInitialCaret); }
Source:
<code><START> public static List<String> readStringArray(DataInput in) throws IOException <END> { int count = WritableUtils.readVInt(in); if(count == 0) { return null; } List<String> values = Lists.newArrayListWithCapacity(count); for(int i = 0; i < count; i++) { values.add(readString(in)); } return values; }</code><technical_language>util methods private</technical_language>

Target:
private static List<String> readStringArray(DataInput in) throws IOException { int count = WritableUtils.readVInt(in); if (count == 0) { return null; } List<String> values = Lists.newArrayListWithCapacity(count); for (int i = 0; i < count; i++) { values.add(readString(in)); } return values; }
Source:
<code>public void parse_shouldReturnAnMrrtTemplateObjectIfFileIsValid() throws Exception { String templateContent = getFileContent("mrrttemplates/ihe/connectathon/2015/CTChestAbdomen.html"); MrrtReportTemplate template = parser.parse(templateContent); <START> Date dcTermsDate = new SimpleDateFormat("yyyy-MM-dd").parse(TEST_DCTERMS_DATE); <END> assertNotNull(template); assertThat(template.getCharset(), is(CHARSET)); assertThat(template.getDcTermsTitle(), is(TEST_DCTERMS_TITLE)); assertThat(template.getDcTermsDescription(), is(TEST_DCTERMS_DESCRIPTION)); assertThat(template.getDcTermsIdentifier(), is(TEST_DCTERMS_IDENTIFIER)); assertThat(template.getDcTermsLanguage(), is(TEST_DCTERMS_LANGUAGE)); assertThat(template.getDcTermsLanguage(), is(TEST_DCTERMS_LANGUAGE)); assertThat(template.getDcTermsType(), is(TEST_DCTERMS_TYPE)); assertThat(template.getDcTermsPublisher(), is(TEST_DCTERMS_PUBLISHER)); assertThat(template.getDcTermsRights(), is(TEST_DCTERMS_RIGHTS)); assertThat(template.getDcTermsLicense(), is(TEST_DCTERMS_LICENSE)); assertThat(template.getDcTermsDate(), is(dcTermsDate)); assertThat(template.getDcTermsCreator(), is(TEST_DCTERMS_CREATOR)); }</code><technical_language>dont hard code format of date</technical_language>

Target:
public void parse_shouldReturnAnMrrtTemplateObjectIfFileIsValid() throws Exception { String templateContent = getFileContent("mrrttemplates/ihe/connectathon/2015/CTChestAbdomen.html"); MrrtReportTemplate template = parser.parse(templateContent); Date dcTermsDate = new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(TEST_DCTERMS_DATE); assertNotNull(template); assertThat(template.getCharset(), is(CHARSET)); assertThat(template.getDcTermsTitle(), is(TEST_DCTERMS_TITLE)); assertThat(template.getDcTermsDescription(), is(TEST_DCTERMS_DESCRIPTION)); assertThat(template.getDcTermsIdentifier(), is(TEST_DCTERMS_IDENTIFIER)); assertThat(template.getDcTermsLanguage(), is(TEST_DCTERMS_LANGUAGE)); assertThat(template.getDcTermsLanguage(), is(TEST_DCTERMS_LANGUAGE)); assertThat(template.getDcTermsType(), is(TEST_DCTERMS_TYPE)); assertThat(template.getDcTermsPublisher(), is(TEST_DCTERMS_PUBLISHER)); assertThat(template.getDcTermsRights(), is(TEST_DCTERMS_RIGHTS)); assertThat(template.getDcTermsLicense(), is(TEST_DCTERMS_LICENSE)); assertThat(template.getDcTermsDate(), is(dcTermsDate)); assertThat(template.getDcTermsCreator(), is(TEST_DCTERMS_CREATOR)); }
Source:
<code>public String getModel() throws KuraException { synchronized (atLock) { if (this.model == null) { logger.debug("sendCommand getModelNumber :: {}", HspaModemAtCommands.getModelNumber.getCommand()); <START> byte[] reply; <END> CommConnection commAtConnection = openSerialPort(getAtPort()); if (!isAtReachable(commAtConnection)) { closeSerialPort(commAtConnection); throw new KuraException(KuraErrorCode.NOT_CONNECTED, MODEM_NOT_AVAILABLE_FOR_AT_CMDS_MSG); } try { reply = commAtConnection.sendCommand(HspaModemAtCommands.getModelNumber.getCommand().getBytes(), 1000, 100); } catch (IOException e) { closeSerialPort(commAtConnection); throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } closeSerialPort(commAtConnection); if (reply != null) { this.model = getResponseString(reply); } } } return this.model; }</code><technical_language>unfortunate try-with-resources CommConnection, wrap in AutoCloseable stream... for next release</technical_language>

Target:
public String getModel() throws KuraException { synchronized (this.atLock) { if (this.model == null) { logger.debug("sendCommand getModelNumber :: {}", HspaModemAtCommands.getModelNumber.getCommand()); byte[] reply; CommConnection commAtConnection = openSerialPort(getAtPort()); if (!isAtReachable(commAtConnection)) { closeSerialPort(commAtConnection); throw new KuraException(KuraErrorCode.NOT_CONNECTED, MODEM_NOT_AVAILABLE_FOR_AT_CMDS_MSG); } try { reply = commAtConnection.sendCommand(HspaModemAtCommands.getModelNumber.getCommand().getBytes(), 1000, 100); } catch (IOException e) { closeSerialPort(commAtConnection); throw new KuraException(KuraErrorCode.CONNECTION_FAILED, e); } closeSerialPort(commAtConnection); if (reply != null) { this.model = getResponseString(reply); } } } return this.model; }
Source:
<code>ScopePassingSpanSubscriber(Subscriber<? super T> subscriber, Context ctx, Tracing tracing) { this.subscriber = subscriber; this.tracing = tracing; Span root = ctx != null ? <START> ctx.getOrDefault(Span.class, tracing.tracer().currentSpan()) : null; <END> this.spanTraceContext = root != null ? root.context() : null; this.context = ctx != null && root != null ? ctx.put(Span.class, root) : ctx != null ? ctx : Context.empty(); if (log.isTraceEnabled()) { log.trace("Root span [" + root + "], context [" + this.context + "]"); } }</code><technical_language>ahh Span is here.. need tracer afterall..</technical_language>

Target:
ScopePassingSpanSubscriber(Subscriber<? super T> subscriber, Context ctx, Tracing tracing) { this.subscriber = subscriber; this.currentTraceContext = tracing.currentTraceContext(); Span root = ctx != null ? ctx.getOrDefault(Span.class, tracing.tracer().currentSpan()) : null; this.spanTraceContext = root != null ? root.context() : null; this.context = ctx != null && root != null ? ctx.put(Span.class, root) : ctx != null ? ctx : Context.empty(); if (log.isTraceEnabled()) { log.trace("Root span [" + root + "], context [" + this.context + "]"); } }
Source:
<code>public void setTimerForDBCleanUpTask() { <START> ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); <END> scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { public void run() { LOG.debug("Deleting expired_objects from database."); persistenceService.deleteAllExpiredObjects(); } }, configurationService.get().getDbCleanupIntervalInHours(), configurationService.get().getDbCleanupIntervalInHours(), TimeUnit.HOURS); }</code><technical_language>executor <LINK_0> Withiut daemon shutdown of server cleanly</technical_language>

Target:
public void setTimerForDBCleanUpTask() { ScheduledExecutorService scheduledExecutorService = CoreUtils.createExecutor(); scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { public void run() { LOG.debug("Deleting expired_objects from database."); persistenceService.deleteAllExpiredObjects(); } }, configurationService.get().getDbCleanupIntervalInHours(), configurationService.get().getDbCleanupIntervalInHours(), TimeUnit.HOURS); }
Source:
<code>@VisibleForTesting Call<MwQueryResponse<CreateAccountInfo>> request(@NonNull Service service, @NonNull final Callback cb) { Call<MwQueryResponse<CreateAccountInfo>> call = service.request(); call.enqueue(new retrofit2.Callback<MwQueryResponse<CreateAccountInfo>>() { @Override public void onResponse(Call<MwQueryResponse<CreateAccountInfo>> call, Response<MwQueryResponse<CreateAccountInfo>> response) { if (response.isSuccessful()) { if (response.body().success()) { String token = response.body().query().token(); String captchaId = response.body().query().captchaId(); cb.success(call, new CreateAccountInfoResult(token, captchaId)); } else if (response.body().hasError()) { cb.failure(call, new MwApiErrorException(response.body().getError())); <START> } <END> } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<CreateAccountInfo>> call, Throwable t) { cb.failure(call, t); } }); return call; }</code><technical_language>I recommend adding a case callback returns</technical_language>

Target:
@VisibleForTesting Call<MwQueryResponse<CreateAccountInfo>> request(@NonNull Service service, @NonNull final Callback cb) { Call<MwQueryResponse<CreateAccountInfo>> call = service.request(); call.enqueue(new retrofit2.Callback<MwQueryResponse<CreateAccountInfo>>() { @Override public void onResponse(Call<MwQueryResponse<CreateAccountInfo>> call, Response<MwQueryResponse<CreateAccountInfo>> response) { if (response.isSuccessful()) { if (response.body().success()) { String token = response.body().query().token(); String captchaId = response.body().query().captchaId(); cb.success(call, new CreateAccountInfoResult(token, captchaId)); } else if (response.body().hasError()) { cb.failure(call, new MwApiException(response.body().getError())); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<CreateAccountInfo>> call, Throwable t) { cb.failure(call, t); } }); return call; }
Source:
<code>public List<CaddisflyResource> listResources() { List<CaddisflyResource> result = new ArrayList<CaddisflyResource>(); try { InputStream stream = getClass().getClassLoader().getResourceAsStream ("resources/caddisfly/caddisfly-tests.json"); String jsonTxt = IOUtils.toString(stream); <START> ObjectMapper mapper = new ObjectMapper(); <END> JsonNode rootNode = mapper.readValue(jsonTxt, JsonNode.class); ArrayNode testsNode = (ArrayNode) rootNode.get("tests"); for (int i = 0; i < testsNode.size(); i++){ CaddisflyResource cr = JsonToCaddisflyResource(testsNode.get(i)); result.add(cr); } } catch (Exception e) { log.log(Level.SEVERE, "Error parsing Caddisfly resource: " + e.getMessage(), e); } return result; }</code><technical_language>ObjectMapper is thread safe, member of a class static instance</technical_language>

Target:
public List<CaddisflyResource> listResources() { List<CaddisflyResource> result = new ArrayList<CaddisflyResource>(); try { InputStream stream = getClass().getClassLoader() .getResourceAsStream( "resources/caddisfly/caddisfly-tests.json"); String jsonTxt = IOUtils.toString(stream); JsonNode rootNode = mapper.readValue(jsonTxt, JsonNode.class); ArrayNode testsNode = (ArrayNode) rootNode.get("tests"); for (int i = 0; i < testsNode.size(); i++) { CaddisflyResource cr = JsonToCaddisflyResource(testsNode.get(i)); result.add(cr); } } catch (Exception e) { log.log(Level.SEVERE, "Error parsing Caddisfly resource: " + e.getMessage(), e); } return result; }
Source:
<code>public Pair<Boolean, String> restoreVMToDifferentLocation(String restorePointId, String hostIp, String dataStoreUuid) { <START> final String restoreLocation = "CS-RSTR-" + UUID.randomUUID().toString(); <END> final String datastoreId = dataStoreUuid.replace("-",""); final List<String> cmds = Arrays.asList( "$points = Get-VBRRestorePoint", String.format("foreach($point in $points) { if ($point.Id -eq '%s') { break; } }",restorePointId), String.format("$server = Get-VBRServer -Name \"%s\"", hostIp), String.format("$ds = Find-VBRViDatastore -Server:$server -Name \"%s\"", datastoreId), String.format("Start-VBRRestoreVM -RestorePoint:$point -Server:$server -Datastore:$ds -VMName \"%s\"", restoreLocation) ); Pair<Boolean, String> result = executePowerShellCommands(cmds); if (result == null || !result.first()) { throw new CloudRuntimeException("Failed to restore VM to location " + restoreLocation); } return new Pair<>(result.first(), restoreLocation); }</code><technical_language>"CS-RSTR" a final variable</technical_language>

Target:
public Pair<Boolean, String> restoreVMToDifferentLocation(String restorePointId, String hostIp, String dataStoreUuid) { final String restoreLocation = RESTORE_VM_SUFFIX + UUID.randomUUID().toString(); final String datastoreId = dataStoreUuid.replace("-",""); final List<String> cmds = Arrays.asList( "$points = Get-VBRRestorePoint", String.format("foreach($point in $points) { if ($point.Id -eq '%s') { break; } }", restorePointId), String.format("$server = Get-VBRServer -Name \"%s\"", hostIp), String.format("$ds = Find-VBRViDatastore -Server:$server -Name \"%s\"", datastoreId), String.format("$job = Start-VBRRestoreVM -RestorePoint:$point -Server:$server -Datastore:$ds -VMName \"%s\" -RunAsync", restoreLocation), "while (-not (Get-VBRRestoreSession -Id $job.Id).IsCompleted) { Start-Sleep -Seconds 10 }" ); Pair<Boolean, String> result = executePowerShellCommands(cmds); if (result == null || !result.first()) { throw new CloudRuntimeException("Failed to restore VM to location " + restoreLocation); } return new Pair<>(result.first(), restoreLocation); }
Source:
<code>public QueryResponse getBrowsableStudies(@RequestParam("species") String species) <START> throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { <END> StudyDBAdaptor studyMongoDbAdaptor = DBAdaptorConnector.getStudyDBAdaptor(species); return setQueryResponse(studyMongoDbAdaptor.listStudies()); }</code><technical_language>UnknownHostException necessary</technical_language>

Target:
public QueryResponse getBrowsableStudies(@RequestParam("species") String species) throws IllegalOpenCGACredentialsException, IOException { StudyDBAdaptor studyMongoDbAdaptor = DBAdaptorConnector.getStudyDBAdaptor(species); return setQueryResponse(studyMongoDbAdaptor.listStudies()); }
Source:
<code>private void toggleCompletedTasksList() { ViewPropertyAnimator viewPropertyAnimator = mChevron.animate() .rotation(mIsCompletedTaskListExpanded ? 0f : 180f) .setInterpolator(new LinearInterpolator()) .setDuration(Duration.SHORT.toMillis(mContext)); viewPropertyAnimator.setListener(new AnimatorListener() { <START> @Override public void onAnimationStart(Animator animation) { <END> itemView.setClickable(false); } @Override public void onAnimationEnd(Animator animation) { if (mIsCompletedTaskListExpanded) { mTasks.removeAll(mTaskCompleted); notifyItemRangeRemoved(getAdapterPosition() + 1, mTaskCompleted.size()); } else { mTasks.addAll(mTaskCompleted); notifyItemRangeInserted(getAdapterPosition() + 1, mTaskCompleted.size()); } mIsCompletedTaskListExpanded = !mIsCompletedTaskListExpanded; itemView.setClickable(true); } @Override public void onAnimationCancel(Animator animation) { itemView.setClickable(true); } @Override public void onAnimationRepeat(Animator animation) { } }); }</code><technical_language>suggestion @Override public void onAnimationStart(Animator animation) { move @Override annotation a separate line method declaration for code style consistency</technical_language>

Target:
private void toggleCompletedTasksList() { ViewPropertyAnimator viewPropertyAnimator = mChevron.animate() .rotation(mIsCompletedTaskListExpanded ? COLLAPSED_CHEVRON_ROTATION : EXPANDED_CHEVRON_ROTATION) .setInterpolator(new LinearInterpolator()) .setDuration(Duration.SHORT.toMillis(mContext)); viewPropertyAnimator.setListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { itemView.setClickable(false); } @Override public void onAnimationEnd(Animator animation) { if (mIsCompletedTaskListExpanded) { mTasks.removeAll(mTaskCompleted); notifyItemRangeRemoved(getAdapterPosition() + 1, mTaskCompleted.size()); } else { mTasks.addAll(mTaskCompleted); notifyItemRangeInserted(getAdapterPosition() + 1, mTaskCompleted.size()); } mIsCompletedTaskListExpanded = !mIsCompletedTaskListExpanded; itemView.setClickable(true); } @Override public void onAnimationCancel(Animator animation) { itemView.setClickable(true); } @Override public void onAnimationRepeat(Animator animation) { } }); }
Source:
<code>public long getFreshTimestamp() { <START> return checkAndUpdate(delegate::getFreshTimestamp, x -> x, x -> x); <END> }</code><technical_language>need functional approach, (imo) unnecessarily complicates checkAndUpdate. simple as: java public long getFreshTimestamp() { long delegateTimestamp = delegate.getFreshTimestamp(); checkAndUpdate(delegateTimestamp, delegateTimestamp); return delegateTimestamp; } public TimestampRange getFreshTimestamps(numRequested) { TimestampRange range = delegate.getFreshTimestamps(numRequested); checkAndUpdate(range.getLowerBound(), range.getUpperBound()); return range; } public StartAtlasDbTransactionResponse startAtlasDbTransaction(request) { StartAtlaqsDbTransactionResponse response = delegate.startAtlasDbTransaction(request); long timestamp = response.freshTimestamp(); checkAndUpdate(timestamp, timestamp); return response; }</technical_language>

Target:
public long getFreshTimestamp() { return checkAndUpdateLowerBound(delegate::getFreshTimestamp, x -> x, x -> x); }
Source:
<code>public void doLaunch(MessageInput input) throws MisfireException { final AWSPluginConfiguration awsConfig = clusterConfigService.getOrDefault(AWSPluginConfiguration.class, AWSPluginConfiguration.createDefault()); AWSAuthProvider authProvider = new AWSAuthProvider( awsConfig, configuration.getString(CK_ACCESS_KEY), configuration.getString(CK_SECRET_KEY), configuration.getString(CK_AWS_REGION), configuration.getString(CK_ASSUME_ROLE_ARN) ); this.reader = new KinesisConsumer( configuration.getString(CK_KINESIS_STREAM_NAME), Region.getRegion(Regions.fromName(configuration.getString(CK_AWS_REGION))), kinesisCallback(input), awsConfig, authProvider, nodeId, graylogConfiguration.getHttpProxyUri() == null ? null : HttpUrl.get(graylogConfiguration.getHttpProxyUri()), this, objectMapper, configuration.intIsSet(CK_KINESIS_MAX_THROTTLED_WAIT_MS) ? configuration.getInt(CK_KINESIS_MAX_THROTTLED_WAIT_MS) : null, configuration.getInt(CK_KINESIS_RECORD_BATCH_SIZE, DEFAULT_THROTTLED_WAIT_MS) ); LOG.info("Starting Kinesis reader thread for input [{}/{}]", input.getName(), input.getId()); <START> executor = getExecutorService(); <END> kinesisTaskFuture = executor.submit(this.reader); }</code><technical_language>I initialize executor field in constructor field final, no?</technical_language>

Target:
public void doLaunch(MessageInput input) throws MisfireException { final AWSPluginConfiguration awsConfig = clusterConfigService.getOrDefault(AWSPluginConfiguration.class, AWSPluginConfiguration.createDefault()); AWSAuthProvider authProvider = new AWSAuthProvider( awsConfig, configuration.getString(CK_ACCESS_KEY), configuration.getString(CK_SECRET_KEY), configuration.getString(CK_AWS_REGION), configuration.getString(CK_ASSUME_ROLE_ARN) ); this.reader = new KinesisConsumer( configuration.getString(CK_KINESIS_STREAM_NAME), Region.getRegion(Regions.fromName(configuration.getString(CK_AWS_REGION))), kinesisCallback(input), awsConfig, authProvider, nodeId, graylogConfiguration.getHttpProxyUri() == null ? null : HttpUrl.get(graylogConfiguration.getHttpProxyUri()), this, objectMapper, configuration.intIsSet(CK_KINESIS_MAX_THROTTLED_WAIT_MS) ? configuration.getInt(CK_KINESIS_MAX_THROTTLED_WAIT_MS) : null, configuration.getInt(CK_KINESIS_RECORD_BATCH_SIZE, DEFAULT_BATCH_SIZE) ); LOG.info("Starting Kinesis reader thread for input [{}/{}]", input.getName(), input.getId()); kinesisTaskFuture = executor.submit(this.reader); }
Source:
<code>byte[] wrapContent(byte[] message, String id, long timestamp, Schema schema, Map<String, String> externalMetadata) { try { GenericRecord genericRecord = bytesToRecord(message, schema); genericRecord.put(METADATA_MARKER, metadataMap(id, timestamp, externalMetadata)); return recordToBytes(genericRecord, schema); } catch (Exception e) { if (e instanceof AvroRuntimeException && e.getMessage().equals("Not a valid schema field: __metadata")) { throw new AvroInvalidMetadataException("Avro schema has invalid field __metadata", e); } <START> throw new WrappingException("Could not wrap avro message", e); <END> } }</code><technical_language>stick WrappingException extend message message? Like: throw new WrappingException(String.format("Could wrap avro message: %s", e.getMessage()), e); I original message AvroRuntimeException is fine, avoid equals checking, etc. of Avro's internal exception</technical_language>

Target:
byte[] wrapContent(byte[] message, String id, long timestamp, Schema schema, Map<String, String> externalMetadata) { try { GenericRecord genericRecord = bytesToRecord(message, schema); genericRecord.put(METADATA_MARKER, metadataMap(id, timestamp, externalMetadata)); return recordToBytes(genericRecord, schema); } catch (Exception e) { if (e instanceof AvroRuntimeException && e.getMessage().equals("Not a valid schema field: __metadata")) { throw new AvroInvalidMetadataException("Schema does not contain mandatory __metadata field for Hermes internal metadata. Please fix topic schema.", e); } throw new WrappingException("Could not wrap avro message", e); } }
Source:
<code>public Optional<ClassOrderer> getTestClassOrderer() { <START> ClassOrderingStrategy classOrderingStrategy = classOrderingStrategyConverter.get(configurationParameters, CLASS_ORDERING_STRATEGY_PROPERTY_NAME, ClassOrderingStrategy.DEFAULT); if (classOrderingStrategy != ClassOrderingStrategy.CUSTOM) { return Optional.empty(); } Optional<ClassOrderer> classOrderer = configurationParameters.get(CUSTOM_CLASS_ORDERER_PROPERTY_NAME).map( className -> ReflectionUtils.tryToLoadClass(className).andThenTry(ordererClass -> { Preconditions.condition(ClassOrderer.class.isAssignableFrom(ordererClass), CUSTOM_CLASS_ORDERER_PROPERTY_NAME + " does not implement " + ClassOrderer.class); return (ClassOrderer) ReflectionUtils.newInstance(ordererClass); }).getOrThrow( cause -> new JUnitException("Could not create configuration for strategy class: " + className, cause))); classOrderer.orElseThrow(() -> new JUnitException(CUSTOM_CLASS_ORDERER_PROPERTY_NAME + " must be set")); return classOrderer; <END> }</code><technical_language>reuse InstantiatingConfigurationParameterConverter if possible</technical_language>

Target:
public Optional<ClassOrderer> getTestClassOrderer() { return classOrdererConverter.get(configurationParameters, DEFAULT_TEST_CLASS_ORDER_PROPERTY_NAME); }
Source:
<code>public static String formatPlainTextFileName(String taskName, Instant firstLogTime, String agentId) { <START> return String.format(ENGLISH, <END> "%s@%08x%08x.%s", taskName, firstLogTime.getEpochSecond(), firstLogTime.getNano(), agentId) + LOG_PLAIN_TEXT_FILE_SUFFIX; }</code><technical_language>This code is duplicated formatFileName(). extracting this String.format() a private method calling formatFileName() formatPlainTextFileName()</technical_language>

Target:
public static String formatPlainTextFileName(String taskName, Instant firstLogTime, String agentId) { return formatFileNameWithSuffix(taskName, firstLogTime, agentId, LOG_PLAIN_TEXT_FILE_SUFFIX); }
Source:
<code>public void addConfigurations_shouldAddConfigurationsWithValue() throws Exception { ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name")); <START> AuthorizationMetadataStore store = AuthorizationMetadataStore.newInstanceForTest(); <END> SecurityAuthConfig profile = new SecurityAuthConfig("id", "plugin_id", store); profile.addConfigurations(Arrays.asList(property)); assertThat(profile.size(), is(1)); assertThat(profile, contains(new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name")))); }</code><technical_language>mock store injecting instead of AuthorizationMetadataStore.newInstanceForTest()</technical_language>

Target:
public void addConfigurations_shouldAddConfigurationsWithValue() throws Exception { ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name")); AuthorizationMetadataStore store = mock(AuthorizationMetadataStore.class); SecurityAuthConfig profile = new SecurityAuthConfig("id", "plugin_id", store); profile.addConfigurations(Arrays.asList(property)); assertThat(profile.size(), is(1)); assertThat(profile, contains(new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name")))); }
Source:
<code>public void shouldGetChangeInfo() throws Exception { String url = String.format("/a/changes/%s/revisions/%s/files/", SOME_CHANGE_ID, SOME_REVISION_ID); stubFor(get(urlEqualTo(url)) <START> .willReturn(aResponse() <END> .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(IOUtils.toString(getClass().getResourceAsStream("/gerrit-changes.json"))))); List<ReviewFile> files = fixture.listFiles(); assertThat(files).hasSize(2); verify(getRequestedFor(urlMatching(url))); }</code><technical_language>Great test, withHeader Basic authorisation header in this stub, in Stash test</technical_language>

Target:
public void shouldGetChangeInfo() throws Exception { String url = String.format("/a/changes/%s/revisions/%s/files/", SOME_CHANGE_ID, SOME_REVISION_ID); stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(IOUtils.toString(getClass().getResourceAsStream("/gerrit-changes.json"))))); List<ReviewFile> files = fixture.listFiles(); assertThat(files).hasSize(2); }
Source:
<code>private void saveChainToTrustStore(List<? extends Certificate> chain) { if (chain != null && chain.size() > 0) { KeyStore ks = null; try { ks = ExternalTrustStoreInitializer.getTrustStore(); <START> } catch (RuntimeException e) { <END> handleException(e); } try { int firstCertificateIndex = chain.size() == 1 ? 0 : 1; for (int certIndex = firstCertificateIndex; certIndex < chain.size(); ++certIndex) { Certificate certificate = chain.get(certIndex); String alias = Guid.NewGuid().toString(); ks.setCertificateEntry(alias, certificate); } ExternalTrustStoreInitializer.setTrustStore(ks); setSucceeded(true); } catch (KeyStoreException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } } }</code><technical_language>I suggest catch (Throwable ) cover cases</technical_language>

Target:
private void saveChainToTrustStore(List<? extends Certificate> chain) { if (chain != null && chain.size() > 0) { KeyStore ks = null; try { ks = ExternalTrustStoreInitializer.getTrustStore(); } catch (Throwable e) { handleException(e); } try { int firstCertificateIndex = chain.size() == 1 ? 0 : 1; for (int certIndex = firstCertificateIndex; certIndex < chain.size(); ++certIndex) { Certificate certificate = chain.get(certIndex); String alias = Guid.NewGuid().toString(); ks.setCertificateEntry(alias, certificate); } ExternalTrustStoreInitializer.setTrustStore(ks); setSucceeded(true); } catch (KeyStoreException e) { handleException(e); } catch (Throwable e) { handleException(e); } } }
Source:
<code><START> public Response exportApiSubscriptionsLogsAsCSV( <END> @BeanParam SubscriptionParam subscriptionParam, @Valid @BeanParam Pageable pageable) { final PagedResult<SubscriptionEntity> subscriptions = getApiSubscriptions(subscriptionParam, pageable, null); return Response .ok(subscriptionService.exportAsCsv(subscriptions.getData(), subscriptions.getMetadata())) .header(HttpHeaders.CONTENT_DISPOSITION, format("attachment;filename=subscriptions-%s-%s.csv", api, System.currentTimeMillis())) .build(); }</code><technical_language>Ok for mediaType in @ApiResponse. I change media type in @Produces</technical_language>

Target:
public Response exportApiSubscriptionsLogsAsCSV( @BeanParam SubscriptionParam subscriptionParam, @Valid @BeanParam Pageable pageable) { final SubscriptionEntityPage subscriptions = getApiSubscriptions(subscriptionParam, pageable, null); return Response .ok(subscriptionService.exportAsCsv(subscriptions.getData(), subscriptions.getMetadata())) .header(HttpHeaders.CONTENT_DISPOSITION, format("attachment;filename=subscriptions-%s-%s.csv", api, System.currentTimeMillis())) .build(); }
Source:
<code>public NetworkBitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action, Downloader downloader) { super(picasso, dispatcher, cache, stats, action); this.downloader = downloader; this.retryCount = DEFAULT_RETRY_COUNT; if (!hasPermission(picasso.context, Manifest.permission.INTERNET)) { Picasso.HANDLER.post(new Runnable() { @Override public void run() { <START> throw new SecurityException("INTERNET permission is required."); <END> } }); } }</code><technical_language>IllegalStateException</technical_language>

Target:
public NetworkBitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action, Downloader downloader) { super(picasso, dispatcher, cache, stats, action); this.downloader = downloader; this.retryCount = DEFAULT_RETRY_COUNT; if (!hasPermission(picasso.context, Manifest.permission.INTERNET)) { Picasso.HANDLER.post(new Runnable() { @Override public void run() { throw new IllegalStateException("INTERNET permission is required."); } }); } }
Source:
<code>private String location(ImportTableDesc tblDesc, Database parentDb) throws MetaException, SemanticException { if (tblDesc.tableType().equals(TableType.EXTERNAL_TABLE)) { <START> return context.warehouse.getDnsPath(tblDesc.getTableLocationPath()).toString(); <END> } else if (!tableContext.waitOnPrecursor()) { return context.warehouse.getDefaultTablePath( parentDb, tblDesc.getTableName(), tblDesc.isExternal()).toString(); } else { Path tablePath = context.warehouse.getDefaultTablePath( tblDesc.getDatabaseName(), tblDesc.getTableName(), tblDesc.isExternal()); return context.warehouse.getDnsPath(tablePath).toString(); } }</code><technical_language>in 3.0, external tables created warehouse directory. context.warehouse.getDefaultTablePath .. takes if table is external a parameter</technical_language>

Target:
private String location(ImportTableDesc tblDesc, Database parentDb) throws MetaException, SemanticException { if (tblDesc.isExternal()) { return context.warehouse.getDnsPath(tblDesc.getSourceTableLocationPath()).toString(); } else if (!tableContext.waitOnPrecursor()) { return context.warehouse.getDefaultTablePath( parentDb, tblDesc.getTableName(), tblDesc.isExternal()).toString(); } else { Path tablePath = context.warehouse.getDefaultTablePath( tblDesc.getDatabaseName(), tblDesc.getTableName(), tblDesc.isExternal()); return context.warehouse.getDnsPath(tablePath).toString(); } }
Source:
<code>public void close() throws WrongStateException, SystemException { if (confirmationHandler != null) { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(applicationClassloader); CompensationContext.setTxContextToExtend(currentTX); ConfirmationHandler handler = instantiate(confirmationHandler); handler.confirm(); Thread.currentThread().setContextClassLoader(origClassLoader); } <START> CompensationContextLifetimeManager.getInstance().participantDestroyed(currentTX); <END> }</code><technical_language>lifecycle methods throw exceptions. I do fully understand semantics of exceptions need put participantDestroyed calls a finally block</technical_language>

Target:
public void close() throws WrongStateException, SystemException { if (confirmationHandler != null) { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(applicationClassloader); CompensationContext.setTxContextToExtend(currentTX); ConfirmationHandler handler = instantiate(confirmationHandler); handler.confirm(); Thread.currentThread().setContextClassLoader(origClassLoader); } decrementParticipantsCounter(); }
Source:
<code>public void setup() { nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests") .defaultCache(new CacheConfiguration("default", 100))); addNativeCache(CACHE_NAME); cacheManager = new EhCacheCacheManager(nativeCacheManager); cacheManager.afterPropertiesSet(); <START> transactionalCacheManager = new EhCacheCacheManager(true, nativeCacheManager); <END> transactionalCacheManager.afterPropertiesSet(); }</code><technical_language>compile anymore</technical_language>

Target:
public void setup() { nativeCacheManager = new CacheManager(new Configuration().name("EhCacheCacheManagerTests") .defaultCache(new CacheConfiguration("default", 100))); addNativeCache(CACHE_NAME); cacheManager = new EhCacheCacheManager(nativeCacheManager); cacheManager.setTransactionAware(false); cacheManager.afterPropertiesSet(); transactionalCacheManager = new EhCacheCacheManager(nativeCacheManager); transactionalCacheManager.setTransactionAware(true); transactionalCacheManager.afterPropertiesSet(); }
Source:
<code>public List<Account> getNewAccounts(long updatedSince) throws SQLException { long startTimeMs = System.currentTimeMillis(); Timestamp sinceTime = new Timestamp(updatedSince); try { PreparedStatement getSinceStatement = dataAccessor.getPreparedStatement(getAccountsSinceSql, false); getSinceStatement.setTimestamp(1, sinceTime); <START> ResultSet rs = getSinceStatement.executeQuery(); <END> List<Account> accounts = convertAccountsResultSet(rs); dataAccessor.onSuccess(Read, System.currentTimeMillis() - startTimeMs); return accounts; } catch (SQLException e) { dataAccessor.onException(e, Read); throw e; } }</code><technical_language>If result set is created in a try-with-resources block, needs closed in a finally block</technical_language>

Target:
public List<Account> getNewAccounts(long updatedSince) throws SQLException { long startTimeMs = System.currentTimeMillis(); Timestamp sinceTime = new Timestamp(updatedSince); ResultSet rs = null; try { PreparedStatement getSinceStatement = dataAccessor.getPreparedStatement(getAccountsSinceSql, false); getSinceStatement.setTimestamp(1, sinceTime); rs = getSinceStatement.executeQuery(); List<Account> accounts = convertAccountsResultSet(rs); dataAccessor.onSuccess(Read, System.currentTimeMillis() - startTimeMs); return accounts; } catch (SQLException e) { dataAccessor.onException(e, Read); throw e; } finally { closeQuietly(rs); } }
Source:
<code>public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new <START> ArrayList<CommentLinkInfo>(commentLinks); <END> operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo clp : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = clp.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }</code><technical_language><></technical_language>

Target:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo cli : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = cli.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }