auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onReceive(Context context, Intent intent) { NotificationHandler.sendNotification(context, context.getString(R.string.local_notifications_text)); TestData.getInstance(context, null); TestData.doNetworkMeasurements(context, "web_connectivity", null); TestData.doNetworkMeasurements(context, "http_invalid_request_line", null); <START> TestData.doNetworkMeasurements(context, "ndt_test", null); <END> }</code><technical_language>@hellais do want run more tests here</technical_language>

Target:
public void onReceive(Context context, Intent intent) { NotificationHandler.sendNotification(context, context.getString(R.string.local_notifications_text)); TestData.getInstance(context, null); TestData.doNetworkMeasurements(context, OONITests.WEB_CONNECTIVITY, null); TestData.doNetworkMeasurements(context, OONITests.HTTP_HEADER_FIELD_MANIPULATION, null); TestData.doNetworkMeasurements(context, OONITests.HTTP_INVALID_REQUEST_LINE, null); TestData.doNetworkMeasurements(context, OONITests.NDT, null); TestData.doNetworkMeasurements(context, OONITests.DASH, null); }
Source:
<code>private void checkIsAuthorizedToReadHistoryAndTenants() { <START> CompositePermissionCheck suspensionStatePermission = new PermissionCheckBuilder() <END> .conjunctive() .atomicCheckForResourceId(PROCESS_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(DECISION_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(TENANT, ANY, READ) .build(); getAuthorizationManager().checkAuthorization(suspensionStatePermission); }</code><technical_language>name of check adjusted</technical_language>

Target:
private void checkIsAuthorizedToReadHistoryAndTenants() { CompositePermissionCheck necessaryPermissionsForOptimize = new PermissionCheckBuilder() .conjunctive() .atomicCheckForResourceId(PROCESS_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(DECISION_DEFINITION, ANY, READ_HISTORY) .atomicCheckForResourceId(TENANT, ANY, READ) .build(); getAuthorizationManager().checkAuthorization(necessaryPermissionsForOptimize); }
Source:
<code>private void appendQueryParameter(String key, Object paramValue, StringBuilder stringBuilder) throws UnsupportedEncodingException { if (paramValue instanceof String) { stringBuilder.append(URLEncoder.encode(key, "UTF-8")); <START> stringBuilder.append("="); <END> stringBuilder.append(URLEncoder.encode((String) paramValue, "UTF-8")); } else if (paramValue.getClass().isArray()) { Class ofArray = paramValue.getClass().getComponentType(); if (ofArray.isPrimitive()) { int length = Array.getLength(paramValue); for (int i = 0; i < length; i++) { appendQueryParameter(key, Array.get(paramValue, i).toString(), stringBuilder); if (i < length - 1) { stringBuilder.append("&"); } } } else { Object[] zeArray = (Object[]) paramValue; for (int i = 0; i < zeArray.length; i++) { appendQueryParameter(key, zeArray[i].toString(), stringBuilder); if (i < zeArray.length - 1) { stringBuilder.append("&"); } } } } else if (paramValue instanceof Collection) { Collection zeCollection = (Collection) paramValue; int index = 0; for (Object paramValueElement : zeCollection) { appendQueryParameter(key, paramValueElement.toString(), stringBuilder); if (index < zeCollection.size() - 1) { stringBuilder.append("&"); } index++; } } else { appendQueryParameter(key, paramValue.toString(), stringBuilder); } }</code><technical_language>suggestion stringBuilder.append('='); for performances</technical_language>

Target:
private void appendQueryParameter(String key, Object paramValue, StringBuilder stringBuilder) throws UnsupportedEncodingException { if (paramValue instanceof String) { stringBuilder.append(URLEncoder.encode(key, "UTF-8")); stringBuilder.append('='); stringBuilder.append(URLEncoder.encode((String) paramValue, "UTF-8")); } else if (paramValue.getClass().isArray()) { Class ofArray = paramValue.getClass().getComponentType(); if (ofArray.isPrimitive()) { int length = Array.getLength(paramValue); for (int i = 0; i < length; i++) { appendQueryParameter(key, Array.get(paramValue, i).toString(), stringBuilder); if (i < length - 1) { stringBuilder.append('&'); } } } else { Object[] zeArray = (Object[]) paramValue; for (int i = 0; i < zeArray.length; i++) { appendQueryParameter(key, zeArray[i].toString(), stringBuilder); if (i < zeArray.length - 1) { stringBuilder.append('&'); } } } } else if (paramValue instanceof Collection) { Collection zeCollection = (Collection) paramValue; int index = 0; for (Object paramValueElement : zeCollection) { appendQueryParameter(key, paramValueElement.toString(), stringBuilder); if (index < zeCollection.size() - 1) { stringBuilder.append('&'); } index++; } } else { appendQueryParameter(key, paramValue.toString(), stringBuilder); } }
Source:
<code>public static String joinWithSeparator(Iterable<?> strings) { <START> return org.apache.hadoop.util.StringUtils.join("]", strings); <END> }</code><technical_language>"]" in a static class variable meaningful name</technical_language>

Target:
public static String joinWithSeparator(Iterable<?> strings) { return org.apache.hadoop.util.StringUtils.join(TXN_WRITE_EVENT_FILE_SEPARATOR, strings); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomFieldDefinition that = (CustomFieldDefinition) o; <START> if (id != that.id) { <END> return false; } return true; }</code><technical_language>This is identity comparison. Equal (in sense of .equals()) Integers == (and !=). Please, .equals provide proper null-handling code</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomFieldDefinition that = (CustomFieldDefinition) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; return true; }
Source:
<code>public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) { Map<String, HashCode> classNames = new HashMap<>(); for (String line : lines) { <START> int index = line.trim().lastIndexOf(CLASS_NAME_HASH_CODE_SEPARATOR); <END> String key = line.substring(0, index); HashCode value = HashCode.fromString(line.substring(index + 1)); HashCode existing = classNames.putIfAbsent(key, value); if (existing != null && !existing.equals(value)) { throw new IllegalArgumentException( String.format( "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s", key, value, existing)); } } return ImmutableSortedMap.copyOf(classNames, Ordering.natural()); }</code><technical_language>trim necessary creates a copy. precondition check index > 0</technical_language>

Target:
public static ImmutableSortedMap<String, HashCode> parseClassHashes(List<String> lines) { Map<String, HashCode> classNames = new HashMap<>(); for (String line : lines) { int index = line.lastIndexOf(CLASS_NAME_HASH_CODE_SEPARATOR); Preconditions.checkArgument(index > 0, "Class names and hashcodes malformed: %1$s", line); String key = line.substring(0, index); HashCode value = HashCode.fromString(line.substring(index + 1)); HashCode existing = classNames.putIfAbsent(key, value); if (existing != null && !existing.equals(value)) { throw new IllegalArgumentException( String.format( "Multiple entries with same key but differing values: %1$s=%2$s and %1$s=%3$s", key, value, existing)); } } return ImmutableSortedMap.copyOf(classNames, Ordering.natural()); }
Source:
<code>private void push(Repository repo, ReplicaPushRequest req) throws NotSupportedException, TransportException, IOException { Map<String, Ref> adv; List<RemoteCommand> cmds = asUpdateList(req.getCommands()); Transport <START> tn = <END> Transport.open(repo, uri); try { RemoteConfig rc = getRemoteConfig(); if (rc != null) { tn.applyConfig(rc); } tn.setPushAtomic(true); adv = push(repo, tn, cmds); } finally { tn.close(); } for (RemoteCommand c : cmds) { c.copyStatusToResult(); } req.setRefs(adv); }</code><technical_language>s/tn/transport/ Also, try resources</technical_language>

Target:
private void push(Repository repo, ReplicaPushRequest req) throws NotSupportedException, TransportException, IOException { Map<String, Ref> adv; List<RemoteCommand> cmds = asUpdateList(req.getCommands()); try (Transport transport = Transport.open(repo, uri)) { RemoteConfig rc = getRemoteConfig(); if (rc != null) { transport.applyConfig(rc); } transport.setPushAtomic(true); adv = push(repo, transport, cmds); } for (RemoteCommand c : cmds) { c.copyStatusToResult(); } req.setRefs(adv); }
Source:
<code><START> public AggStatsProcessor(final SleepStatsDAODynamoDB sleepStatsDAODynamoDB, <END> final PillDataDAODynamoDB pillDataDAODynamoDB, final DeviceDataDAODynamoDB deviceDataDAODynamoDB, final SenseColorDAO senseColorDAO, final CalibrationDAO calibrationDAO, final AggStatsDAODynamoDB aggStatsDAODynamoDB) { this.sleepStatsDAODynamoDB = sleepStatsDAODynamoDB; this.pillDataDAODynamoDB = pillDataDAODynamoDB; this.deviceDataDAODynamoDB = deviceDataDAODynamoDB; this.senseColorDAO = senseColorDAO; this.calibrationDAO = calibrationDAO; this.aggStatsDAODynamoDB = aggStatsDAODynamoDB; }</code><technical_language>private a builder</technical_language>

Target:
private AggStatsProcessor(final SleepStatsDAODynamoDB sleepStatsDAODynamoDB, final PillDataDAODynamoDB pillDataDAODynamoDB, final DeviceDataDAODynamoDB deviceDataDAODynamoDB, final SenseColorDAO senseColorDAO, final CalibrationDAO calibrationDAO, final AggStatsDAODynamoDB aggStatsDAODynamoDB) { this.sleepStatsDAODynamoDB = sleepStatsDAODynamoDB; this.pillDataDAODynamoDB = pillDataDAODynamoDB; this.deviceDataDAODynamoDB = deviceDataDAODynamoDB; this.senseColorDAO = senseColorDAO; this.calibrationDAO = calibrationDAO; this.aggStatsDAODynamoDB = aggStatsDAODynamoDB; }
Source:
<code>public void deleteGroupUnauthorizedTest() throws Exception { GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); Group parentGroup = null; try { context.turnOffAuthorisationSystem(); parentGroup = groupService.create(context); context.commit(); <START> parentGroup = context.reloadEntity(parentGroup); <END> String authToken = getAuthToken(admin.getEmail(), password); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); getClient().perform( delete("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isUnauthorized()); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); } finally { if (parentGroup != null) { GroupBuilder.deleteGroup(parentGroup.getID()); } } }</code><technical_language>above. GroupBuilder, missing a context.restoreAuthSystemState(); question commit() reloadEntity() above</technical_language>

Target:
public void deleteGroupUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); Group parentGroup = GroupBuilder.createGroup(context) .withName("test group") .build(); context.restoreAuthSystemState(); String authToken = getAuthToken(admin.getEmail(), password); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); getClient().perform( delete("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isUnauthorized()); getClient(authToken).perform( get("/api/eperson/groups/" + parentGroup.getID()) ).andExpect(status().isOk()); }
Source:
<code>public void emitTuples() { if (tupleCount < totalTupleCount) { DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); Date date = new Date(); <START> String xmlSample = "<?xml version=\"1.0\"?>" + "<EmployeeBean>" <END> + "<name>employee" + tupleCount + "</name>" + "<dept>department" + tupleCount + "</dept>" + "<eid>" + tupleCount +"</eid>" + "<dateOfJoining>2015-01-01</dateOfJoining>" + "<address>" + "<city>new york</city>" +"<country>US</country>" + "</address>" + "</EmployeeBean>"; System.out.println(xmlSample); output.emit(xmlSample); tupleCount++; } }</code><technical_language>StringBuffer for this</technical_language>

Target:
public void emitTuples() { if (tupleCount < totalTupleCount) { StringBuilder xmlSample = new StringBuilder(); xmlSample.append("<?xml version=\"1.0\"?>"); xmlSample.append("<EmployeeBean>"); xmlSample.append("<name>employee" + tupleCount + "</name>"); xmlSample.append("<dept>department"+ tupleCount + "</dept>"); xmlSample.append("<eid>" + tupleCount +"</eid>"); xmlSample.append("<dateOfJoining>2015-01-01</dateOfJoining>"); xmlSample.append("<address>"+ "<city>new york</city>"); xmlSample.append("<country>US</country>" +"</address>"); xmlSample.append("</EmployeeBean>"); output.emit(xmlSample.toString()); tupleCount++; } }
Source:
<code>public static S3WriterConfiguration detectWriterConfiguration(Config s3) { S3WriterConfiguration s3Configuration = null; try { s3Configuration = mapper.readValue(s3.root().render(ConfigRenderOptions.concise()), S3WriterConfiguration.class); if(!s3Configuration.getWriterPath().endsWith("/")) { s3Configuration.setWriterPath(s3Configuration.getWriterPath() + "/"); } } catch (Exception e) { <START> e.printStackTrace(); <END> LOGGER.warn("Could not parse S3Configuration"); } return s3Configuration; }</code><technical_language>in here, remove e.printStackTrace(). If exception needs output console, needs output logs</technical_language>

Target:
public static S3WriterConfiguration detectWriterConfiguration(Config s3) { S3WriterConfiguration s3Configuration = null; try { s3Configuration = mapper.readValue(s3.root().render(ConfigRenderOptions.concise()), S3WriterConfiguration.class); if(!s3Configuration.getWriterPath().endsWith("/")) { s3Configuration.setWriterPath(s3Configuration.getWriterPath() + "/"); } } catch (Exception e) { LOGGER.warn("Could not parse S3Configuration", e); } return s3Configuration; }
Source:
<code>public void testDelete() { Mono<LongIdDomainPartition> saveMono = this.repository.save(DOMAIN_1); <START> StepVerifier.create(saveMono).thenConsumeWhile(domain -> true).expectComplete().verify(); <END> Mono<Void> deleteMono = this.repository.delete(DOMAIN_1); StepVerifier.create(deleteMono).verifyComplete(); Mono<Long> countMono = repository.count(); StepVerifier.create(countMono).expectNext(1L).verifyComplete(); }</code><technical_language>expectNext = DOMAIN_1</technical_language>

Target:
public void testDelete() { Mono<LongIdDomainPartition> saveMono = this.repository.save(DOMAIN_1); StepVerifier.create(saveMono).expectNext(DOMAIN_1).expectComplete().verify(); Mono<Void> deleteMono = this.repository.delete(DOMAIN_1); StepVerifier.create(deleteMono).verifyComplete(); Mono<Long> countMono = repository.count(); StepVerifier.create(countMono).expectNext(1L).verifyComplete(); }
Source:
<code>private Resource loadResource(String name) throws IOException { Path p = staticBase.resolve(name); try { p = p.toRealPath().normalize(); } catch (IOException e) { return Resource.NOT_FOUND; } if (!p.startsWith(staticBase)) { return Resource.NOT_FOUND; } <START> long ts = Files.getLastModifiedTime(p).toMillis(); <END> byte[] raw; try (InputStream in = Files.newInputStream(p)) { raw = ByteStreams.toByteArray(in); } catch (FileNotFoundException e) { return Resource.NOT_FOUND; } return new Resource(p, ts, contentType(name), raw); }</code><technical_language>Do callers handle NoSuchFileException Resource.NOT_FOUND? Consider FileUtils.lastModified() instead</technical_language>

Target:
private Resource loadResource(String name) throws IOException { Path p = staticBase.resolve(name); try { p = p.toRealPath().normalize(); } catch (IOException e) { return Resource.NOT_FOUND; } if (!p.startsWith(staticBase)) { return Resource.NOT_FOUND; } long ts = FileUtil.lastModified(p); byte[] raw; try { raw = Files.readAllBytes(p); } catch (NoSuchFileException e) { return Resource.NOT_FOUND; } return new Resource(p, ts, contentType(name), raw); }
Source:
<code>public void retrieve(@PathVariable UUID uuid, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException { Context context = ContextUtil.obtainContext(request); Bitstream bit = getBitstreamIfAuthorized(context, uuid, response); if (bit == null) { return; } Long lastModified = bitstreamService.getLastModified(bit); String mimetype = bit.getFormat(context).getMIMEType(); try(InputStream is = getInputStream(context, bit)) { MultipartFileSender sender = MultipartFileSender .fromInputStream(is) .withBufferSize(bufferSize) .withFileName(bit.getName()) .withLength(bit.getSize()) .withChecksum(bit.getChecksum()) .withMimetype(mimetype) .withLastModified(lastModified) .with(request) .with(response); if (sender.isValid()) { sender.serveResource(); } if (sender.isNoRangeRequest() && isNotAnErrorResponse(response)) { eventService.fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, <START> bit)); <END> } } catch(IOException ex) { log.debug("Client aborted the request before the download was completed. Client is probably switching to a Range request.", ex); } catch (Exception e) { log.error(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }</code><technical_language>that? IOException occur if issue read underline storage. If client abort request exception occur Servlet container stack writing response is in some "buffered" tomcat, etc. (I admit I check)</technical_language>

Target:
public void retrieve(@PathVariable UUID uuid, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException, AuthorizeException { Context context = ContextUtil.obtainContext(request); Bitstream bit = getBitstream(context, uuid, response); if (bit == null) { return; } Long lastModified = bitstreamService.getLastModified(bit); String mimetype = bit.getFormat(context).getMIMEType(); try(InputStream is = bitstreamService.retrieve(context, bit)) { MultipartFileSender sender = MultipartFileSender .fromInputStream(is) .withBufferSize(BUFFER_SIZE) .withFileName(bit.getName()) .withLength(bit.getSize()) .withChecksum(bit.getChecksum()) .withMimetype(mimetype) .withLastModified(lastModified) .with(request) .with(response); if (sender.isNoRangeRequest() && isNotAnErrorResponse(response)) { eventService.fireEvent( new UsageEvent( UsageEvent.Action.VIEW, request, context, bit)); } context.complete(); if (sender.isValid()) { sender.serveResource(); } } catch(ClientAbortException ex) { log.debug("Client aborted the request before the download was completed. Client is probably switching to a Range request.", ex); } }
Source:
<code>private void signInAnonymously() { Toast.makeText(this, "Signing in...", Toast.LENGTH_SHORT).show(); mAuth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { attachRecyclerViewAdapter(); } }) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { <START> Toast.makeText(getApplicationContext(), <END> R.string.signed_in, Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(getApplicationContext(), R.string.sign_in_failed, Toast.LENGTH_SHORT) .show(); } } }); }</code><technical_language>remove call attachRecyclerViewAdapter() here? if scope onComplete listener Activity context avoid dead activity issues</technical_language>

