auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static IBinding instantiateBinding(IBinding binding, ICPPTemplateParameterMap tpMap, int packOffset, ICPPClassSpecialization within, int maxdepth, IASTNode point) throws DOMException { if (binding instanceof ICPPClassTemplate) { binding = createDeferredInstance((ICPPClassTemplate) binding); } if (binding instanceof ICPPUnknownBinding) { return resolveUnknown((ICPPUnknownBinding) binding, tpMap, packOffset, within, point); <START> } else if (binding instanceof IEnumerator <END> || binding instanceof ICPPMethod || binding instanceof ICPPField || binding instanceof ICPPEnumeration || binding instanceof ICPPClassType) { IBinding owner = binding.getOwner(); if (!(owner instanceof ICPPSpecialization)) { owner = instantiateBinding(owner, tpMap, packOffset, within, maxdepth, point); } if (binding instanceof IEnumerator) { if (owner instanceof ICPPEnumerationSpecialization) { return ((ICPPEnumerationSpecialization) owner).specializeEnumerator((IEnumerator) binding); } } else { if (owner instanceof ICPPClassSpecialization) { return ((ICPPClassSpecialization) owner).specializeMember(binding, point); } } } return binding; }</code><technical_language>Redundant 'else'</technical_language>

Target:
public static IBinding instantiateBinding(IBinding binding, ICPPTemplateParameterMap tpMap, int packOffset, ICPPClassSpecialization within, int maxdepth, IASTNode point) throws DOMException { if (binding instanceof ICPPClassTemplate) { binding = createDeferredInstance((ICPPClassTemplate) binding); } if (binding instanceof ICPPUnknownBinding) { return resolveUnknown((ICPPUnknownBinding) binding, tpMap, packOffset, within, point); } if (binding instanceof IEnumerator || binding instanceof ICPPMethod || binding instanceof ICPPField || binding instanceof ICPPEnumeration || binding instanceof ICPPClassType) { IBinding owner = binding.getOwner(); if (!(owner instanceof ICPPSpecialization)) { owner = instantiateBinding(owner, tpMap, packOffset, within, maxdepth, point); } if (binding instanceof IEnumerator) { if (owner instanceof ICPPEnumerationSpecialization) { return ((ICPPEnumerationSpecialization) owner).specializeEnumerator((IEnumerator) binding); } } else { if (owner instanceof ICPPClassSpecialization) { return ((ICPPClassSpecialization) owner).specializeMember(binding, point); } } } return binding; }
Source:
<code>public void handleServerSafe(NetHandlerPlayServer netHandler) { <START> if(netHandler.player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() instanceof ItemSlimeBoots) <END> netHandler.player.fallDistance = 0; }</code><technical_language>indentation is off, 2 space indentation. curly brackets for single if statements</technical_language>

Target:
public void handleServerSafe(NetHandlerPlayServer netHandler) { if(netHandler.player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() instanceof ItemSlimeBoots) { netHandler.player.fallDistance = 0; } }
Source:
<code>public HttpResponse getTraces( <START> @Param("serviceName") Optional<String> serviceName, <END> @Param("spanName") Optional<String> spanName, @Param("annotationQuery") Optional<String> annotationQuery, @Param("minDuration") Optional<Long> minDuration, @Param("maxDuration") Optional<Long> maxDuration, @Param("endTs") Optional<Long> endTs, @Param("lookback") Optional<Long> lookback, @Default("10") @Param("limit") int limit) throws IOException { QueryRequest queryRequest = QueryRequest.newBuilder() .serviceName(serviceName.orElse(null)) .spanName(spanName.orElse(null)) .parseAnnotationQuery(annotationQuery.orElse(null)) .minDuration(minDuration.orElse(null)) .maxDuration(maxDuration.orElse(null)) .endTs(endTs.orElse(System.currentTimeMillis())) .lookback(lookback.orElse(defaultLookback)) .limit(limit) .build(); List<List<Span>> traces = storage.spanStore().getTraces(queryRequest).execute(); return jsonResponse(writeTraces(SpanBytesEncoder.JSON_V2, traces)); }</code><technical_language>omit of @Param annotation if -parameters javac option. <LINK_0></technical_language>

Target:
public AggregatedHttpMessage getTraces( @Param("serviceName") Optional<String> serviceName, @Param("spanName") Optional<String> spanName, @Param("annotationQuery") Optional<String> annotationQuery, @Param("minDuration") Optional<Long> minDuration, @Param("maxDuration") Optional<Long> maxDuration, @Param("endTs") Optional<Long> endTs, @Param("lookback") Optional<Long> lookback, @Default("10") @Param("limit") int limit) throws IOException { QueryRequest queryRequest = QueryRequest.newBuilder() .serviceName(serviceName.orElse(null)) .spanName(spanName.orElse(null)) .parseAnnotationQuery(annotationQuery.orElse(null)) .minDuration(minDuration.orElse(null)) .maxDuration(maxDuration.orElse(null)) .endTs(endTs.orElse(System.currentTimeMillis())) .lookback(lookback.orElse(defaultLookback)) .limit(limit) .build(); List<List<Span>> traces = storage.spanStore().getTraces(queryRequest).execute(); return jsonResponse(writeTraces(SpanBytesEncoder.JSON_V2, traces)); }
Source:
<code>public int getNumActiveTasks() { <START> return super.getActiveCount() - mNumPaused; <END> }</code><technical_language>Is correct mPauseLock is protecting mNumPaused</technical_language>

