auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain nextFilter) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (!request.isSecure() || authenticators.isEmpty()) { nextFilter.doFilter(request, response); return; } List<String> messages = new ArrayList<>(); <START> List<String> headerValues = new ArrayList<>(); <END> for (Authenticator authenticator : authenticators) { Principal principal; try { principal = authenticator.authenticate(request); } catch (AuthenticationException e) { if (e.getMessage() != null) { messages.add(e.getMessage()); } e.getHeaderValue().ifPresent(headerValues::add); continue; } nextFilter.doFilter(withPrincipal(request, principal), response); return; } skipRequestBody(request); for (String value : headerValues) { response.setHeader(WWW_AUTHENTICATE, value); } if (messages.isEmpty()) { messages.add("Unauthorized"); } response.sendError(SC_UNAUTHORIZED, Joiner.on(" | ").join(messages)); }</code><technical_language>Name this authenticateHeaders</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain nextFilter) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (!request.isSecure() || authenticators.isEmpty()) { nextFilter.doFilter(request, response); return; } Set<String> messages = new LinkedHashSet<>(); Set<String> authenticateHeaders = new LinkedHashSet<>(); for (Authenticator authenticator : authenticators) { Principal principal; try { principal = authenticator.authenticate(request); } catch (AuthenticationException e) { if (e.getMessage() != null) { messages.add(e.getMessage()); } e.getAuthenticateHeader().ifPresent(authenticateHeaders::add); continue; } nextFilter.doFilter(withPrincipal(request, principal), response); return; } skipRequestBody(request); for (String value : authenticateHeaders) { response.setHeader(WWW_AUTHENTICATE, value); } if (messages.isEmpty()) { messages.add("Unauthorized"); } response.sendError(SC_UNAUTHORIZED, Joiner.on(" | ").join(messages)); }
Source:
<code>public static void readFileMetaData(InputStream from, final FileMetaDataConsumer consumer, boolean skipRowGroups) throws IOException { <START> readFileMetaData(from, consumer, skipRowGroups, (BlockCipher.Decryptor) null, (byte[]) null); <END> }</code><technical_language>I omit casting add value</technical_language>

Target:
public static void readFileMetaData(InputStream from, final FileMetaDataConsumer consumer, boolean skipRowGroups) throws IOException { readFileMetaData(from, consumer, skipRowGroups, null, null); }
Source:
<code>private static Pair<CommandType, String> determineCommandTypeAndAttribute(RuleContext ruleContext) { AttributeMap attributeMap = ruleContext.attributes(); if (OS.getCurrent() == OS.WINDOWS) { <START> if (attributeMap.isAttributeValueExplicitlySpecified("cmd_ps")) { <END> return Pair.of(CommandType.POWERSHELL, "cmd_ps"); } if (attributeMap.isAttributeValueExplicitlySpecified("cmd_bat")) { return Pair.of(CommandType.BATCH, "cmd_bat"); } } if (attributeMap.isAttributeValueExplicitlySpecified("cmd_bash")) { return Pair.of(CommandType.BASH, "cmd_bash"); } if (attributeMap.isAttributeValueExplicitlySpecified("cmd")) { return Pair.of(CommandType.BASH, "cmd"); } ruleContext.attributeError( "cmd", "missing value for `cmd` attribute in genrule, you can also set `cmd_ps` or `cmd_bat` on Windows and `cmd_bash` on other platforms."); return null; }</code><technical_language>need check if explicitly defined. enough check if empty not. empty command possibly sense (it generate outputs, action fail anyway), ignore cmd_ps if user deliberately sets "". for other attributes</technical_language>

Target:
private static Pair<CommandType, String> determineCommandTypeAndAttribute(RuleContext ruleContext) { AttributeMap attributeMap = ruleContext.attributes(); if (OS.getCurrent() == OS.WINDOWS) { if (attributeMap.isAttributeValueExplicitlySpecified("cmd_ps")) { return Pair.of(CommandType.WINDOWS_POWERSHELL, "cmd_ps"); } if (attributeMap.isAttributeValueExplicitlySpecified("cmd_bat")) { return Pair.of(CommandType.WINDOWS_BATCH, "cmd_bat"); } } if (attributeMap.isAttributeValueExplicitlySpecified("cmd_bash")) { return Pair.of(CommandType.BASH, "cmd_bash"); } if (attributeMap.isAttributeValueExplicitlySpecified("cmd")) { return Pair.of(CommandType.BASH, "cmd"); } ruleContext.attributeError( "cmd", "missing value for `cmd` attribute in genrule, you can also set `cmd_ps` or `cmd_bat` on Windows and `cmd_bash` on other platforms."); return null; }
Source:
<code>public final <T> Observable<List<T>> mapToList(@NonNull final Func1<Cursor, T> mapper) { return lift(new Operator<List<T>, Query>() { @Override public Subscriber<? super Query> call(final Subscriber<? super List<T>> subscriber) { return new Subscriber<Query>(subscriber) { @Override public void onNext(Query query) { Cursor cursor = query.run(); List<T> items = new ArrayList<>(cursor.getCount()); try { while (cursor.moveToNext() && !subscriber.isUnsubscribed()) { items.add(mapper.call(cursor)); } } finally { cursor.close(); } <START> subscriber.onNext(items); <END> } @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } }; } }); }</code><technical_language>wrap if (!subscriber.isUnsubscribed())</technical_language>