Target:
private void signInAnonymously() { Toast.makeText(this, "Signing in...", Toast.LENGTH_SHORT).show(); mAuth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult result) { attachRecyclerViewAdapter(); } }) .addOnCompleteListener(new SignInResultNotifier(this)); }
Source:
<code><START> public void runToLocation(Location location) { <END> if (isConnected()) { for (DebuggerObserver observer : observers) { observer.onPreResume(); } removeCurrentLocation(); preserveDebuggerState(); RunToLocationActionDto action = dtoFactory .createDto(RunToLocationActionDto.class) .withType(Action.TYPE.RUN_TO_LOCATION) .withTarget(location.getTarget()) .withLineNumber(location.getLineNumber()); Promise<Void> promise = service.runToLocation(debugSessionDto.getId(), action); promise.catchError( error -> { Log.error(AbstractDebugger.class, error.getCause()); }); } }</code><technical_language>reconsidered a lot. is a pitfall if location executable. get rid of server side changes support RunToCursor action for debugger implementation</technical_language>

Target:
public void runToLocation(Location location) { if (!isConnected()) { return; } if (disposableBreakpoint != null) { return; } disposableBreakpoint = dtoFactory.createDto(BreakpointDto.class).withLocation(toDto(location)).withEnabled(true); service .addBreakpoint(debugSessionDto.getId(), disposableBreakpoint) .then( it -> { preserveDebuggerState(); resume(); }) .catchError( error -> { service .deleteBreakpoint(debugSessionDto.getId(), disposableBreakpoint.getLocation()) .catchError( err -> { Log.error(AbstractDebugger.class, err.getMessage()); }); invalidateDisposableBreakpoint(); preserveDebuggerState(); }); }
Source:
<code><START> public void add(RevCommit revCommit) { <END> Assert.isNotNull(revCommit); checkWidget(); String shortSha1 = revCommit.getName().substring(0, 6); String message = shortSha1 + ": " + revCommit.getShortMessage(); combo.add(message); commits.add(new ComboCommitEnt(revCommit.getId(), message)); }</code><technical_language>public</technical_language>