Target:
public int getNumActiveTasks() { mPauseLock.lock(); try { return super.getActiveCount() - mNumPaused; } finally { mPauseLock.unlock(); } }
Source:
<code>public boolean hasFlavors( ImmutableSet<Flavor> flavors, TargetConfiguration toolchainTargetConfiguration) { Set<Flavor> unmatchedFlavors = Sets.difference(flavors, SUPPORTED_FLAVORS); if (unmatchedFlavors.isEmpty()) { return true; } ImmutableSet<Flavor> delegateFlavors = ImmutableSet.copyOf(Sets.difference(flavors, NON_DELEGATE_FLAVORS)); ImmutableSet<Flavor> supportedDelegateFlavors = swiftDelegate .map(swift -> swift.getSupportedFlavors(delegateFlavors, toolchainTargetConfiguration)) .orElse(ImmutableSet.<Flavor>of()); unmatchedFlavors = Sets.difference(unmatchedFlavors, supportedDelegateFlavors); if (unmatchedFlavors.isEmpty()) { return true; } ImmutableList<ImmutableSortedSet<Flavor>> thinFlavorSets = generateThinDelegateFlavors(ImmutableSet.<Flavor>copyOf(unmatchedFlavors)); if (thinFlavorSets.size() > 0) { return Iterables.all( thinFlavorSets, inputFlavors -> cxxBinaryFlavored.hasFlavors(inputFlavors, toolchainTargetConfiguration)); } else { <START> return cxxBinaryFlavored.hasFlavors(ImmutableSet.<Flavor>copyOf(unmatchedFlavors), toolchainTargetConfiguration); <END> } }</code><technical_language>this match style more closely suggestion return cxxBinaryFlavored.hasFlavors( ImmutableSet.<Flavor>copyOf(unmatchedFlavors), toolchainTargetConfiguration);</technical_language>

Target:
public boolean hasFlavors( ImmutableSet<Flavor> flavors, TargetConfiguration toolchainTargetConfiguration) { Set<Flavor> unmatchedFlavors = Sets.difference(flavors, SUPPORTED_FLAVORS); if (unmatchedFlavors.isEmpty()) { return true; } ImmutableSet<Flavor> delegateFlavors = ImmutableSet.copyOf(Sets.difference(flavors, NON_DELEGATE_FLAVORS)); ImmutableSet<Flavor> supportedDelegateFlavors = swiftDelegate .map(swift -> swift.getSupportedFlavors(delegateFlavors, toolchainTargetConfiguration)) .orElse(ImmutableSet.<Flavor>of()); unmatchedFlavors = Sets.difference(unmatchedFlavors, supportedDelegateFlavors); if (unmatchedFlavors.isEmpty()) { return true; } ImmutableSet<Flavor> immutableUnmatchedFlavors = ImmutableSet.<Flavor>copyOf(unmatchedFlavors); ImmutableList<ImmutableSortedSet<Flavor>> thinFlavorSets = generateThinDelegateFlavors(immutableUnmatchedFlavors); if (thinFlavorSets.size() > 0) { return Iterables.all( thinFlavorSets, inputFlavors -> cxxBinaryFlavored.hasFlavors(inputFlavors, toolchainTargetConfiguration)); } else { return cxxBinaryFlavored.hasFlavors(immutableUnmatchedFlavors, toolchainTargetConfiguration); } }
Source:
<code>public void updateSchema(KObject kObject) { String clustedId = toProtobufFormat(kObject.getClusterId()); Optional<Schema> storedSchema = this.infinispanContext.getSchema(clustedId); if (!storedSchema.isPresent()) { Schema newSchema = this.mappingProvider.getMapping(kObject); <START> newSchema.getMessages().stream().forEach(message -> { <END> message.setFields(this.reorderFields(new ArrayList<>(message.getFields()))); }); this.infinispanContext.addSchema(newSchema); this.infinispanContext.addProtobufSchema(kObject.getClusterId(), newSchema); } else { String type = toProtobufFormat(kObject.getClusterId() + "_" + kObject.getType().getName()); Optional<Message> storedMessage = this.getMessage(storedSchema.get(), type); Set<Message> messages = new HashSet<>(); if (storedMessage.isPresent()) { Message newMessages = this.merge(storedMessage.get(), this.getMessage(kObject)); messages.addAll(storedSchema.get().getMessages()); messages.remove(storedMessage.get()); messages.add(newMessages); } else { Set<Message> newMessages = this.mappingProvider.buildMessages(kObject); messages.addAll(newMessages); messages.addAll(storedSchema.get().getMessages()); } Schema newSchema = this.mappingProvider.buildSchema(kObject, messages); this.infinispanContext.addSchema(newSchema); this.infinispanContext.addProtobufSchema(kObject.getClusterId(), newSchema); } }</code><technical_language>stream().forEach() -> forEach()</technical_language>

Target:
public void updateSchema(KObject kObject) { String clustedId = toProtobufFormat(kObject.getClusterId()); Optional<Schema> storedSchema = this.infinispanContext.getSchema(clustedId); if (!storedSchema.isPresent()) { Schema newSchema = this.mappingProvider.getMapping(kObject); newSchema.getMessages().forEach(message -> { message.setFields(this.reorderFields(new ArrayList<>(message.getFields()))); }); this.infinispanContext.addSchema(newSchema); this.infinispanContext.addProtobufSchema(kObject.getClusterId(), newSchema); } else { String type = toProtobufFormat(kObject.getClusterId() + "_" + kObject.getType().getName()); Optional<Message> storedMessage = this.getMessage(storedSchema.get(), type); Set<Message> messages = new HashSet<>(); if (storedMessage.isPresent()) { Message newMessages = this.merge(storedMessage.get(), this.getMessage(kObject)); messages.addAll(storedSchema.get().getMessages()); messages.remove(storedMessage.get()); messages.add(newMessages); } else { Set<Message> newMessages = this.mappingProvider.buildMessages(kObject); messages.addAll(newMessages); messages.addAll(storedSchema.get().getMessages()); } Schema newSchema = this.mappingProvider.buildSchema(kObject, messages); this.infinispanContext.addSchema(newSchema); this.infinispanContext.addProtobufSchema(kObject.getClusterId(), newSchema); } }
Source:
<code>public static String getErrorMessage(final Context context, final MediaModel media, final MediaStore.MediaError error) { if (context == null || media == null || error == null) { return null; } switch (error.type) { case FS_READ_PERMISSION_DENIED: return context.getString(R.string.error_media_insufficient_fs_permissions); case NOT_FOUND: return context.getString(R.string.error_media_not_found); case AUTHORIZATION_REQUIRED: return context.getString(R.string.media_error_no_permission_upload); case REQUEST_TOO_LARGE: if (media.isVideo()) { return context.getString(R.string.media_error_http_too_large_video_upload); } else { <START> return context.getString(R.string.media_error_http_too_large_photo_upload) + ". " + <END> context.getString(R.string.media_error_suggest_optimize_image); } case SERVER_ERROR: return context.getString(R.string.media_error_internal_server_error); case TIMEOUT: return context.getString(R.string.media_error_timeout); case CONNECTION_ERROR: return context.getString(R.string.connection_error) + ". " + context.getString(R.string.media_error_generic_connection_error); case EXCEEDS_FILESIZE_LIMIT: return context.getString(R.string.media_error_exceeds_php_filesize); case EXCEEDS_MEMORY_LIMIT: return context.getString(R.string.media_error_exceeds_memory_limit); case PARSE_ERROR: return context.getString(R.string.error_media_parse_error); } return null; }</code><technical_language>concatenating strings a single string resource work</technical_language>