Target:
public final <T> Observable<List<T>> mapToList(@NonNull final Func1<Cursor, T> mapper) { return lift(new Operator<List<T>, Query>() { @Override public Subscriber<? super Query> call(final Subscriber<? super List<T>> subscriber) { return new Subscriber<Query>(subscriber) { @Override public void onNext(Query query) { Cursor cursor = query.run(); List<T> items = new ArrayList<>(cursor.getCount()); try { while (cursor.moveToNext() && !subscriber.isUnsubscribed()) { items.add(mapper.call(cursor)); } } finally { cursor.close(); } if (!subscriber.isUnsubscribed()) { subscriber.onNext(items); } } @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } }; } }); }
Source:
<code>public NettyServerConnection createConnection(final ChannelHandlerContext ctx, String protocol, boolean httpEnabled) throws Exception { if (connectionsAllowed == -1 || connections.size() < connectionsAllowed) { super.channelActive(ctx); Listener connectionListener = new Listener(); NettyServerConnection nc = new NettyServerConnection(configuration, ctx.channel(), connectionListener, !httpEnabled && batchDelay > 0, directDeliver); connectionListener.connectionCreated(NettyAcceptor.this, nc, protocolHandler.getProtocol(protocol)); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (sslHandler != null) { sslHandler.handshakeFuture().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Channel>>() { @Override public void operationComplete(final io.netty.util.concurrent.Future<Channel> future) throws Exception { if (future.isSuccess()) { active = true; <START> ctx.channel().pipeline().remove("readTimeoutHandler"); <END> } else { future.getNow().close(); } } }); } else { active = true; } return nc; } else { ActiveMQServerLogger.LOGGER.connectionLimitReached(connectionsAllowed, ctx.channel().remoteAddress().toString()); ctx.channel().close(); return null; } }</code><technical_language>This is valid for SSL connections. "readTimeoutHandler" removed for non-SSL connections well</technical_language>

Target:
public NettyServerConnection createConnection(final ChannelHandlerContext ctx, String protocol, boolean httpEnabled) throws Exception { if (connectionsAllowed == -1 || connections.size() < connectionsAllowed) { super.channelActive(ctx); Listener connectionListener = new Listener(); NettyServerConnection nc = new NettyServerConnection(configuration, ctx.channel(), connectionListener, !httpEnabled && batchDelay > 0, directDeliver); connectionListener.connectionCreated(NettyAcceptor.this, nc, protocolHandler.getProtocol(protocol)); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (sslHandler != null) { sslHandler.handshakeFuture().addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Channel>>() { @Override public void operationComplete(final io.netty.util.concurrent.Future<Channel> future) throws Exception { if (future.isSuccess()) { active = true; } else { future.getNow().close(); } } }); } else { active = true; } return nc; } else { ActiveMQServerLogger.LOGGER.connectionLimitReached(connectionsAllowed, ctx.channel().remoteAddress().toString()); ctx.channel().close(); return null; } }
Source:
<code><START> public void equalTo_UUID() { <END> populateTestRealm(realm, 10); RealmResults<AllTypes> resultList = realm.where(AllTypes.class).sort(AllTypes.FIELD_UUID, Sort.ASCENDING).findAll(); for (int i = 0; i < 10; i++) { assertEquals(UUID.fromString(uuid), resultList.get(i).getColumnUUID()); } }</code><technical_language>tests in UUID tests, remove this one? test equalTo, sort</technical_language>

Target:
public void equalTo_UUID() { populateTestRealm(realm, 10); for (int i = 0; i < 10; i++) { RealmResults<AllTypes> resultList = realm .where(AllTypes.class) .equalTo(AllTypes.FIELD_UUID, UUID.fromString(TestHelper.generateUUIDString(i))) .sort(AllTypes.FIELD_UUID, Sort.ASCENDING) .findAll(); assertEquals(1, resultList.size()); assertEquals(UUID.fromString(TestHelper.generateUUIDString(i)), resultList.get(0).getColumnUUID()); } }
Source:
<code>public void bind(String portalName, String statementName, List<Object> params, @Nullable FormatCodes.FormatCode[] resultFormatCodes) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("method=bind portalName={} statementName={} params={}", portalName, statementName, params); } PreparedStmt preparedStmt; try { preparedStmt = getSafeStmt(statementName); } catch (Throwable t) { jobsLogs.logPreExecutionFailure(UUID.randomUUID(), null, SQLExceptions.messageOf(t), sessionContext.user()); throw t; } AnalyzedStatement analyzedStatement; <START> if (preparedStmt.analyzedStatement() == null) { <END> try { analyzedStatement = analyzer.analyze( preparedStmt.parsedStatement(), sessionContext, preparedStmt.paramTypes()); } catch (Throwable t) { jobsLogs.logPreExecutionFailure( UUID.randomUUID(), preparedStmt.rawStatement(), SQLExceptions.messageOf(t), sessionContext.user()); throw t; } } else { analyzedStatement = preparedStmt.analyzedStatement(); } Portal portal = new Portal( portalName, preparedStmt, params, analyzedStatement, resultFormatCodes); Portal oldPortal = portals.put(portalName, portal); if (oldPortal != null) { oldPortal.closeActiveConsumer(); } }</code><technical_language>Do sense eagerly analyze statement parse already? allow remove special case in describe. get rid of analyzedStatement setter PreparedStmt</technical_language>

Target:
public void bind(String portalName, String statementName, List<Object> params, @Nullable FormatCodes.FormatCode[] resultFormatCodes) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("method=bind portalName={} statementName={} params={}", portalName, statementName, params); } PreparedStmt preparedStmt; try { preparedStmt = getSafeStmt(statementName); } catch (Throwable t) { jobsLogs.logPreExecutionFailure(UUID.randomUUID(), null, SQLExceptions.messageOf(t), sessionContext.user()); throw t; } Portal portal = new Portal( portalName, preparedStmt, params, preparedStmt.analyzedStatement(), resultFormatCodes); Portal oldPortal = portals.put(portalName, portal); if (oldPortal != null) { oldPortal.closeActiveConsumer(); } }
Source:
<code>public void onAttach(Activity activity) { super.onAttach(activity); <START> com.baidu.mapapi.SDKInitializer.initialize(getActivity().getApplicationContext()); <END> mDpApp = (DroidPlannerApp) activity.getApplication(); }</code><technical_language>@droneboost activity parameter instead of calling getActivity() method</technical_language>