Target:
public void add(RevCommit revCommit) { Assert.isNotNull(revCommit); checkWidget(); String shortSha1 = revCommit.getName().substring(0, 8); String message = shortSha1 + ": " + revCommit.getShortMessage(); combo.add(message); commits.add(new ComboCommitEnt(revCommit.getId(), message)); }
Source:
<code>public void initialize(DataManager manager, ARXConfiguration config){ if (beta < 0) { <START> double epsilonAnon = epsilon - (isDataDependent() ? config.getDPSearchBudget() : 0d); <END> ParameterCalculation pCalc = null; try { pCalc = new ParameterCalculation(epsilonAnon, delta); } catch (IntervalArithmeticException e) { throw new RuntimeException(e); } beta = pCalc.getBeta(); k = pCalc.getK(); } if (subset == null || initialized) { Random random = deterministic ? new Random(0xDEADBEEF) : new SecureRandom(); Set<Integer> subsetIndices = new HashSet<Integer>(); int numRecords = manager.getDataGeneralized().getDataLength(); for (int i = 0; i < numRecords; ++i) { if (random.nextDouble() < beta) { subsetIndices.add(i); } } this.subset = DataSubset.create(numRecords, subsetIndices); } initialized = true; }</code><technical_language>a reliable calculation, errors small</technical_language>