Target:
public static String getErrorMessage(final Context context, final MediaModel media, final MediaStore.MediaError error) { if (context == null || media == null || error == null) { return null; } switch (error.type) { case FS_READ_PERMISSION_DENIED: return context.getString(R.string.error_media_insufficient_fs_permissions); case NOT_FOUND: return context.getString(R.string.error_media_not_found); case AUTHORIZATION_REQUIRED: return context.getString(R.string.media_error_no_permission_upload); case REQUEST_TOO_LARGE: if (media.isVideo()) { return context.getString(R.string.media_error_http_too_large_video_upload); } else { return context.getString(R.string.media_error_http_too_large_photo_upload); } case SERVER_ERROR: return context.getString(R.string.media_error_internal_server_error); case TIMEOUT: return context.getString(R.string.media_error_timeout); case CONNECTION_ERROR: return context.getString(R.string.connection_error); case EXCEEDS_FILESIZE_LIMIT: return context.getString(R.string.media_error_exceeds_php_filesize); case EXCEEDS_MEMORY_LIMIT: return context.getString(R.string.media_error_exceeds_memory_limit); case PARSE_ERROR: return context.getString(R.string.error_media_parse_error); } return null; }
Source:
<code>public PhoneHome(Node node) { hazelcastNode = node; logger = hazelcastNode.getLogger(com.hazelcast.internal.util.phonehome.PhoneHome.class); <START> basePhoneHomeUrl = "<LINK_0>"; <END> }</code><technical_language>Please change this constructor calls other 2-arg constructor. Generally is good field assignments in a single constructor (as long possible), if argument validation is necessary, is enough do place only. please extract "<LINK_0>" a constant called DEFAULT_BASE_PHONE_HOME_URL</technical_language>

Target:
public PhoneHome(Node node) { this(node, DEFAULT_BASE_PHONE_HOME_URL); }
Source:
<code>protected Statement classBlock(final RunNotifier notifier) { if (areAllChildrenIgnored()) { return withIgnores(null, notifier); } Statement statement = childrenInvoker(notifier); statement = withBeforeClasses(statement); <START> statement = withIgnores(statement, notifier); <END> statement = withAfterClasses(statement); statement = withClassRules(statement); return statement; }</code><technical_language>this do returning statement chain? If class rules @AfterClass methods throw, want methods notified? worried notifications out of order</technical_language>

Target:
protected Statement classBlock(final RunNotifier notifier) { if (areAllChildrenIgnored()) { return withNotificationOfIgnoredChildren(null, notifier); } Statement statement = childrenInvoker(notifier); statement = withBeforeClasses(statement); statement = withNotificationOfIgnoredChildren(statement, notifier); statement = withAfterClasses(statement); statement = withClassRules(statement); return statement; }
Source:
<code>public static AbstractWebsocket getWebsocketImpl(Class<? extends AbstractWebsocket> websocketImpl, ModularXmppClientToServerConnectionInternal connectionInternal, DiscoveredWebsocketEndpoints discoveredWebsocketEndpoints) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { <START> if (connectionInternal == null) { <END> throw new IllegalArgumentException("ConnectionInternal cannot be null"); } Constructor<? extends AbstractWebsocket> constructor = websocketImpl.getConstructor(ModularXmppClientToServerConnectionInternal.class, DiscoveredWebsocketEndpoints.class); return (AbstractWebsocket) constructor.newInstance(connectionInternal, discoveredWebsocketEndpoints); }</code><technical_language>Objects.requireNotNull instead</technical_language>

Target:
public static AbstractWebsocket getWebsocketImpl(Class<? extends AbstractWebsocket> websocketImpl, ModularXmppClientToServerConnectionInternal connectionInternal, DiscoveredWebsocketEndpoints discoveredWebsocketEndpoints) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Objects.requireNonNull(connectionInternal, "ConnectionInternal cannot be null"); Constructor<? extends AbstractWebsocket> constructor = websocketImpl.getConstructor(ModularXmppClientToServerConnectionInternal.class, DiscoveredWebsocketEndpoints.class); return (AbstractWebsocket) constructor.newInstance(connectionInternal, discoveredWebsocketEndpoints); }
Source:
<code><START> <U> BitMappedTrie<U> map(Function<? super T, ? extends U> mapper) { <END> Objects.requireNonNull(mapper, "mapper is null"); final Object[] elems = newInstance(length); final MutableInt index = new MutableInt(); this.<T> visit((leaf, start, end) -> { for (int i = start; i < end; i++) { elems[index.val++] = mapper.apply(leaf[i]); } }); return BitMappedTrie.ofAll(elems, length, 0); }</code><technical_language>I do need improvement (for now). new visitor, map method this: java <U> BitMappedTrie<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); final Object[] results = new Object[length()]; this.<T> visit((leaf, start, end, index) -> { for (int i = start; i < end; i++) { elems[index++] = mapper.apply(leaf[i]); } return index; }); return BitMappedTrie.ofAll(elems, length); }</technical_language>