Target:
public void onAttach(Activity activity) { super.onAttach(activity); com.baidu.mapapi.SDKInitializer.initialize(activity.getApplicationContext()); mDpApp = (DroidPlannerApp) activity.getApplication(); }
Source:
<code>protected String[] customCommandLineValidation() { List<String> errors = new ArrayList<>(); if (INPUT.equals(OUTPUT)) errors.add("INPUT file and OUTPUT file must differ!"); checkInputs(Arrays.asList(Filter.includeReadList, Filter.excludeReadList), READ_LIST_FILE, "READ_LIST_FILE").ifPresent(errors::add); checkInputs(Collections.singletonList(Filter.includePairedIntervals), INTERVAL_LIST, "INTERVAL_LIST").ifPresent(errors::add); checkInputs(Collections.singletonList(Filter.includeJavascript), JAVASCRIPT_FILE, "JAVASCRIPT_FILE").ifPresent(errors::add); <START> checkInputs(Arrays.asList(Filter.includeTagValues, Filter.excludeTagValues), TAG, "TAG").ifPresent(errors::add); <END> if (!errors.isEmpty()) return errors.toArray(new String[errors.size()]); return super.customCommandLineValidation(); }</code><technical_language>check for TAG_VALUE, right</technical_language>

Target:
protected String[] customCommandLineValidation() { List<String> errors = new ArrayList<>(); if (INPUT.equals(OUTPUT)) errors.add("INPUT file and OUTPUT file must differ!"); List<Filter> tagFilters = Arrays.asList(Filter.includeTagValues, Filter.excludeTagValues); checkInputs(Arrays.asList(Filter.includeReadList, Filter.excludeReadList), READ_LIST_FILE, "READ_LIST_FILE").ifPresent(errors::add); checkInputs(Collections.singletonList(Filter.includePairedIntervals), INTERVAL_LIST, "INTERVAL_LIST").ifPresent(errors::add); checkInputs(Collections.singletonList(Filter.includeJavascript), JAVASCRIPT_FILE, "JAVASCRIPT_FILE").ifPresent(errors::add); checkInputs(tagFilters, TAG, "TAG").ifPresent(errors::add); if (tagFilters.contains(FILTER) && TAG_VALUE.isEmpty()) { log.warn("Running FilterSamReads with a Tag Filter but no TAG_VALUE argument provided. This " + "will recreate the original input file i.e. not filter anything"); } if (!errors.isEmpty()) return errors.toArray(new String[errors.size()]); return super.customCommandLineValidation(); }
Source:
<code>public ActionResponseDto execute(final ClientConnection conn, final DlmsDevice device, final GetConfigurationRequestDataDto getConfigurationRequestDataDto) { String resultString = null; try { <START> resultString = this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null); <END> } catch (final ProtocolAdapterException e) { LOGGER.error("Error retrieving configuration objects for device: " + device.getDeviceIdentification(), e); return new ActionResponseDto(e, "Error retrieving configuration objects for device: " + device.getDeviceIdentification()); } return new GetConfigurationResponseDataDto(resultString); }</code><technical_language>better: return new GetConfigurationResponseDataDto(this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null));</technical_language>

Target:
public ActionResponseDto execute(final ClientConnection conn, final DlmsDevice device, final GetConfigurationRequestDataDto getConfigurationRequestDataDto) { try { return new GetConfigurationResponseDataDto(this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null)); } catch (final ProtocolAdapterException e) { LOGGER.error("Error retrieving configuration objects for device: " + device.getDeviceIdentification(), e); return new ActionResponseDto(e, "Error retrieving configuration objects for device: " + device.getDeviceIdentification()); } }
Source:
<code>public Result setSystemProperty( @Option(value = "named", description = "The property name", required = true) final String propertyName, @Option(value = "value", description = "The property value", required = true) final String propertyValue) { <START> System.setProperty(propertyName, propertyValue); <END> return Results.success("System property '" + propertyName + "' successfully set."); }</code><technical_language>Change return type String impl: return System.setProperty(propertyName,propertyValue);</technical_language>

Target:
public String setSystemProperty( @Option(value = "named", description = "The property name", required = true) final String propertyName, @Option(value = "value", description = "The property value", required = true) final String propertyValue) { return System.setProperty(propertyName, propertyValue); }
Source:
<code>public void testShouldFetchTeam() throws Exception { GHOrganization organization = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHTeam teamByName = organization.getTeams().get("Core Developers"); GHTeam teamById = organization.getTeam(teamByName.getId()); <START> assertNotNull(teamById); <END> assertEquals(teamByName.getId(), teamById.getId()); assertEquals(teamByName.getDescription(), teamById.getDescription()); }</code><technical_language>Sorry, is deprecated remove test for it. ensure continues work is removed</technical_language>

Target:
public void testShouldFetchTeam() throws Exception { GHOrganization organization = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHTeam teamByName = organization.getTeams().get("Core Developers"); GHTeam teamById = gitHub.getTeam(teamByName.getId()); assertNotNull(teamById); assertEquals(teamByName.getId(), teamById.getId()); assertEquals(teamByName.getDescription(), teamById.getDescription()); }
Source:
<code>public String toString() { <START> String dataHost = options.getDataHost(); <END> String tableAdminHost = options.getTableAdminHost(); return MoreObjects.toStringHelper(AbstractBigtableConnection.class) .add("zone", options.getZone()) .add("project", options.getProjectId()) .add("cluster", options.getCluster()) .add("dataHost", dataHost) .add("tableAdminHost", tableAdminHost) .toString(); }</code><technical_language>need create local variables for this</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(AbstractBigtableConnection.class) .add("zone", options.getZone()) .add("project", options.getProjectId()) .add("cluster", options.getCluster()) .add("dataHost", options.getDataHost()) .add("tableAdminHost", options.getTableAdminHost()) .toString(); }
Source:
<code>public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) { return null; } Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Map<Object, Object> data = new HashMap<>(); setAgentVolumes(instance, labels, data); setName(instance, labels, data); setDns(instance, labels, data); setLogConfig(instance, data); setSecrets(instance, data); <START> setSystemLabel(instance, data); <END> if (!data.isEmpty()) { return new HandlerResult(data); } return null; }</code><technical_language>pass in existing labels</technical_language>