Target:
public void initialize(DataManager manager, ARXConfiguration config){ if (beta < 0) { double epsilonAnon = epsilon; if (isDataDependent()) { try { IntervalArithmeticDouble ia = new IntervalArithmeticDouble(); epsilonAnon = ia.sub(ia.createInterval(epsilon), ia.createInterval(config.getDPSearchBudget())).lower; } catch (IntervalArithmeticException e) { throw new RuntimeException(e); } } ParameterCalculation pCalc = null; try { pCalc = new ParameterCalculation(epsilonAnon, delta); } catch (IntervalArithmeticException e) { throw new RuntimeException(e); } beta = pCalc.getBeta(); k = pCalc.getK(); } if (subset == null || initialized) { Random random = deterministic ? new Random(0xDEADBEEF) : new SecureRandom(); Set<Integer> subsetIndices = new HashSet<Integer>(); int numRecords = manager.getDataGeneralized().getDataLength(); for (int i = 0; i < numRecords; ++i) { if (random.nextDouble() < beta) { subsetIndices.add(i); } } this.subset = DataSubset.create(numRecords, subsetIndices); } initialized = true; }
Source:
<code>public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(Exceptions.propagate(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) <START> .filter(t -> !t.isExpired()); <END> }</code><technical_language>Do expect MSAL return expired token</technical_language>