Target:
<U> BitMappedTrie<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); final Object[] results = newInstance(length); this.<T> visit((index, leaf, start, end) -> { for (int i = start; i < end; i++) { results[index++] = mapper.apply(leaf[i]); } return index; }); return BitMappedTrie.ofAll(results); }
Source:
<code>public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { checkInitialized(); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); final Optional<TaskExecutorProcessSpecContainerResourcePriorityAdapter.PriorityAndResource> priorityAndResourceOpt = taskExecutorProcessSpecContainerResourcePriorityAdapter.getPriorityAndResource(taskExecutorProcessSpec); if (!priorityAndResourceOpt.isPresent()) { <START> requestResourceFuture.completeExceptionally( new ResourceManagerException(String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s.", taskExecutorProcessSpec))); <END> } else { final Priority priority = priorityAndResourceOpt.get().getPriority(); final Resource resource = priorityAndResourceOpt.get().getResource(); resourceManagerClient.addContainerRequest(getContainerRequest(resource, priority)); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new LinkedList<>()).add(requestResourceFuture); log.info("Requesting new TaskExecutor container with resource {}, priority {}.", taskExecutorProcessSpec, priority); } return requestResourceFuture; }</code><technical_language>a bit more details helpful here? compute container resource</technical_language>

Target:
public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { checkInitialized(); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); final Optional<TaskExecutorProcessSpecContainerResourcePriorityAdapter.PriorityAndResource> priorityAndResourceOpt = taskExecutorProcessSpecContainerResourcePriorityAdapter.getPriorityAndResource(taskExecutorProcessSpec); if (!priorityAndResourceOpt.isPresent()) { requestResourceFuture.completeExceptionally( new ResourceManagerException( String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s. " + "This usually indicates the requested resource is larger than Yarn's max container resource limit.", taskExecutorProcessSpec))); } else { final Priority priority = priorityAndResourceOpt.get().getPriority(); final Resource resource = priorityAndResourceOpt.get().getResource(); resourceManagerClient.addContainerRequest(getContainerRequest(resource, priority)); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new LinkedList<>()).add(requestResourceFuture); log.info("Requesting new TaskExecutor container with resource {}, priority {}.", taskExecutorProcessSpec, priority); } return requestResourceFuture; }
Source:
<code>public void startLRA() throws WebApplicationException { <START> URL lra = lraClient.startLRA(null, "SpecTest#startLRA", LRA_TIMEOUT_MILLIS, TimeUnit.SECONDS); <END> lraClient.closeLRA(lra); }</code><technical_language>I feel a startLRA operation require pass null param for parentLRA</technical_language>

Target:
public void startLRA() throws WebApplicationException { URL lra = lraClient.startLRA("SpecTest#startLRA", LRA_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); lraClient.closeLRA(lra); }
Source:
<code>public void removeWaypoint(Waypoint waypoint) { <START> if(waypoints.contains(waypoint)) <END> waypoints.remove(waypoint); }</code><technical_language>follow [1TBS](<LINK_0> exclusively (also, space if ()</technical_language>

Target:
public void removeWaypoint(Waypoint waypoint) { if (waypoints.contains(waypoint)) { waypoints.remove(waypoint); } }
Source:
<code>void onWindowFocusChange(boolean inFocus) { GridTimer modelTimer = getModelTimer(); if (modelTimer.isActive() && !modelTimer.isPaused()) { if (inFocus) { <START> modelTimer.stop(); <END> modelTimer.setRefreshRate(readRefreshRate()); } else { modelTimer.stop(); modelTimer.setRefreshRate(OUT_OF_FOCUS_REFRESH_RATE); } modelTimer.start(); } }</code><technical_language>Hm, reason add: modelTimer.stop(); if block, is analogous having: modelTimer.start(); if block</technical_language>

Target:
void onWindowFocusChange(boolean inFocus) { GridTimer modelTimer = getModelTimer(); if (modelTimer.isActive() && !modelTimer.isPaused()) { modelTimer.stop(); if (inFocus) { modelTimer.setRefreshRate(readRefreshRate()); } else { modelTimer.setRefreshRate(OUT_OF_FOCUS_REFRESH_RATE); } modelTimer.start(); } }
Source:
<code>private RxDocumentServiceResponse completeResponse( StoreResponse storeResponse, RxDocumentServiceRequest request) throws InternalServerErrorException { if (storeResponse.getResponseHeaderNames().length != storeResponse.getResponseHeaderValues().length) { throw new InternalServerErrorException(RMResources.InvalidBackendResponse); } <START> HttpHeaders httpHeaders = new HttpHeaders(); <END> for (int idx = 0; idx < storeResponse.getResponseHeaderNames().length; idx++) { String name = storeResponse.getResponseHeaderNames()[idx]; String value = storeResponse.getResponseHeaderValues()[idx]; httpHeaders.put(name, value); } this.updateResponseHeader(request, httpHeaders); this.captureSessionToken(request, httpHeaders); BridgeInternal.recordRetryContext(request.requestContext.cosmosDiagnostics, request); storeResponse.setCosmosDiagnostics(request.requestContext.cosmosDiagnostics); return new RxDocumentServiceResponse(storeResponse); }</code><technical_language>potential perf impact. previously pass capacity constructor of hashmap upfront reserving required capacity underlying map grow multiple times</technical_language>

Target:
private RxDocumentServiceResponse completeResponse( StoreResponse storeResponse, RxDocumentServiceRequest request) throws InternalServerErrorException { HttpHeaders httpHeaders = storeResponse.getHeaders(); this.updateResponseHeader(request, httpHeaders); this.captureSessionToken(request, httpHeaders); BridgeInternal.recordRetryContext(request.requestContext.cosmosDiagnostics, request); storeResponse.setCosmosDiagnostics(request.requestContext.cosmosDiagnostics); return new RxDocumentServiceResponse(storeResponse); }
Source:
<code>public void update() { fNodes = new HashMap<>(); <START> fChildren = new HashMap<>(); <END> fTree.removeAll(); Path path = Paths.get(fXmlFilesPath.toString()); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { TreeItem itemParent = fNodes.get(dir.getParent().toString()); TreeItem item = null; if (itemParent == null) { item = new TreeItem(fTree, SWT.NONE); } else { item = new TreeItem(itemParent, SWT.NONE); } item.setText(dir.getFileName().toString()); fItemsPaths.put(item, dir); fNodes.put(dir.toString(), item); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path dir, BasicFileAttributes attrs){ TreeItem itemParent = fNodes.get(dir.getParent().toString()); if (fChildren.get(itemParent) == null) { fChildren.put(itemParent, new ArrayList<Path>()); } fChildren.get(itemParent).add(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Activator.logError("Cannot walk through the XML Files directory!", e); } for (TreeItem p : fChildren.keySet()) { for (Path c : fChildren.get(p)) { TreeItem item = new TreeItem(p, SWT.NONE); fItemsPaths.put(item, c); item.setText(c.getFileName().toString()); } } fTree.layout(); fNodes = null; fChildren = null; }</code><technical_language>initialize set null end. local variables instead</technical_language>

Target:
public void update() { final Map<String, TreeItem> fNodes = new HashMap<>(); final Map<TreeItem, ArrayList<Path>> fChildren = new HashMap<>(); fTree.removeAll(); Path path = Paths.get(fXmlFilesPath.toString()); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { TreeItem itemParent = fNodes.get(dir.getParent().toString()); TreeItem item = null; if (itemParent == null) { item = new TreeItem(fTree, SWT.NONE); } else { item = new TreeItem(itemParent, SWT.NONE); } item.setText(dir.getFileName().toString()); fItemsPaths.put(item, dir); fNodes.put(dir.toString(), item); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path dir, BasicFileAttributes attrs) { TreeItem itemParent = fNodes.get(dir.getParent().toString()); if (fChildren.get(itemParent) == null) { fChildren.put(itemParent, new ArrayList<Path>()); } fChildren.get(itemParent).add(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Activator.logError("Cannot walk through the XML Files directory!", e); } for (TreeItem p : fChildren.keySet()) { for (Path c : fChildren.get(p)) { TreeItem item = new TreeItem(p, SWT.NONE); fItemsPaths.put(item, c); item.setText(c.getFileName().toString()); } } fTree.layout(); }
Source:
<code>public void readRanges() { long firstTileOffset = cogTileInfo.getFirstTileOffset(); byte[] headerBytes = CacheManagement.DEFAULT.getHeader(uri.toString()); if (firstTileOffset < headerBytes.length) { byte[] newHeaderBytes = Arrays.copyOf(headerBytes, (int) firstTileOffset); CacheManagement.DEFAULT.cacheHeader(uri.toString(), newHeaderBytes); rangeReader.setHeaderLength(newHeaderBytes.length); } RangeBuilder rangeBuilder = new RangeBuilder(0, cogTileInfo.getHeaderSize() - 1); cogTileInfo.getTileRanges().forEach((tileIndex, tileRange) -> { if (tileIndex == HEADER_TILE_INDEX) { return; } TileCacheEntryKey key = new TileCacheEntryKey(uri.toString(), tileIndex); if (!CacheManagement.DEFAULT.keyExists(key)) { rangeBuilder.addTileRange(tileRange.getStart(), tileRange.getEnd()); } }); Set<long[]> ranges = rangeBuilder.getRanges(); if (ranges.size() == 0) { return; } LOGGER.fine("Submitting " + ranges.size() + " range request(s)"); rangeReader.readAsync(ranges); cogTileInfo.getTileRanges().forEach((tileIndex, tileRange) -> { if (tileIndex == HEADER_TILE_INDEX) { return; } TileCacheEntryKey key = new TileCacheEntryKey(uri.toString(), tileIndex); try { byte[] b = rangeReader.getBytes(); byte[] tileBytes = Arrays.copyOfRange(b, (int) tileRange.getStart(), (int) (tileRange.getEnd() + 1)); CacheManagement.DEFAULT.cacheTile(key, tileBytes); } catch (Exception e) { <START> e.printStackTrace(); <END> } }); }</code><technical_language>printing stack trace</technical_language>

Target:
public void readRanges() { ContiguousRangeComposer contiguousRangeComposer = new ContiguousRangeComposer(0, cogTileInfo.getHeaderLength() - 1); cogTileInfo.getTileRanges().forEach((tileIndex, tileRange) -> { if (tileIndex == HEADER_TILE_INDEX) { return; } TileCacheEntryKey key = new TileCacheEntryKey(uri.toString(), tileIndex); if (!CacheManagement.DEFAULT.keyExists(key)) { contiguousRangeComposer.addTileRange(tileRange.getStart(), tileRange.getEnd()); } }); Set<long[]> ranges = contiguousRangeComposer.getRanges(); if (ranges.size() == 0) { return; } LOGGER.fine("Submitting " + ranges.size() + " range request(s)"); Map<Long, byte[]> data = rangeReader.read(ranges); cogTileInfo.getTileRanges().forEach((tileIndex, tileRange) -> { if (tileIndex == HEADER_TILE_INDEX) { return; } TileCacheEntryKey key = new TileCacheEntryKey(uri.toString(), tileIndex); for (Map.Entry<Long, byte[]> entry : data.entrySet()) { long contiguousRangeOffset = entry.getKey(); int contiguousRangeLength = (int) contiguousRangeOffset + entry.getValue().length; if (tileRange.getStart() >= contiguousRangeOffset && tileRange.getEnd() < contiguousRangeLength) { byte[] contiguousBytes = entry.getValue(); long relativeOffset = tileRange.getStart() - contiguousRangeOffset; byte[] tileBytes = Arrays .copyOfRange(contiguousBytes, (int) relativeOffset, (int) tileRange.getEnd()); CacheManagement.DEFAULT.cacheTile(key, tileBytes); } } }); }
Source:
<code>protected boolean delete(XWikiContext context) throws XWikiException { <START> return deleteToRecycleBin(context.getDoc().getDocumentReference().getLastSpaceReference(), context, true); <END> }</code><technical_language>true there? supposed skip recycle bin</technical_language>

Target:
protected boolean delete(XWikiContext context) throws XWikiException { return deleteToRecycleBin(context.getDoc().getDocumentReference().getLastSpaceReference(), context, false); }
Source:
<code>public boolean matches() { List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() == parameters.length ) { <START> for ( int i = 0; i < parameters.length; i++ ) { <END> TypeMatcher parameterMatcher = new TypeMatcher(); parameterMatcher.visit( candidateParameters.get( i ).asType(), parameters[i].getTypeMirror() ); if ( !typesMatch ) { break; } } } else { typesMatch = false; } if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) { typesMatch = false; } } } return typesMatch; }</code><technical_language>Is this loop required? For mapping properties invoke method a single parameter (methods parameters supported public "entry point" for user of a mapper). Btw. I visitor approach. in process of digging everything, this good :)</technical_language>

Target:
public boolean matches() { List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() == parameters.length ) { for ( int i = 0; i < parameters.length; i++ ) { TypeMatcher parameterMatcher = new TypeMatcher(); typesMatch = parameterMatcher.visit( candidateParameters.get( i ).asType(), parameters[i].getTypeMirror() ); if ( !typesMatch ) { break; } } } else { typesMatch = false; } if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) { typesMatch = false; } } } return typesMatch; }
Source:
<code>static void computeSha1s(InputStream fileInputStream, BoxUploadSession uploadSession, long fileSize) throws NoSuchAlgorithmException, IOException { int totalParts = uploadSession.getTotalParts(); List<String> partSha1s = new ArrayList<>(totalParts); byte[] partBuffer = new byte[SdkUtils.BUFFER_SIZE]; int bytesOfChunkToRead; MessageDigest mdFile = MessageDigest.getInstance("SHA-1"); MessageDigest mdPart = MessageDigest.getInstance("SHA-1"); for (int i = 0; i < totalParts; i++) { bytesOfChunkToRead = BoxUploadSession.getChunkSize(uploadSession, i, fileSize); while (bytesOfChunkToRead > 0) { int readTo = Math.min(bytesOfChunkToRead, partBuffer.length); int bytesRead = fileInputStream.read(partBuffer, 0, readTo); <START> if (bytesRead != -1) { <END> bytesOfChunkToRead -= bytesRead; mdPart.update(partBuffer, 0, readTo); mdFile.update(partBuffer, 0, readTo); } } partSha1s.add(Base64.encodeToString(mdPart.digest(), Base64.DEFAULT)); mdPart.reset(); } uploadSession.setPartsSha1(partSha1s); uploadSession.setSha1(Base64.encodeToString(mdFile.digest(), Base64.DEFAULT)); }</code><technical_language>if (bytesRead == -1) break;</technical_language>

Target:
static void computeSha1s(InputStream fileInputStream, BoxUploadSession uploadSession, long fileSize) throws NoSuchAlgorithmException, IOException { int totalParts = uploadSession.getTotalParts(); List<String> partSha1s = new ArrayList<>(totalParts); byte[] partBuffer = new byte[SdkUtils.BUFFER_SIZE]; int bytesOfChunkToRead; MessageDigest mdFile = MessageDigest.getInstance("SHA-1"); MessageDigest mdPart = MessageDigest.getInstance("SHA-1"); for (int i = 0; i < totalParts; i++) { bytesOfChunkToRead = BoxUploadSession.getChunkSize(uploadSession, i, fileSize); while (bytesOfChunkToRead > 0) { int readTo = Math.min(bytesOfChunkToRead, partBuffer.length); int bytesRead = fileInputStream.read(partBuffer, 0, readTo); if (bytesRead != -1) { bytesOfChunkToRead -= bytesRead; mdPart.update(partBuffer, 0, readTo); mdFile.update(partBuffer, 0, readTo); } else if (bytesRead == -1){ break; } } partSha1s.add(Base64.encodeToString(mdPart.digest(), Base64.DEFAULT)); mdPart.reset(); } uploadSession.setPartsSha1(partSha1s); uploadSession.setSha1(Base64.encodeToString(mdFile.digest(), Base64.DEFAULT)); }
Source:
<code>public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException { <START> if (!fEvents.isEmpty()) { <END> if (fEventUnsetId) { throw new CTFReaderException("Cannot add to a stream with an unidentified event"); } for (IEventDeclaration event : events) { if (event != null) { int index = event.getId().intValue(); ensureSize(index); if (fEvents.get(index) != null) { throw new CTFReaderException("Both lists have an event defined at position " + index); } fEvents.set(index, event); } } } else { fEvents.addAll(events); } }</code><technical_language>condition positive, swap if/else clauses</technical_language>

Target:
public void addEvents(Collection<IEventDeclaration> events) throws CTFReaderException { boolean isUnset = isUnsetList(events); if (fEvents.isEmpty()) { fEvents.addAll(events); if( isUnset) { fEventUnsetId = isUnset; } return; } if (fEventUnsetId) { throw new CTFReaderException("Cannot add to a stream with an unidentified event"); } for (IEventDeclaration event : events) { if (event != null) { int index = event.getId().intValue(); ensureSize(index); if (fEvents.get(index) != null) { throw new CTFReaderException("Both lists have an event defined at position " + index); } fEvents.set(index, event); } } }
Source:
<code>@Override public void setUp(BenchmarkConfiguration cfg) throws Exception { super.setUp(cfg); <START> <END> txs = ignite().transactions(); ex = Executors.newFixedThreadPool(cfg.threads()); keysNumbPerThread = (args.range() > cfg.threads() ? args.range() / cfg.threads() : args.range()); }</code><technical_language>put keyCntr Supplier in ThreadLocal.withInitial() a final field. create a static class for it. helps separate a key thread logic benchmarking logic, I guess</technical_language>

Target:
@Override public void setUp(BenchmarkConfiguration cfg) throws Exception { super.setUp(cfg); txs = ignite().transactions(); ex = Executors.newFixedThreadPool(cfg.threads()); keysNumbPerThread = (args.range() > cfg.threads() ? args.range() / cfg.threads() : args.range()); firstKey = new ThreadLocal<Integer>() { final private AtomicInteger keyCntr = new AtomicInteger(0); @Override protected Integer initialValue() { return keyCntr.getAndAdd(keysNumbPerThread); } }; }
Source:
<code>public void genericTestStore( String scheduleType, HashMap<String, Object> scheduleProperties ) throws ParseException { ScheduledTask<Integer> task = null; try { task = createScheduledTask( createSchedule( scheduleType, scheduleProperties ) ); defaultManager.addTask( task ); <START> assertEquals( 1, getTaskConfiguration().size() ); <END> assertEquals( TaskState.SUBMITTED, TaskState.valueOf( ( (CScheduledTask) getTaskConfiguration().get( 0 ) ).getStatus() ) ); assertEquals( TASK_NAME, ( (CScheduledTask) getTaskConfiguration().get( 0 ) ).getName() ); defaultManager.removeTask( task ); } finally { if ( task != null ) { task.cancel(); defaultManager.removeTask( task ); } } }</code><technical_language>touched change assertThat? ;)</technical_language>