Target:
public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) { return null; } Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Map<Object, Object> data = new HashMap<>(); setAgentVolumes(instance, labels, data); setName(instance, labels, data); setDns(instance, labels, data); setLogConfig(instance, data); setSecrets(instance, data); setSystemLabel(instance, labels); if (!data.isEmpty()) { return new HandlerResult(data); } return null; }
Source:
<code>public Optional<TimelineAlgorithm> get(final AlgorithmType alg) { <START> final TimelineAlgorithm algorithm = algorithmMap.get(alg); <END> if (algorithm == null) { return Optional.absent(); } return Optional.of(algorithm); }</code><technical_language>a algorithmMap.containsKey(alg); instead</technical_language>

Target:
public Optional<TimelineAlgorithm> get(final AlgorithmType alg) { return Optional.fromNullable(algorithmMap.get(alg)); }
Source:
<code>TestFunctionTranslator(FunctionManager functionManager, FunctionTranslator<String> functionTranslator) { <START> this.functionTranslator = functionTranslator; <END> this.functionManager = functionManager; }</code><technical_language>Follow order of argument definition. add requireNonNull is needed (@Inject) null (usually annotate @Nullable)</technical_language>

Target:
TestFunctionTranslator(FunctionManager functionManager, FunctionTranslator<String> functionTranslator) { this.functionTranslator = requireNonNull(functionTranslator); this.functionManager = requireNonNull(functionManager); }
Source:
<code>private void onTopologyChanged(ClientChannel ch) { if (affinityCtx.updateLastTopologyVersion(ch.serverTopologyVersion(), ch.serverNodeId())) <START> channelsInit(true); <END> }</code><technical_language>If partition awareness is disabled a new node is joined fine work current node failure (we need find new nodes disconnected current)</technical_language>

Target:
private void onTopologyChanged(ClientChannel ch) { if (affinityCtx.updateLastTopologyVersion(ch.serverTopologyVersion(), ch.serverNodeId())) { if (scheduledChannelsReinit.compareAndSet(false, true)) { if (partitionAwarenessEnabled) asyncRunner.submit(this::channelsInit); } } }
Source:
<code><START> protected DocumentBlobHolder getDocumentBlob(String path, String srcMT) throws IOException { <END> DocumentModel documentModel = session.createDocumentModel("/", "src", "File"); documentModel = session.createDocument(documentModel); session.save(); DocumentBlobHolder documentBlobHolder = new DocumentBlobHolder(documentModel, "file:content"); Blob blob = buildBlob(path, srcMT); documentBlobHolder.setBlob(blob); return documentBlobHolder; }</code><technical_language>needed changes</technical_language>

Target:
protected DocumentBlobHolder getDocumentBlob(String path, String srcMT) throws IOException { Blob blob = buildBlob(path, srcMT); return createDocumentBlob(blob); }
Source:
<code>private SpanBuilder startSpanWithExplicitParent(String spanName, Context context) { Optional<Object> optionalSpanKey = context.getData(OPENCENSUS_SPAN_KEY); Optional<Object> optionalSpanNameKey = context.getData(OPENCENSUS_SPAN_NAME_KEY); Span parentSpan = null; String spanNameKey = null; if (!optionalSpanNameKey.isPresent()) { spanNameKey = spanName; } else if (optionalSpanKey.isPresent() && optionalSpanNameKey.get() instanceof String) { spanNameKey = (String) optionalSpanNameKey.get(); } else { <START> logger.warning(String.format(Locale.US, <END> "Span name type is not of type String, but type: %s. Failed to add span links.", optionalSpanNameKey.get() != null ? optionalSpanNameKey.get().getClass() : "null")); } if (optionalSpanKey.get() instanceof Span) { parentSpan = (Span) context.getData(OPENCENSUS_SPAN_KEY).orElse(TRACER.getCurrentSpan()); } else { logger.warning(String.format(Locale.US, "Parent span type is not of type Span, but type: %s. Failed to add span links.", optionalSpanKey.get() != null ? optionalSpanKey.get().getClass() : "null")); } SpanBuilder spanBuilder = TRACER.spanBuilderWithExplicitParent(spanNameKey, parentSpan); return spanBuilder; }</code><technical_language>logger supports "format string" var args. need format it</technical_language>

Target:
private SpanBuilder startSpanWithExplicitParent(String spanName, Context context) { Optional<Object> optionalSpanKey = context.getData(OPENCENSUS_SPAN_KEY); Optional<Object> optionalSpanNameKey = context.getData(OPENCENSUS_SPAN_NAME_KEY); Span parentSpan = null; String spanNameKey = null; if (!optionalSpanNameKey.isPresent()) { spanNameKey = spanName; } else if (optionalSpanKey.isPresent() && optionalSpanNameKey.get() instanceof String) { spanNameKey = (String) optionalSpanNameKey.get(); } else { logger.warning("Span name type is not of type String, but type: {}. Failed to add span links.", optionalSpanNameKey.get() != null ? optionalSpanNameKey.get().getClass() : "null"); } if (optionalSpanKey.get() instanceof Span) { parentSpan = (Span) context.getData(OPENCENSUS_SPAN_KEY).orElse(TRACER.getCurrentSpan()); } else { logger.warning("Parent span type is not of type Span, but type: {}. Failed to add span links.", optionalSpanKey.get() != null ? optionalSpanKey.get().getClass() : "null"); } SpanBuilder spanBuilder = TRACER.spanBuilderWithExplicitParent(spanNameKey, parentSpan); return spanBuilder; }
Source:
<code>public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) { try { Context context = getApplicationContext(); ShortcutInfoCompatSaver shortcutSaver = ShortcutInfoCompatSaver.getInstance(context); List<ShortcutInfoCompat> shortcuts = shortcutSaver.getShortcuts(); List<ShareTargetCompat> targets = ShareTargetXmlParser.getShareTargets(context); <START> ArrayList<ChooserTarget> chooserTargets = new ArrayList<>(); for (ShareTargetCompat target : targets) { boolean matchedDataType = false; for (ShareTargetCompat.TargetData data : target.mTargetData) { if (matchedFilter.hasDataType(data.mMimeType)) { matchedDataType = true; break; } } <END> if (!matchedDataType) { continue; } for (ShortcutInfoCompat shortcut : shortcuts) { if (!shortcut.getCategories().containsAll(Arrays.asList(target.mCategories))) { continue; } IconCompat icon = shortcutSaver.getShortcutIcon(shortcut.getId()); Bundle extras = new Bundle(); extras.putCharSequence("EXTRA_SHORTCUT_ID", shortcut.getId()); chooserTargets.add(new ChooserTarget( shortcut.getShortLabel(), icon != null ? icon.toIcon() : null, 0.5f, new ComponentName(context.getPackageName(), target.mTargetClass), extras)); } } return chooserTargets; } catch (Exception e) { throw new RuntimeException("Failed to get chooser targets", e); } }</code><technical_language>do a loop targets. If targets match, is need call shortcutSaver.getShortcuts();</technical_language>