Target:
public Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestContext request) { return Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); try { return getConfidentialClientApplication().acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e))); } }).map(ar -> (AccessToken) new MsalToken(ar, options)) .filter(t -> !t.isExpired()); }
Source:
<code>public Result updateEmail() { JsonNode json = request().body().asJson(); if (!validateUpdateEmailParameters(json)) { return badRequest(EMAIL_EXPECTED); } String actualEmail = session().get(ConstantsManager.COOKIE_SESSION_FIELD_NAME); String newEmail = json.get(ConstantsManager.USERNAME_FIELD_NAME).asText(); try { User user = userDao.findByEmail(actualEmail); <START> user.setEmail(newEmail); <END> userDao.update(user); session().put(ConstantsManager.COOKIE_SESSION_FIELD_NAME, newEmail); return ok(); } catch (RecordNotFoundException e) { return unauthorized(BAD_SESSION_WRONG_USERNAME); } catch (ValidationException e) { return unauthorized(EMAIL_SHOULD_BE_UNIQUE); } }</code><technical_language>cool :+1:</technical_language>

Target:
public Result updateEmail() { JsonNode json = request().body().asJson(); if (!validateUpdateEmailParameters(json)) { return badRequest(EMAIL_EXPECTED); } String actualEmail = session().get(ConstantsManager.COOKIE_SESSION_FIELD_NAME); String newEmail = json.get(ConstantsManager.USERNAME_FIELD_NAME).asText(); try { User user = userDao.findByEmail(actualEmail); user.setEmail(newEmail); userDao.update(user); session().put(ConstantsManager.COOKIE_SESSION_FIELD_NAME, newEmail); return ok(); } catch (RecordNotFoundException e) { return unauthorized(BAD_SESSION_WRONG_USERNAME); } catch (UniqueValidationException e) { return unauthorized(EMAIL_SHOULD_BE_UNIQUE); } catch (ConstraintViolationException e) { return unauthorized(EMAIL_IS_INVALID); } }
Source:
<code>public void nextJsonObject_SingleElement() throws JsonParseException, IOException { String content = normalizeJson("{bre: 'sss', arr:['1112', 'abc']}"); JsonParser jsonParser = jsonFactory.createParser(content); JsonToken jsonToken = jsonUtils.nextJsonObject(jsonParser); assertNotNull(jsonToken); <START> assertEquals(content.replaceAll("\\s", ""), jsonParser.readValueAsTree().toString()); <END> assertNull(jsonUtils.nextJsonObject(jsonParser)); }</code><technical_language>need replaceAll, normalizeJson</technical_language>

Target:
public void nextJsonObject_SingleElement() throws JsonParseException, IOException { String content = normalizeJson("{bre: 'sss', arr:['1112', 'abc']}"); JsonParser jsonParser = jsonFactory.createParser(content); JsonToken jsonToken = jsonUtils.nextJsonObject(jsonParser); assertNotNull(jsonToken); assertEquals(content, jsonParser.readValueAsTree().toString()); assertNull(jsonUtils.nextJsonObject(jsonParser)); }
Source:
<code>public void onPlayerJoin(PlayerJoinEvent event) { skinUpdateTracker.updatePlayer(event.getPlayer(), 6 * 20, true); for (NPC npc : getAllNPCs()) { String teamName = npc.data().get(NPC.SCOREBOARD_FAKE_TEAM_NAME_METADATA, ""); Team team = null; if (!(npc.getEntity() instanceof Player) || teamName.length() == 0 || (team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(teamName)) == null) return; <START> if (Setting.USE_SCOREBOARD_TEAMS.asBoolean()) { <END> NMS.sendTeamPacket(event.getPlayer(), team); } } }</code><technical_language>This pulled out of loop</technical_language>

Target:
public void onPlayerJoin(PlayerJoinEvent event) { skinUpdateTracker.updatePlayer(event.getPlayer(), 6 * 20, true); if (Setting.USE_SCOREBOARD_TEAMS.asBoolean()) { for (NPC npc : getAllNPCs()) { if (!(npc.getEntity() instanceof Player)) { continue; } String teamName = npc.data().get(NPC.SCOREBOARD_FAKE_TEAM_NAME_METADATA, ""); Team team = null; if (teamName.length() == 0 || (team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(teamName)) == null) continue; NMS.sendTeamPacket(event.getPlayer(), team); } } }
Source:
<code>public static List<Path> listDirectoryFiles(Path dir) throws IOException { <START> try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, FILE_FILTER)) { <END> return Lists.newArrayList(entries); } }</code><technical_language>do feel public method regularFileFIlter in place of referencing constant directly? easier for users copy approach in libraries</technical_language>

Target:
public static List<Path> listDirectoryFiles(Path dir) throws IOException { try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, regularFileFilter())) { return Lists.newArrayList(entries); } }
Source:
<code>public static String formatDate(Date dateToformat) { try { DataverseLocaleBean d = new DataverseLocaleBean(); Locale bundle_locale = new Locale(d.getLocaleCode()); String formattedDate = ""; <START> if(bundle_locale.getLanguage().contains("fr")) <END> { DateFormat df = new SimpleDateFormat("dd MMM yyyy",bundle_locale); formattedDate = df.format(dateToformat); } else { DateFormat df = new SimpleDateFormat("MMM dd, yyyy", bundle_locale); formattedDate = df.format(dateToformat); } return formattedDate; } catch(Exception e) { return null; } }</code><technical_language>world's population (*Wikipedia: <LINK_0> "dd MMM yyyy" format, a more scalable solution hardcoding "fr" here. @scolapasta some more detailed insight share</technical_language>