Target:
public void genericTestStore( String scheduleType, HashMap<String, Object> scheduleProperties ) throws ParseException { ScheduledTask<Integer> task = null; try { task = createScheduledTask( createSchedule( scheduleType, scheduleProperties ) ); defaultManager.addTask( task ); assertThat( getTaskConfiguration().size(), equalTo( 1 ) ); assertThat( TaskState.valueOf( ( (CScheduledTask) getTaskConfiguration().get( 0 ) ).getStatus() ), equalTo( TaskState.SUBMITTED ) ); assertThat( ( (CScheduledTask) getTaskConfiguration().get( 0 ) ).getName(), equalTo( TASK_NAME ) ); defaultManager.removeTask( task ); } finally { if ( task != null ) { task.cancel(); defaultManager.removeTask( task ); } } }
Source:
<code>public String getCloseTagPattern() { <START> return String.format("<[ ]*/[ ]*%s[ ]*>", this.xmlName); <END> }</code><technical_language>u extract a final constant a readable name out of "<[ ]*/[ ]*%s[ ]*>"</technical_language>

Target:
public String getCloseTagPattern() { return String.format(CLOSE_TAG_PATTERN, this.xmlName); }
Source:
<code>public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm, String role) { <START> checkPermission(configuration, perm, Collections.singletonList(role)); <END> }</code><technical_language>this constructs a new collection for invocation need check for a role (which is majority of cases in code). In invocations substitute (String)null Collections.emptyList()</technical_language>