Target:
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) { Context context = getApplicationContext(); ArrayList<ChooserTarget> chooserTargets = new ArrayList<>(); List<ShareTargetCompat> targets = ShareTargetXmlParser.getShareTargets(context); List<ShareTargetCompat> matchedTargets = new ArrayList<>(); for (ShareTargetCompat target : targets) { for (ShareTargetCompat.TargetData data : target.mTargetData) { if (matchedFilter.hasDataType(data.mMimeType)) { matchedTargets.add(target); break; } } } if (matchedTargets.isEmpty()) { return chooserTargets; } ShortcutInfoCompatSaver shortcutSaver = ShortcutInfoCompatSaver.getInstance(context); List<ShortcutInfoCompat> shortcuts; try { shortcuts = shortcutSaver.getShortcuts(); } catch (Exception e) { Log.e(TAG, "Failed to retrieve shortcuts: ", e); return chooserTargets; } if (shortcuts == null || shortcuts.isEmpty()) { return chooserTargets; } for (ShortcutInfoCompat shortcut : shortcuts) { ShareTargetCompat target = null; for (ShareTargetCompat item : matchedTargets) { if (shortcut.getCategories().containsAll(Arrays.asList(item.mCategories))) { target = item; break; } } if (target == null) { continue; } IconCompat icon; try { icon = shortcutSaver.getShortcutIcon(shortcut.getId()); } catch (Exception e) { Log.e(TAG, "Failed to retrieve shortcut icon: ", e); continue; } Bundle extras = new Bundle(); extras.putCharSequence(ShortcutManagerCompat.EXTRA_SHORTCUT_ID, shortcut.getId()); chooserTargets.add(new ChooserTarget( shortcut.getShortLabel(), icon != null ? icon.toIcon() : null, 0.5f, new ComponentName(context.getPackageName(), target.mTargetClass), extras)); } return chooserTargets; }
Source:
<code>public Object get(int index) { if (row.isNull(index)) { return null; } DataType type = columns.getType(index); if (type.isCollection()) { return getCollection(index, type); } <START> if (ObjectUtils.nullSafeEquals(type.getName(), Name.TUPLE)) { <END> return row.getTupleValue(index); } if (ObjectUtils.nullSafeEquals(type.getName(), Name.UDT)) { return row.getUDTValue(index); } return row.getObject(index); }</code><technical_language>simplified to... if (Name.TUPLE.equals(type.getName()) { A properly coded equals method handles null case with... if (!(obj instanceof Type)) { return false; }</technical_language>

Target:
public Object get(int index) { if (row.isNull(index)) { return null; } DataType type = columns.getType(index); if (type.isCollection()) { return getCollection(index, type); } if (Name.TUPLE.equals(type.getName())) { return row.getTupleValue(index); } if (Name.UDT.equals(type.getName())) { return row.getUDTValue(index); } return row.getObject(index); }
Source:
<code>private static CommandExecutor toExecutor(EdgeOptions options) { Objects.requireNonNull(options, "No options to construct executor from"); EdgeDriverService.Builder<?, ?> builder = <START> StreamSupport.stream(ServiceLoader.load(DriverService.Builder.class).spliterator(), false) <END> .filter(b -> b instanceof EdgeDriverService.Builder) .map(b -> (EdgeDriverService.Builder) b) .filter(b -> b.isEdgeHTML() == !Boolean.getBoolean(DRIVER_USE_EDGE_CHROMIUM)) .findFirst().orElseThrow(WebDriverException::new); if (!Boolean.getBoolean(DRIVER_USE_EDGE_CHROMIUM)) return new DriverCommandExecutor(builder.build()); return new ChromeDriverCommandExecutor(builder.build()); }</code><technical_language>FirefoxDriver some lengths XPI-backed version moved a JAR classpath. If planning that, a simple if/else block work here. a ternary operator :)</technical_language>

Target:
private static CommandExecutor toExecutor(EdgeOptions options) { Objects.requireNonNull(options, "No options to construct executor from"); boolean isLegacy = System.getProperty(DRIVER_USE_EDGE_EDGEHTML) == null || Boolean.getBoolean(DRIVER_USE_EDGE_EDGEHTML); EdgeDriverService.Builder<?, ?> builder = StreamSupport.stream(ServiceLoader.load(DriverService.Builder.class).spliterator(), false) .filter(b -> b instanceof EdgeDriverService.Builder) .map(b -> (EdgeDriverService.Builder) b) .filter(b -> b.isLegacy() == isLegacy) .findFirst().orElseThrow(WebDriverException::new); if (isLegacy) return new DriverCommandExecutor(builder.build()); return new ChromiumDriverCommandExecutor(builder.build()); }
Source:
<code>public void verifyAllPinTypesIsCheck() { waitForElementByElement(allPinTypes); waitForElementByElement(enabledPinTypesCollection.get(InteractiveMapsContent.pinTypeIndex)); if(allPinTypes.getAttribute("class").contains("enabled")) { PageObjectLogging.log("verifyAllPointTypesIsCheck", "All pin types was checked", true); }else { <START> PageObjectLogging.log("verifyAllPointTypesIsCheck", "All pin types was unchecked", false); <END> } }</code><technical_language>If this condition is required for test pass, raise exception met. get fail in results</technical_language>

Target:
public void verifyAllPinTypesIsCheck() { try { waitForElementByElement(allPinTypes); waitForElementByElement(enabledPinTypesCollection.get(InteractiveMapsContent.pinTypeIndex)); if (allPinTypes.getAttribute("class").contains("enabled")) { PageObjectLogging.log("verifyAllPointTypesIsCheck", "All pin types were checked", true); } }catch (Exception e) { PageObjectLogging.log("verifyAllPointTypesIsCheck", e.toString(), false); } }
Source:
<code>public Router getRouter() throws InstantiationException { try { return new NonBlockingRouter(routerConfig, routerMetrics, networkClientFactory, notificationSystem, clusterMap, kms, cryptoService, cryptoJobHandler, time); } catch (IOException e) { <START> throw new InstantiationException("Error instantiating NonBlocking Router" + e.getMessage()); <END> } }</code><technical_language>I prefer throwing IllegalStateException other RuntimeException, InstantiationException pass in a exception. passing in e.getMessage() lose stack trace</technical_language>

Target:
public Router getRouter() { try { return new NonBlockingRouter(routerConfig, routerMetrics, networkClientFactory, notificationSystem, clusterMap, kms, cryptoService, cryptoJobHandler, time); } catch (IOException e) { throw new IllegalStateException("Error instantiating NonBlocking Router ", e); } }
Source:
<code>private void handleCtrlC(Key[] keys) { if (doKeysMatch(keys, Key.CONTROL, Key.C)) { <START> this.execute(newDefaultCallback("Error while trying to copy selected items. Message=")); <END> } }</code><technical_language>Minor thing, I " Message=" part of code in LOGGER.log(Level.SEVERE,errorMessage + error.toString());</technical_language>

Target:
private void handleCtrlC(Key[] keys) { if (doKeysMatch(keys, Key.CONTROL, Key.C)) { this.execute(newDefaultCallback("Error while trying to copy selected items.")); } }
Source:
<code>public void setJetpackSettings(long siteId, Map<String, Object> bodyData, Listener listener, ErrorListener errorListener) { String path = String.format(Locale.US, "jetpack-blogs/%d/rest-api/", siteId); JSONObject params = new JSONObject(); JSONObject body = new JSONObject(); try { for (String key : bodyData.keySet()) { body.putOpt(key, bodyData.get(key)); } params.put("path", "/jetpack/v4/settings/"); params.put("body", body.toString()); post(path, params, null, listener, errorListener); } catch (JSONException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>I I raised a similar issue in previous review well. I e.printStackTrace() is a good handle exceptions</technical_language>

Target:
public void setJetpackSettings(long siteId, Map<String, Object> bodyData, Listener listener, ErrorListener errorListener) { String path = String.format(Locale.US, "jetpack-blogs/%d/rest-api/", siteId); JSONObject params = new JSONObject(); JSONObject body = new JSONObject(); try { for (String key : bodyData.keySet()) { body.putOpt(key, bodyData.get(key)); } params.put("path", "/jetpack/v4/settings/"); params.put("body", body.toString()); post(path, params, null, listener, errorListener); } catch (JSONException e) { AppLog.e(AppLog.T.API, "Error updating Jetpack settings: " + e); if (errorListener != null) { errorListener.onErrorResponse( new VolleyError("Error: Attempted to update Jetpack settings with malformed body data", e)); } } }
Source:
<code><START> private ChronicleMapMessageRepository(File file, int entries, int averageMessageSize) { <END> logger.info("Creating backup storage in path: {}", file.getAbsolutePath()); try { map = ChronicleMapBuilder.of(String.class, ChronicleMapEntryValue.class) .constantKeySizeBySample(MessageIdGenerator.generate()) .averageValueSize(averageMessageSize) .entries(entries) .createPersistedTo(file); if (map == null) { logger.error("Backup file could not be read - check if it was not corrupted."); } } catch (IOException e) { logger.error("Failed to load backup storage file from path {}", file.getAbsoluteFile(), e); throw new ChronicleMapCreationException(e); } }</code><technical_language>I similar private constructors. Do need two</technical_language>

Target:
public ChronicleMapMessageRepository(File file, int entries, int averageMessageSize) { logger.info("Creating backup storage in path: {}", file.getAbsolutePath()); try { map = ChronicleMapBuilder.of(String.class, ChronicleMapEntryValue.class) .constantKeySizeBySample(MessageIdGenerator.generate()) .averageValueSize(averageMessageSize) .entries(entries) .createOrRecoverPersistedTo(file, SAME_BUILDER_CONFIG); } catch (IOException e) { logger.error("Failed to load backup storage file from path {}", file.getAbsoluteFile(), e); throw new ChronicleMapCreationException(e); } }
Source:
<code>private static String getCustomClassName(Class<? extends ObjCObject> type) { CustomClass customClassAnno = type.getAnnotation(CustomClass.class); String name = type.getName(); if (customClassAnno != null && customClassAnno.value().length() > 0) { name = customClassAnno.value(); } <START> name = CUSTOM_CLASS_NAME_PREFIX + name.replace('.', '_'); <END> return name; }</code><technical_language>This done if is @CustomClass annotation. If is name specifies is user collisions</technical_language>

Target:
private static String getCustomClassName(Class<? extends ObjCObject> type) { CustomClass customClassAnno = type.getAnnotation(CustomClass.class); String name = type.getName(); if (customClassAnno != null && customClassAnno.value().length() > 0) { name = customClassAnno.value(); } else { name = CUSTOM_CLASS_NAME_PREFIX + name; } name = name.replace('.', '_'); return name; }
Source:
<code>public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String remoteAddress = context.channel().remoteAddress().toString(); long startNano = Long.parseLong(requestContext.getHeaderString(NANO_TIME)); String requestMethod = requestContext.getMethod(); String uri = requestContext.getUriInfo().getPath(); int status = responseContext.getStatus(); int requestSize = requestContext.getLength(); int responseSize = responseContext.getLength(); if (responseSize == -1 && responseContext.hasEntity()) { Object entity = responseContext.getEntity(); if (entity instanceof byte[]) { responseSize = ((byte[]) entity).length; responseContext.getHeaders().addFirst(HttpHeaders.CONTENT_LENGTH, responseSize); } } long responseTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNano); <START> log.fatalf("%s [%s] \"%s %s\" %s %d %d %d ms", remoteAddress, responseTime, requestMethod, uri, status, requestSize, <END> responseSize, responseTime); }</code><technical_language>Fatal</technical_language>

Target:
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String remoteAddress = context.channel().remoteAddress().toString(); long startNano = Long.parseLong(requestContext.getHeaderString(NANO_TIME)); String requestMethod = requestContext.getMethod(); String uri = requestContext.getUriInfo().getPath(); int status = responseContext.getStatus(); int requestSize = requestContext.getLength(); int responseSize = responseContext.getLength(); if (responseSize == -1 && responseContext.hasEntity()) { Object entity = responseContext.getEntity(); if (entity instanceof byte[]) { responseSize = ((byte[]) entity).length; responseContext.getHeaders().addFirst(HttpHeaders.CONTENT_LENGTH, responseSize); } } long responseTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNano); log.tracef("%s [%s] \"%s %s\" %s %d %d %d ms", remoteAddress, responseTime, requestMethod, uri, status, requestSize, responseSize, responseTime); }
Source:
<code>private void updateDefaultNameSpaces(final Node<Definition<DMNDiagram>, ?> diagramNode) { final DMNDiagram dmnDiagram = diagramNode.getContent().getDefinition(); final Definitions dmnDefinitions = dmnDiagram.getDefinitions(); Stream.of(DMNModelInstrumentedBase.Namespace.values()) .filter(namespace -> !dmnDefinitions.getNsContext().containsValue(namespace.getUri())) .forEach(namespace -> dmnDefinitions.getNsContext().put(namespace.getPrefix(), namespace.getUri())); <START> String defaultNamespace = (dmnDefinitions.getNamespace() != null) <END> ? dmnDefinitions.getNamespace() : DMNModelInstrumentedBase.Namespace.DEFAULT.getUri() + UUID.uuid(); dmnDefinitions.setNamespace(defaultNamespace); dmnDefinitions.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), defaultNamespace); }</code><technical_language>I do [StringUtils](<LINK_0> check here</technical_language>

Target:
private void updateDefaultNameSpaces(final Node<Definition<DMNDiagram>, ?> diagramNode) { final DMNDiagram dmnDiagram = diagramNode.getContent().getDefinition(); final Definitions dmnDefinitions = dmnDiagram.getDefinitions(); Stream.of(DMNModelInstrumentedBase.Namespace.values()) .filter(namespace -> !dmnDefinitions.getNsContext().containsValue(namespace.getUri())) .forEach(namespace -> dmnDefinitions.getNsContext().put(namespace.getPrefix(), namespace.getUri())); String defaultNamespace = !StringUtils.isEmpty(dmnDefinitions.getNamespace()) ? dmnDefinitions.getNamespace() : DMNModelInstrumentedBase.Namespace.DEFAULT.getUri() + UUID.uuid(); dmnDefinitions.setNamespace(defaultNamespace); dmnDefinitions.getNsContext().put(DMNModelInstrumentedBase.Namespace.DEFAULT.getPrefix(), defaultNamespace); }
Source:
<code>protected int insertHeaderCellInSec(final HSSFRow headerRow, final int columnIndex, final String value) { int newColumnIndex = columnIndex; HSSFCell cell = headerRow.createCell(newColumnIndex++); cell.setCellStyle(headerCellStyle); <START> if ("false".equals( <END> pluginSettings.get(GlobalSettingsKey.JTTP_PLUGIN_REPORTING_SETTINGS_WORKLOG_IN_SEC))) { cell.setCellValue(value); } else { cell.setCellValue(value + " (s)"); } return newColumnIndex; }</code><technical_language>This repelaced a UserReportingSettingsHelper call</technical_language>

Target:
protected int insertHeaderCellInSec(final HSSFRow headerRow, final int columnIndex, final String value) { int newColumnIndex = columnIndex; HSSFCell cell = headerRow.createCell(newColumnIndex++); cell.setCellStyle(headerCellStyle); if (userReportingSettingsHelper.getWorklogTimeInSeconds()) { cell.setCellValue(value + " (s)"); } else { cell.setCellValue(value); } return newColumnIndex; }
Source:
<code>public List<ConstraintViolation> validate(Command command) { final ImmutableList.Builder<ConstraintViolation> result = ImmutableList.builder(); if (!command.hasMessage()) { result.add(ConstraintViolation.newBuilder().setMsgFormat(COMMAND_MESSAGE_MUST_BE_SET).build()); } if (!command.hasContext()) { result.add(ConstraintViolation.newBuilder().setMsgFormat(COMMAND_CONTEXT_MUST_BE_SET).build()); } final Message commandMessage = Commands.getMessage(command); final Object targetId = GetTargetIdFromCommand.asNullableObject(commandMessage); if (targetId != null) { final String targetIdString = idToString(targetId).trim(); if (targetIdString.isEmpty()) { result.add(ConstraintViolation.newBuilder().setMsgFormat( COMMAND_TARGET_ENTITY_ID_CANNOT_BE_EMPTY_OR_BLANK).build()); } } final List<ConstraintViolation> messageViolations = new MessageValidator().validate(commandMessage); result.addAll(messageViolations); final CommandContext context = command.getContext(); <START> final String commandId = idToString(context.getCommandId()); <END> if (commandId.isEmpty()) { result.add(ConstraintViolation.newBuilder().setMsgFormat(COMMAND_ID_CANNOT_BE_EMPTY_OR_BLANK).build()); } return result.build(); }</code><technical_language>Command/EventIdToStringConverters registered in converter registry, I remove explicit command/event ID conversion idToString()</technical_language>

Target:
public List<ConstraintViolation> validate(Command command) { final ImmutableList.Builder<ConstraintViolation> result = ImmutableList.builder(); if (!command.hasMessage()) { result.add(newConstraintViolation(COMMAND_MESSAGE_MUST_BE_SET)); } if (!command.hasContext()) { result.add(newConstraintViolation(COMMAND_CONTEXT_MUST_BE_SET)); } final Message commandMessage = Commands.getMessage(command); final Object targetId = GetTargetIdFromCommand.asNullableObject(commandMessage); if (targetId != null) { final String targetIdString = idToString(targetId); if (targetIdString.equals(EMPTY_ID)) { result.add(newConstraintViolation(COMMAND_TARGET_ENTITY_ID_CANNOT_BE_EMPTY_OR_BLANK)); } } final List<ConstraintViolation> messageViolations = new MessageValidator().validate(commandMessage); result.addAll(messageViolations); final CommandContext context = command.getContext(); final String commandId = idToString(context.getCommandId()); if (commandId.equals(EMPTY_ID)) { result.add(newConstraintViolation(COMMAND_ID_CANNOT_BE_EMPTY_OR_BLANK)); } return result.build(); }
Source:
<code>protected void endStepJob() { GlusterAsyncTask asyncTask = getGlusterVolume().getAsyncTask(); <START> Step step = DbFacade.getInstance().getStepDao().getStepsByExternalId(asyncTask.getTaskId()).get(0); <END> step.markStepEnded(JobExecutionStatus.ABORTED); step.setDescription(ExecutionMessageDirector.resolveStepMessage(getStepType(), getStepMessageMap(JobExecutionStatus.ABORTED))); JobRepositoryFactory.getJobRepository().updateStep(step); ExecutionContext finalContext = ExecutionHandler.createFinalizingContext(step.getId()); ExecutionHandler.endTaskJob(finalContext, false); }</code><technical_language>please introduce a getStepDao() perform return DbFacade.getInstance().getStepDao()</technical_language>

Target:
protected void endStepJob() { GlusterAsyncTask asyncTask = getGlusterVolume().getAsyncTask(); Step step = getStepDao().getStepsByExternalId(asyncTask.getTaskId()).get(0); step.markStepEnded(JobExecutionStatus.ABORTED); step.setDescription(ExecutionMessageDirector.resolveStepMessage(getStepType(), getStepMessageMap(JobExecutionStatus.ABORTED))); JobRepositoryFactory.getJobRepository().updateStep(step); ExecutionContext finalContext = ExecutionHandler.createFinalizingContext(step.getId()); ExecutionHandler.endTaskJob(finalContext, false); }
Source:
<code>private void updateProgramRecord(final SAMRecord record, final Map<String, String> chainedPgIds) { if (PROGRAM_RECORD_ID != null) { final String pgId = record.getStringAttribute(SAMTag.PG.name()); if (null == pgId) { if (!warnedNullProgramRecords) { warnedNullProgramRecords = true; log.warn("Encountered a record with no program record, program group chaining will not occur for this read: " + record); } } else if (!chainedPgIds.containsKey(pgId)) { if (!warnedMissingProgramRecords) { warnedMissingProgramRecords = true; <START> log.warn("Encountered a record with a intermediate program record, program group chaining will not occur for this read: " + record); <END> } } else { record.setAttribute(SAMTag.PG.name(), chainedPgIds.get(pgId)); } } }</code><technical_language>"an"</technical_language>

Target:
private void updateProgramRecord(final SAMRecord record, final Map<String, String> chainedPgIds) { if (PROGRAM_RECORD_ID != null) { final String pgId = record.getStringAttribute(SAMTag.PG.name()); if (null == pgId) { if (!warnedNullProgramRecords) { warnedNullProgramRecords = true; log.warn("Encountered a record with no program record, program group chaining will not occur for this read: " + record); } } else if (!chainedPgIds.containsKey(pgId)) { if (!warnedMissingProgramRecords) { warnedMissingProgramRecords = true; log.warn("Encountered a record with an intermediate program record, program group chaining will not occur for this read: " + record); } } else { record.setAttribute(SAMTag.PG.name(), chainedPgIds.get(pgId)); } } }
Source:
<code>private GraphDatabaseAPI deleteLogFilesAndRestart() throws IOException { <START> final Predicate<Path> logFileFilter = p -> p.getFileName().toString().contains( "logical" ); <END> return dbRule.restartDatabase( ( fs, storeDirectory ) -> { Iterable<Path> logFiles = Files.list( storeDir ).filter( logFileFilter )::iterator; for ( Path logFile : logFiles ) { Files.delete( logFile ); } } ); }</code><technical_language>delete "logical" file? log files abstraction instead</technical_language>

Target:
private GraphDatabaseAPI deleteLogFilesAndRestart() throws IOException { List<File> logFiles = new ArrayList<>(); NeoStoreDataSource dataSource = dbRule.resolveDependency( NeoStoreDataSource.class ); try ( ResourceIterator<StoreFileMetadata> files = dataSource.listStoreFiles( true ) ) { files.stream().filter( StoreFileMetadata::isLogFile ) .map( StoreFileMetadata::file ) .forEach( logFiles::add ); } return dbRule.restartDatabase( ( fs, storeDirectory ) -> { for ( File logFile : logFiles ) { fs.deleteFile( logFile ); } } ); }
Source:
<code>public static String toJson(Date date) { <START> dateFormat.setTimeZone(TimeZone.getTimeZone(DEFAULT_TIMEZONE)); <END> return toJson(date, dateFormat); }</code><technical_language>note above, new a SimpleDateFormat here, provide a override JSON_DATE_FORMAT is construct a new format object provide format string fall JSON_DATE_FORMAT if provided</technical_language>

Target:
public static String toJson(Date date) { if (date == null) { return NULL_VALUE; } CharBuf buffer = CharBuf.create(26); writeDate(date, buffer); return buffer.toString(); }
Source:
<code>public InternalResourceGroup getLatest() <START> { <END> InternalResourceGroup latest = this; while (latest.getNext().isPresent()) { latest = latest.getNext().get(); } return latest; }</code><technical_language>here. need synchronized</technical_language>

Target:
public InternalResourceGroup getLatest() { synchronized (root) { InternalResourceGroup latest = this; while (latest.next.isPresent()) { latest = latest.next.get(); } return latest; } }