Target:
public static String formatDate(Date dateToformat) { String formattedDate; DateFormat dateFormatter; try { DataverseLocaleBean d = new DataverseLocaleBean(); Locale currentLocale = new Locale(d.getLocaleCode()); dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale); formattedDate = dateFormatter.format(dateToformat); return formattedDate; } catch(Exception e) { return null; } }
Source:
<code>public OvsdbVtepBackend(OvsdbClient client) throws Exception { this.client = client; this.endPoint = endPointFromOvsdbClient(client); try { DatabaseSchema dbs = getDbSchema( client, DB_HARDWARE_VTEP).result(Duration.Inf()); this.lsTable = new LogicalSwitchTable( dbs, getTblSchema(dbs, <START> TB_LOGICAL_SWITCH)); <END> this.psTable = new PhysicalSwitchTable( dbs, getTblSchema(dbs, TB_PHYSICAL_SWITCH)); this.plSetTable = new PhysicalLocatorSetTable( dbs, getTblSchema(dbs, TB_PHYSICAL_LOCATOR_SET)); this.plTable = new PhysicalLocatorTable( dbs, getTblSchema(dbs, TB_PHYSICAL_LOCATOR)); this.uMacsLocalTable = new UcastMacsTable( dbs, getTblSchema(dbs, TB_UCAST_MACS_LOCAL)); this.uMacsRemoteTable = new UcastMacsTable( dbs, getTblSchema(dbs, TB_UCAST_MACS_REMOTE)); this.mMacsLocalTable = new McastMacsTable( dbs, getTblSchema(dbs, TB_MCAST_MACS_LOCAL)); this.mMacsRemoteTable = new McastMacsTable( dbs, getTblSchema(dbs, TB_MCAST_MACS_REMOTE)); this.pSwitch = retrievePhysicalSwitch(this.endPoint.mgmtIp()); } catch(NoSuchElementException exc) { throw new VtepUnsupportedException(this.endPoint, exc); } catch(TimeoutException tOut) { throw new VtepException(this.endPoint, tOut); } }</code><technical_language>constants live in Table classes instead? weird pass in</technical_language>

Target:
public OvsdbVtepBackend(OvsdbClient client) throws Exception { this.client = client; this.endPoint = endPointFromOvsdbClient(client); try { DatabaseSchema dbs = getDbSchema( client, DB_HARDWARE_VTEP).result(Duration.Inf()); this.lsTable = new LogicalSwitchTable(dbs); this.psTable = new PhysicalSwitchTable(dbs); this.plSetTable = new PhysicalLocatorSetTable(dbs); this.plTable = new PhysicalLocatorTable(dbs); this.uMacsLocalTable = new UcastMacsLocalTable(dbs); this.uMacsRemoteTable = new UcastMacsRemoteTable(dbs); this.mMacsLocalTable = new McastMacsLocalTable(dbs); this.mMacsRemoteTable = new McastMacsRemoteTable(dbs); this.pSwitch = retrievePhysicalSwitch(this.endPoint.mgmtIp()); } catch(NoSuchElementException exc) { throw new VtepUnsupportedException(this.endPoint, exc); } catch(TimeoutException tOut) { throw new VtepException(this.endPoint, tOut); } }
Source:
<code>public void fillCommonCourtFieldsToItemRepresentation(Item item, CommonCourt court){ item.setId(court.getId()); item.setName(court.getName()); item.setType(court.getType()); item.setCode(court.getCode()); if(court.getParentCourt()!=null){ DumpCourtsView.ParentCourt parentCourt = new DumpCourtsView.ParentCourt(); parentCourt.setId(court.getParentCourt().getId()); item.setParentCourt(parentCourt); <START> } <END> item.setDivisions(toDivisions(court.getDivisions())); }</code><technical_language>moving this if statement separate method? j) :+1:</technical_language>

Target:
public void fillCommonCourtFieldsToItemRepresentation(Item item, CommonCourt court){ item.setId(court.getId()); item.setName(court.getName()); item.setType(court.getType()); item.setCode(court.getCode()); item.setParentCourt(toParentCourt(court.getParentCourt())); item.setDivisions(toDivisions(court.getDivisions())); }
Source:
<code>public MavenDependencyResolver() { <START> this(System.getProperty("robolectric.dependency.repo.url", "<LINK_0>"), <END> System.getProperty("robolectric.dependency.repo.id", "sonatype")); }</code><technical_language>move System.getProperty calls methods RoboSettings? a central place hold system properties</technical_language>

Target:
public MavenDependencyResolver() { this(RoboSettings.getMavenRepositoryUrl(), RoboSettings.getMavenRepositoryId()); }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation representation) { if (representation instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); <START> description.addProperty("uuid"); <END> description.addProperty("diagnosis"); description.addProperty("patient", Representation.REF); description.addProperty("condition"); description.addProperty("encounter"); description.addProperty("certainty"); description.addProperty("rank"); description.addProperty("voided"); description.addProperty("display"); description.addSelfLink(); return description; } else if (representation instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("diagnosis"); description.addProperty("patient", Representation.REF); description.addProperty("condition"); description.addProperty("encounter"); description.addProperty("certainty"); description.addProperty("rank"); description.addProperty("voided"); description.addProperty("auditInfo"); description.addProperty("display"); description.addSelfLink(); return description; } return null; }</code><technical_language>For default representation, add Representation.REF for diagnosis, condition, encounter</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation representation) { if (representation instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("diagnosis", Representation.REF); description.addProperty("condition", Representation.REF); description.addProperty("encounter", Representation.REF); description.addProperty("certainty"); description.addProperty("rank"); description.addProperty("voided"); description.addProperty("display"); description.addProperty("patient", Representation.REF); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); description.addSelfLink(); return description; } else if (representation instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("diagnosis"); description.addProperty("patient", Representation.REF); description.addProperty("condition"); description.addProperty("encounter"); description.addProperty("certainty"); description.addProperty("rank"); description.addProperty("voided"); description.addProperty("auditInfo"); description.addProperty("display"); description.addSelfLink(); return description; } return null; }
Source:
<code>public KafkaWriterFactory( @JsonProperty("producerConfig") @Nonnull Map<String, Object> producerConfig, @JsonProperty("topic") @Nonnull String topic, <START> @JsonProperty("resultSerializer") ResultSerializer resultSerializer) { <END> this.objectMapper = new ObjectMapper(); checkNotNull(producerConfig); ImmutableMap.Builder<String, Object> producerConfigBuilder = ImmutableMap.<String, Object>builder() .putAll(producerConfig); if (!producerConfig.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) { producerConfigBuilder.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER_CLASS); } if (!producerConfig.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) { producerConfigBuilder.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER_CLASS); } this.producerConfig = producerConfigBuilder.build(); this.topic = topic; checkNotNull(topic); this.resultSerializer = resultSerializer == null ? new DefaultResultSerializer( Collections.<String>emptyList(), false, "", Collections.<String,String> emptyMap()) : resultSerializer; }</code><technical_language>prefer expose ResultSerializer a JsonProperty, exposing simple key values in Factories choosing correct class in implementation. This easier refactor code road, while preserving original configuration interface</technical_language>