Target:
public void checkPermission(AuthorizationConfiguration configuration, AuthorizationPermission perm, String role) { if (globalConfiguration.authorization().enabled()) { if (Security.isPrivileged()) { Security.checkPermission(perm.getSecurityPermission()); } else { Subject subject = Security.getSubject(); try { if (subject != null) { if (checkSubjectPermissionAndRole(subject, configuration, perm, role)) { audit.audit(subject, context, name, perm, AuditResponse.ALLOW); } else { checkSecurityManagerPermission(perm); } } else { checkSecurityManagerPermission(perm); } } catch (SecurityException e) { audit.audit(subject, context, name, perm, AuditResponse.DENY); throw log.unauthorizedAccess(Util.prettyPrintSubject(subject), perm.toString()); } } } }
Source:
<code>public synchronized Flux<ByteBuf> getContentAsByteBufFlux() { if (contentAsByteArray == null) { return Flux.empty(); } <START> return Flux.just(Unpooled.wrappedBuffer(contentAsByteArray).retain()); <END> }</code><technical_language>fix a netty ref counting issue. I context. this right place for increasing ref count. Unpooled.wrappedBuffer() sets ref count a zero value. If ref counting issue. I suspect fix elsewhere. here</technical_language>

Target:
public synchronized Flux<ByteBuf> getContentAsByteBufFlux() { if (contentAsByteArray == null) { return Flux.empty(); } return Flux.just(Unpooled.wrappedBuffer(contentAsByteArray)); }
Source:
<code>public boolean hasNext() { if (!getScannerIterator().hasNext() || !more) { try { writer.close(); } catch (MutationsRejectedException e) { log.error(e.toString()); <START> for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) { <END> log.trace(cvs.toString()); } } return false; } return true; }</code><technical_language>this log.isTraceEnabled()</technical_language>

Target:
public boolean hasNext() { if (!getScannerIterator().hasNext() || !more) { try { writer.close(); } catch (MutationsRejectedException e) { log.error(e.toString()); if (Shell.log.isTraceEnabled()) { for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) { log.trace(cvs.toString()); } } } return false; } return true; }
Source:
<code>protected void setUp() throws Exception { super.setUp(); <START> removeLeftOverProjects(); <END> cproject = createProject(isCpp()); tmpDir = cproject.getProject().getLocation().makeAbsolute().toFile(); final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view= activePage.findView("org.eclipse.cdt.ui.tests.DOMAST.DOMAST"); if (view != null) { activePage.hideView(view); } }</code><technical_language>project stuff in baseUiTestCase now? base class</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); final IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart view= activePage.findView("org.eclipse.cdt.ui.tests.DOMAST.DOMAST"); if (view != null) { activePage.hideView(view); } }
Source:
<code>public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: { <START> final String courseId = paramsJson.getString(KEY_COURSE_ID); <END> router.showCourseDashboardTabs(activity, null, courseId, false); break; } case Screen.COURSE_VIDEOS: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); break; } } } }</code><technical_language>I merge this case Screen.COURSE_DASHBOARD</technical_language>

Target:
public static void parseAndReact(@NonNull Activity activity, @NonNull JSONObject paramsJson) throws JSONException { logger.debug("DeepLink received. JSON Details:\n" + paramsJson); final Router router = new Router(); final boolean isLoggedIn = new LoginPrefs(activity).getUsername() != null; if (!isLoggedIn) { activity.startActivity(router.getLogInIntent()); } else { @ScreenDef final String screenName = paramsJson.getString(KEY_SCREEN_NAME); switch (screenName) { case Screen.COURSE_DASHBOARD: case Screen.COURSE_VIDEOS: { final String courseId = paramsJson.getString(KEY_COURSE_ID); router.showCourseDashboardTabs(activity, null, courseId, false, screenName); break; } } } }
Source:
<code><START> public void checkPermissions() { <END> int permission = ContextCompat.checkSelfPermission(MainActivity.this, reqPermission[0]); if (permission == PackageManager.PERMISSION_GRANTED) { setPeData(); } else { ActivityCompat.requestPermissions(MainActivity.this, reqPermission, requestCode); } }</code><technical_language>private, I</technical_language>