Target:
public KafkaWriterFactory( @JsonProperty("producerConfig") @Nonnull Map<String, Object> producerConfig, @JsonProperty("topic") @Nonnull String topic, @JsonProperty("resultSerializer") ResultSerializer resultSerializer) { this.objectMapper = new ObjectMapper(); ImmutableMap.Builder<String, Object> producerConfigBuilder = ImmutableMap.<String, Object>builder() .putAll(producerConfig); if (!producerConfig.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) { producerConfigBuilder.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER_CLASS); } if (!producerConfig.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)) { producerConfigBuilder.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, STRING_SERIALIZER_CLASS); } this.producerConfig = producerConfigBuilder.build(); this.topic = topic; checkNotNull(topic); this.resultSerializer = resultSerializer == null ? new DefaultResultSerializer( Collections.<String>emptyList(), false, "", Collections.<String, String>emptyMap()) : resultSerializer; }
Source:
<code>public static String formatForUtcTime(final Date date) { <START> final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); <END> dateFormat.setTimeZone(TimeZone.getTimeZone(TIMEZONE)); return dateFormat.format(date); }</code><technical_language>Refactor lines 78 79 a common private method methods. (this below)</technical_language>

Target:
public static String formatForUtcTime(final Date date) { return createDateFormat().format(date); }
Source:
<code><START> private ClouderaManagerClusterConfigurationMonitor getConfigurationChangeMonitor() { <END> ClouderaManagerClusterConfigurationMonitor cmMonitor = null; try { Class<?> clazz = Class.forName(GATEWAY_SERVICES_ACCESSOR_CLASS); if (clazz != null) { Method m = clazz.getDeclaredMethod(GATEWAY_SERVICES_ACCESSOR_METHOD); if (m != null) { Object obj = m.invoke(null); if (GatewayServices.class.isAssignableFrom(obj.getClass())) { ClusterConfigurationMonitorService clusterMonitorService = ((GatewayServices) obj).getService(ServiceType.CLUSTER_CONFIGURATION_MONITOR_SERVICE); ClusterConfigurationMonitor monitor = clusterMonitorService.getMonitor(ClouderaManagerClusterConfigurationMonitor.getType()); if (monitor != null && ClouderaManagerClusterConfigurationMonitor.class.isAssignableFrom(monitor.getClass())) { cmMonitor = (ClouderaManagerClusterConfigurationMonitor) monitor; } } } } } catch (Exception e) { log.errorAccessingConfigurationChangeMonitor(e); } return cmMonitor; }</code><technical_language>I thought GatewayServices is a public static object is accessible GatewayServer elsewhere. I need this effort try reflection here</technical_language>

Target:
private ClouderaManagerClusterConfigurationMonitor getConfigurationChangeMonitor() { ClouderaManagerClusterConfigurationMonitor cmMonitor = null; try { GatewayServices gwServices = GatewayServer.getGatewayServices(); if (gwServices != null) { ClusterConfigurationMonitorService clusterMonitorService = GatewayServer.getGatewayServices().getService(ServiceType.CLUSTER_CONFIGURATION_MONITOR_SERVICE); ClusterConfigurationMonitor monitor = clusterMonitorService.getMonitor(ClouderaManagerClusterConfigurationMonitor.getType()); if (monitor != null && ClouderaManagerClusterConfigurationMonitor.class.isAssignableFrom(monitor.getClass())) { cmMonitor = (ClouderaManagerClusterConfigurationMonitor) monitor; } } } catch (Exception e) { log.errorAccessingConfigurationChangeMonitor(e); } return cmMonitor; }
Source:
<code>private Object toValue(final Object baseInstance, final JsonValue jsonValue, final Adapter converter, final Adapter itemConverter, final Type type, final ObjectConverter.Reader objectConverter, final JsonPointerTracker jsonPointer, final Type rootType) { if (objectConverter != null) { <START> if (EnumSet.of(ValueType.OBJECT, ValueType.NUMBER, ValueType.STRING, ValueType.FALSE, ValueType.TRUE).contains(jsonValue.getValueType())) { <END> return objectConverter.fromJson(jsonValue, type, this); } else if (jsonValue instanceof JsonArray) { return buildArray(type, jsonValue.asJsonArray(), itemConverter, objectConverter, jsonPointer, rootType); } else { throw new UnsupportedOperationException("Array handling with ObjectConverter currently not implemented"); } } try { return converter == null ? toObject(baseInstance, jsonValue, type, itemConverter, jsonPointer, rootType) : jsonValue.getValueType() == JsonValue.ValueType.STRING ? converter.to(JsonString.class.cast(jsonValue).getString()) : convertTo(converter, jsonValue, jsonPointer); } catch (Exception e) { if (e instanceof MapperException) { throw e; } throw new MapperException(e); } }</code><technical_language>isnt simpler reversing test (if array => else =>)</technical_language>