Target:
private void checkPermissions() { int permission = ContextCompat.checkSelfPermission(MainActivity.this, reqPermission[0]); if (permission == PackageManager.PERMISSION_GRANTED) { setPeData(); } else { ActivityCompat.requestPermissions(MainActivity.this, reqPermission, requestCode); } }
Source:
<code>public void authorizeResource(String resource, String action, String entityType, String entityName, UserGroupInformation authenticatedUGI) throws AuthorizationException, EntityNotRegisteredException { Validate.notEmpty(resource, "Resource cannot be empty or null"); Validate.isTrue(RESOURCES.contains(resource), "Illegal resource: " + resource); Validate.notEmpty(action, "Action cannot be empty or null"); try { if (isSuperUser(authenticatedUGI)) { return; } if ("admin".equals(resource)) { if (!("version".equals(action) || "clearuser".equals(action) || "getuser".equals(action))) { authorizeAdminResource(authenticatedUGI, action); } } else if ("entities".equals(resource) || "instance".equals(resource)) { authorizeEntityResource(authenticatedUGI, entityName, entityType, action, <START> "entities".equals(resource) && LIST_OPERATION.equals(action)); <END> } else if ("metadata".equals(resource)) { authorizeMetadataResource(authenticatedUGI, action); } } catch (IOException e) { throw new AuthorizationException(e); } }</code><technical_language>is good practice separate out functional logic method calls. a boolean var is set "entities".equals(resource) && LIST_OPERATION.equals(action) in method call</technical_language>

Target:
public void authorizeResource(String resource, String action, String entityType, String entityName, UserGroupInformation authenticatedUGI) throws AuthorizationException, EntityNotRegisteredException { Validate.notEmpty(resource, "Resource cannot be empty or null"); Validate.isTrue(RESOURCES.contains(resource), "Illegal resource: " + resource); Validate.notEmpty(action, "Action cannot be empty or null"); try { if (isSuperUser(authenticatedUGI)) { return; } if ("admin".equals(resource)) { if (!("version".equals(action) || "clearuser".equals(action) || "getuser".equals(action))) { authorizeAdminResource(authenticatedUGI, action); } } else if ("entities".equals(resource) || "instance".equals(resource)) { if ("entities".equals(resource) && LIST_OPERATION.equals(action)) { LOG.info("Skipping authorization for entity list operations"); } else { authorizeEntityResource(authenticatedUGI, entityName, entityType, action); } } else if ("metadata".equals(resource)) { authorizeMetadataResource(authenticatedUGI, action); } } catch (IOException e) { throw new AuthorizationException(e); } }
Source:
<code>public Response getSelfDiscovered() { <START> return Response.ok(Collections.singletonMap("selfDiscovered", selfDiscovered.getAsBoolean())).build(); <END> }</code><technical_language>return 200 OK/503 SERVICE_UNAVAILABLE instead of a JSON response (like HistoricalResource.getReadiness()? Some monitoring checks AWS load balancer health checks able response body. reporting status response code option</technical_language>

Target:
public Response getSelfDiscovered() { if (selfDiscovered.getAsBoolean()) { return Response.ok().build(); } else { return Response.status(HttpStatus.SERVICE_UNAVAILABLE_503).build(); } }
Source:
<code>public JsonNode toJson() { ObjectNode healthCheckResponse = factory.objectNode(); for (Map.Entry<String, HealthCheck.Result> result : healthCheckResults.entrySet()) { ObjectNode resultResponse = factory.objectNode(); resultResponse.put("healthy", result.getValue().isHealthy()); resultResponse.put("message", result.getValue().getMessage()); <START> healthCheckResponse.put(result.getKey(), resultResponse); <END> } return healthCheckResponse; }</code><technical_language>Results arbitrary key/value pairs, too, I nice advantage of</technical_language>

Target:
public JsonNode toJson() { ObjectNode healthCheckResponse = factory.objectNode(); for (Map.Entry<String, HealthCheck.Result> result : healthCheckResults.entrySet()) { ObjectNode resultResponse = factory.objectNode(); resultResponse.put("healthy", result.getValue().isHealthy()); resultResponse.put("message", result.getValue().getMessage()); if (result.getValue().getDetails() != null) { for (Map.Entry<String, Object> entry : result.getValue().getDetails().entrySet()) { if(null != entry.getValue()) { if(entry.getValue() instanceof ObjectNode) { resultResponse.put(entry.getKey(), (ObjectNode)entry.getValue()); } else { resultResponse.put(entry.getKey(), entry.getValue().toString()); } } } } healthCheckResponse.put(result.getKey(), resultResponse); } return healthCheckResponse; }