Target:
private Object toValue(final Object baseInstance, final JsonValue jsonValue, final Adapter converter, final Adapter itemConverter, final Type type, final ObjectConverter.Reader objectConverter, final JsonPointerTracker jsonPointer, final Type rootType) { if (objectConverter != null) { if (jsonValue instanceof JsonArray) { return buildArray(type, jsonValue.asJsonArray(), itemConverter, objectConverter, jsonPointer, rootType); } else { return objectConverter.fromJson(jsonValue, type, this); } } try { return converter == null ? toObject(baseInstance, jsonValue, type, itemConverter, jsonPointer, rootType) : jsonValue.getValueType() == JsonValue.ValueType.STRING ? converter.to(JsonString.class.cast(jsonValue).getString()) : convertTo(converter, jsonValue, jsonPointer); } catch (Exception e) { if (e instanceof MapperException) { throw e; } throw new MapperException(e); } }
Source:
<code>private String read(BitBuffer input) throws CTFReaderException { alignRead(input); StringBuilder sb = new StringBuilder(); char c = (char) input.get(BITS_PER_BYTE, false); while (c != 0) { sb.append(c); c = (char) input.get(BITS_PER_BYTE, false); } @SuppressWarnings("null") @NonNull <START> String string = sb.toString(); <END> return string; }</code><technical_language>new NonNullUtils, #nullToEmptyString() #checkNotNull</technical_language>

Target:
private String read(BitBuffer input) throws CTFReaderException { alignRead(input); StringBuilder sb = new StringBuilder(); char c = (char) input.get(BITS_PER_BYTE, false); while (c != 0) { sb.append(c); c = (char) input.get(BITS_PER_BYTE, false); } return NonNullUtils.checkNotNull(sb.toString()); }
Source:
<code>public String Nc4Version() { try { <START> Class com_sun_jan_Native = Class.forName("com.sun.jna.Native"); <END> Method loadLibrary_method = com_sun_jan_Native.getMethod("loadLibrary", String.class, Class.class); Object nc4 = loadLibrary_method.invoke(null, "netcdf", Nc4prototypes.class); Method nc_inq_libvers_method = Nc4prototypes.class.getMethod("nc_inq_libvers"); String version = (String) nc_inq_libvers_method.invoke(nc4); return version; } catch (Exception e) { return "unavailable (" + e.getClass() + ":" + e.getMessage() + ")"; } }</code><technical_language>This indentation a wonky - tabs hiding in here</technical_language>

Target:
public String Nc4Version() { try { Class jnaNativeClass = Class.forName("com.sun.jna.Native"); Method loadLibraryMethod = jnaNativeClass.getMethod("loadLibrary", String.class, Class.class); Object nc4 = loadLibraryMethod.invoke(null, "netcdf", Nc4prototypes.class); Method nc_inq_libversMethod = Nc4prototypes.class.getMethod("nc_inq_libvers"); String version = (String) nc_inq_libversMethod.invoke(nc4); return version; } catch (Exception e) { return "unavailable (" + e.getClass() + ":" + e.getMessage() + ")"; } }
Source:
<code>public void detach(ChannelCreationListener channelCreationListener) { <START> this.channelCreationListener = ChannelCreationListener.NO_OP; <END> newChannelName.removeTextChangedListener(channelNameTextWatcher); privateChannelSwitch.setOnCheckedChangeListener(null); createButton.setOnClickListener(null); }</code><technical_language>is purpose of no_op ? this listener called detached</technical_language>

Target:
public void detach(ChannelCreationListener channelCreationListener) { newChannelName.removeTextChangedListener(channelNameTextWatcher); privateChannelSwitch.setOnCheckedChangeListener(null); createButton.setOnClickListener(null); this.channelCreationListener = null; }
Source:
<code>private CompletableFuture<RestResponse> getCounter(RestRequest request) throws RestResponseException { String counterName = request.variables().get("counterName"); String accept = request.getAcceptHeader(); MediaType contentType = accept == null ? MediaType.TEXT_PLAIN : negotiateMediaType(accept); NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); CounterConfiguration configuration = counterManager.getConfiguration(counterName); if (configuration == null) { return CompletableFuture.completedFuture(responseBuilder.status(HttpResponseStatus.NOT_FOUND.code()).entity("Counter not found").build()); } else { responseBuilder.contentType(contentType).header(HttpHeaderNames.CACHE_CONTROL.toString(), CacheControl.noCache()); CompletableFuture<Long> response; if (configuration.type() == CounterType.WEAK) { response = CompletableFuture.completedFuture(counterManager.getWeakCounter(counterName).getValue()); <START> } else { <END> response = counterManager.getStrongCounter(counterName).getValue(); } return response.thenApply(res -> responseBuilder.entity(Long.toString(res)).build()); } }</code><technical_language>need wrap value, is a CompletableFuture<Long></technical_language>

Target:
private CompletionStage<RestResponse> getCounter(RestRequest request) throws RestResponseException { String counterName = request.variables().get("counterName"); String accept = request.getAcceptHeader(); MediaType contentType = accept == null ? MediaType.TEXT_PLAIN : negotiateMediaType(accept); NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); CounterConfiguration configuration = counterManager.getConfiguration(counterName); if (configuration == null) { return CompletableFuture.completedFuture(responseBuilder.status(HttpResponseStatus.NOT_FOUND.code()).entity("Counter not found").build()); } responseBuilder.contentType(contentType).header(HttpHeaderNames.CACHE_CONTROL.toString(), CacheControl.noCache()); CompletionStage<Long> response; if (configuration.type() == CounterType.WEAK) { response = CompletableFuture.completedFuture(counterManager.getWeakCounter(counterName).getValue()); } else { response = counterManager.getStrongCounter(counterName).getValue(); } return response.thenApply(res -> responseBuilder.entity(Long.toString(res)).build()); }