auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onFailed() { if (!completedMerge()) { TransactionSupport.executeInNewTransaction(() -> { syncDbRecordsMergeFailure(); return null; }); log.error("Merging of snapshot '{}' images '{}'..'{}' failed. Images have been" + " marked illegal and can no longer be previewed or reverted to." + " Please retry Live Merge on the snapshot to complete the operation.", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)" ); } else { VmBlockJobType blockJobType = getParameters().getMergeStatusReturnValue().getBlockJobType(); DiskImage targetImage = blockJobType == VmBlockJobType.PULL ? getDestinationDiskImage() : getDiskImage(); <START> DiskImage imageFromIRS = getImageInfoFromIRS(targetImage); <END> TransactionSupport.executeInNewTransaction(() -> { syncDbRecords(imageFromIRS, false); return null; }); log.error("Snapshot '{}' images '{}'..'{}' merged, but volume removal failed." + " Some or all of the following volumes may be orphaned: {}." + " Please retry Live Merge on the snapshot to complete the operation.", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)", getParameters().getMergeStatusReturnValue().getImagesToRemove()); } }</code><technical_language>lets this code in a method avoid duplicacy</technical_language>

Target:
public void onFailed() { if (!completedMerge()) { TransactionSupport.executeInNewTransaction(() -> { syncDbRecordsMergeFailure(); return null; }); log.error("Merging of snapshot '{}' images '{}'..'{}' failed. Images have been" + " marked illegal and can no longer be previewed or reverted to." + " Please retry Live Merge on the snapshot to complete the operation.", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)" ); } else { DiskImage imageFromIRS = getImageInfoFromIRS(getTargetImage()); TransactionSupport.executeInNewTransaction(() -> { syncDbRecords(imageFromIRS, false); return null; }); log.error("Snapshot '{}' images '{}'..'{}' merged, but volume removal failed." + " Some or all of the following volumes may be orphaned: {}." + " Please retry Live Merge on the snapshot to complete the operation.", getDiskImage().getImage().getSnapshotId(), getDiskImage().getImageId(), getDestinationDiskImage() != null ? getDestinationDiskImage().getImageId() : "(n/a)", getParameters().getMergeStatusReturnValue().getImagesToRemove()); } }
Source:
<code>public void testCallProcIsProc() throws Exception { when(fakePlayer.isOp()).thenReturn(true); String config = "/for = >>>\n" + " msg(is_proc('_proc'))\n" + " proc('_proc'," + " msg('hello world')" + " )" + "@name_proc = '_proc'" <START> + " msg(is_proc(@name_proc))" <END> + " call_proc(@name_proc)" + "<<<\n"; RunCommand(config, fakePlayer, "/for"); verify(fakePlayer).sendMessage("false"); verify(fakePlayer).sendMessage("true"); verify(fakePlayer).sendMessage("hello world"); }</code><technical_language>is a function called dyn() is meant for in cases, eventually, more static analysis is complete, this warning. <LINK_0> This forces compiler treat dynamic, if hardcoded, is preferred solution in this case, in eval case well</technical_language>

Target:
public void testCallProcIsProc() throws Exception { when(fakePlayer.isOp()).thenReturn(true); String config = "/for = >>>\n" + " msg(is_proc('_proc'))\n" + " proc('_proc'," + " msg('hello world')" + " )" + " msg(is_proc('_proc'))" + " call_proc(dyn('_proc'))" + "<<<\n"; RunCommand(config, fakePlayer, "/for"); verify(fakePlayer).sendMessage("false"); verify(fakePlayer).sendMessage("true"); verify(fakePlayer).sendMessage("hello world"); }
Source:
<code>private ResolutionApiOutput outputFor(String pid, String crid) { if (pid == null && crid == null) { throw new IllegalArgumentException("Must specify pid or crid"); } if (pid != null && crid != null) { throw new IllegalArgumentException("Must not specify both pid and crid"); } if (pid != null) { <START> return outputFor(VERSION_PID_TYPE, pid, YOUVIEW_CRID_TYPE, mappingStore.getValueFor(canonicalUriFor(pid))); <END> } return outputFor(YOUVIEW_CRID_TYPE, crid, VERSION_PID_TYPE, mappingStore.getKeyFor(crid)); }</code><technical_language>return outputFor( VERSION_PID_TYPE, pid, YOUVIEW_CRID_TYPE, mappingStore.getValueFor(canonicalUriFor(pid)) )</technical_language>

Target:
private ResolutionApiOutput outputFor(String pid, String crid) { checkArgument(pid == null && crid == null, "Must specify pid or crid"); checkArgument(pid != null && crid != null, "Must not specify both pid and crid"); if (pid != null) { return outputFor(VERSION_PID_TYPE, pid, YOUVIEW_CRID_TYPE, mappingStore.getValueFor(canonicalUriFor(pid))); } return outputFor(YOUVIEW_CRID_TYPE, crid, VERSION_PID_TYPE, mappingStore.getKeyFor(crid)); }
Source:
<code>void emit(JavaWriter writer) throws IOException; } private void emitCodeForUnderConstruction(JavaWriter writer, VariableElement field, boolean isPrimaryKey, CodeEmitter defaultValueCodeEmitter) throws IOException { writer.beginControlFlow("if (proxyState.isUnderConstruction())"); if (isPrimaryKey) { writer.emitSingleLineComment("default value of the primary key is always ignored."); writer.emitStatement("return"); } else { writer.beginControlFlow("if (!proxyState.getAcceptDefaultValue$realm())") .emitStatement("return") .endControlFlow(); <START> if (Utils.isRealmModel(field)) { <END> } else if (Utils.isRealmList(field)) { writer.beginControlFlow("if (proxyState.getExcludeFields$realm().contains(\"%1$s\"))", field.getSimpleName().toString()) .emitStatement("return") .endControlFlow(); final String modelFqcn = Utils.getGenericTypeQualifiedName(field); writer.beginControlFlow("if (value != null && !value.isManaged())") .emitStatement("final Realm realm = (Realm) proxyState.getRealm$realm()") .emitStatement("final RealmList<%1$s> original = value", modelFqcn) .emitStatement("value = new RealmList<%1$s>()", modelFqcn) .beginControlFlow("for (%1$s item : original)", modelFqcn) .beginControlFlow("if (item == null || RealmObject.isManaged(item))") .emitStatement("value.add(item)") .nextControlFlow("else") .emitStatement("value.add(realm.copyToRealm(item))") .endControlFlow() .endControlFlow() .endControlFlow(); } defaultValueCodeEmitter.emit(writer); } writer.endControlFlow() .emitEmptyLine(); }</code><technical_language>empty block? remove if</technical_language>

Target:
void emit(JavaWriter writer) throws IOException; } private void emitCodeForUnderConstruction(JavaWriter writer, boolean isPrimaryKey, CodeEmitter defaultValueCodeEmitter) throws IOException { writer.beginControlFlow("if (proxyState.isUnderConstruction())"); if (isPrimaryKey) { writer.emitSingleLineComment("default value of the primary key is always ignored."); writer.emitStatement("return"); } else { writer.beginControlFlow("if (!proxyState.getAcceptDefaultValue$realm())") .emitStatement("return") .endControlFlow(); defaultValueCodeEmitter.emit(writer); } writer.endControlFlow(); writer.emitEmptyLine(); }
Source:
<code>public boolean addDnsEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; <START> } else { <END> return applyDhcpEntries(network, nic, vm, dest, Service.Dns); } }</code><technical_language>This else block is unnecessary if block returns. Please remove it</technical_language>

Target:
public boolean addDnsEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } return applyDhcpEntries(network, nic, vm, dest, Service.Dns); }
Source:
<code>@Override public void init(ServiceContext ctx) { Ignite ignite = Ignition.localIgnite(); <START> reqQueue = ignite.queue(String.format(INFERENCE_REQ_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); <END> resQueue = ignite.queue(String.format(INFERENCE_RES_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); mdl = parser.parse(reader.read()); }</code><technical_language>more long names INFERENCE_**REQUEST**_QUEUE_NAME_PATTERN</technical_language>

Target:
@Override public void init(ServiceContext ctx) { Ignite ignite = Ignition.localIgnite(); reqQueue = ignite.queue(String.format(INFERENCE_REQUEST_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); resQueue = ignite.queue(String.format(INFERENCE_RESPONSE_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); mdl = parser.parse(reader.read()); }
Source:
<code>public CallFilteringResult whenDone(CallFilteringResult result) { for (CallFilter filter : mFilter.getPostFilters()) { synchronized <START> (filter.mLock) { <END> int currIndegree = filter.getIndegree(); currIndegree--; filter.setIndegree(currIndegree); if (currIndegree == 0) { mFiltersQueue.offer(filter); } } } mResults.put(mFilter, result); return result; }</code><technical_language>Instead of exposing this lock, create a decrementAndGetIndegree() method? exposing lock, making classes responsible for locking correctly. lock concurrently accessed data in CallFilter itself</technical_language>

Target:
public CallFilteringResult whenDone(CallFilteringResult result) { mFilter.mResult = result; for (CallFilter filter : mFilter.getPostFilters()) { if (filter.decrementAndGetIndegree() == 0) { mFiltersQueue.offer(filter); } } return result; }
Source:
<code>private List<Artifact> getNewDependencies(List<Dependency> dependencies, List<Dependency> existingDependencies) { List<Artifact> updatedArtifacts = new ArrayList<Artifact>(); for (Dependency dep : dependencies) { boolean newDependency = true; for (Dependency existingDep : existingDependencies) { if (dep.getArtifactId().equals(existingDep.getArtifactId())) { newDependency = false; break; } } if (newDependency) { log.debug("New dependency found: " + dep.getArtifactId()); try { <START> Artifact artifact; <END> artifact = getArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getVersion()); updatedArtifacts.add(artifact); } catch (MojoExecutionException e) { log.info(e.getMessage()); } } } return updatedArtifacts; }</code><technical_language>combine lines (587/588)</technical_language>

Target:
private List<Artifact> getNewDependencies(List<Dependency> dependencies, List<Dependency> existingDependencies) { List<Artifact> updatedArtifacts = new ArrayList<Artifact>(); for (Dependency dep : dependencies) { boolean newDependency = true; for (Dependency existingDep : existingDependencies) { if (dep.getArtifactId().equals(existingDep.getArtifactId())) { newDependency = false; break; } } if (newDependency) { log.debug("New dependency found: " + dep.getArtifactId()); try { Artifact artifact = getArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getVersion()); updatedArtifacts.add(artifact); } catch (MojoExecutionException e) { log.warn(e.getMessage()); } } } return updatedArtifacts; }
Source:
<code>private void testSanitization() throws IOException { ______TS("Test sanitization for edit page"); instructorId = testData.accounts.get("instructor1OfTestingSanitizationCourse").googleId; FeedbackSessionAttributes session = testData.feedbackSessions.get("session1InTestingSanitizationCourse"); courseId = session.getCourseId(); feedbackSessionName = session.getFeedbackSessionName(); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.verifyHtmlMainContent("/instructorFeedbackEditPageTestingSanitization.html"); ______TS("Test sanitization for copy question modal"); feedbackEditPage.clickCopyButton(); feedbackEditPage.waitForCopyTableToLoad(); feedbackEditPage.verifyHtmlPart(By.id("copyModal"), "/instructorFeedbackCopyQuestionModalTestingSanitization.html"); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickDeleteQuestionLink(1); <START> feedbackEditPage.waitForConfirmationModalAndClickOk(); <END> }</code><technical_language>Added because</technical_language>

Target:
private void testSanitization() throws IOException { ______TS("Test sanitization for edit page"); instructorId = testData.accounts.get("instructor1OfTestingSanitizationCourse").googleId; FeedbackSessionAttributes session = testData.feedbackSessions.get("session1InTestingSanitizationCourse"); courseId = session.getCourseId(); feedbackSessionName = session.getFeedbackSessionName(); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.verifyHtmlMainContent("/instructorFeedbackEditPageTestingSanitization.html"); ______TS("Test sanitization for copy question modal"); feedbackEditPage.clickCopyButton(); feedbackEditPage.waitForCopyTableToLoad(); feedbackEditPage.verifyHtmlPart(By.id("copyModal"), "/instructorFeedbackCopyQuestionModalTestingSanitization.html"); }
Source:
<code>public FFmpegProbeResult probe(String mediaPath, @Nullable String userAgent) throws IOException { checkIfFFprobe(); ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); args.add(path).add("-v", "quiet"); if (userAgent != null) { args.add("-user-agent", userAgent); } args.add("-print_format", "json") .add("-show_error") .add("-show_format") .add("-show_streams") .add("-show_chapters") .add(mediaPath); Process p = runFunc.run(args.build()); try { Reader reader = wrapInReader(p); if (LOG.isDebugEnabled()) { reader = new LoggingFilterReader(reader, LOG); } FFmpegProbeResult result = gson.fromJson(reader, FFmpegProbeResult.class); throwOnError(p); if (result == null) { throw new IllegalStateException("Gson returned null, which shouldn't happen :("); } return result; } finally { <START> if (p != null) { <END> p.destroy(); } } }</code><technical_language>p null here</technical_language>

Target:
public FFmpegProbeResult probe(String mediaPath, @Nullable String userAgent) throws IOException { checkIfFFprobe(); ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); args.add(path).add("-v", "quiet"); if (userAgent != null) { args.add("-user-agent", userAgent); } args.add("-print_format", "json") .add("-show_error") .add("-show_format") .add("-show_streams") .add("-show_chapters") .add(mediaPath); Process p = runFunc.run(args.build()); try { Reader reader = wrapInReader(p); if (LOG.isDebugEnabled()) { reader = new LoggingFilterReader(reader, LOG); } FFmpegProbeResult result = gson.fromJson(reader, FFmpegProbeResult.class); throwOnError(p); if (result == null) { throw new IllegalStateException("Gson returned null, which shouldn't happen :("); } return result; } finally { p.destroy(); } }
Source:
<code>private ZapMenuItem getMenuItemHtmlReport() { if (menuItemHtmlReport == null) { menuItemHtmlReport = new ZapMenuItem("menu.report.html.generate"); <START> menuItemHtmlReport.addActionListener((java.awt.event.ActionEvent e) -> { <END> ReportLastScan report = new ReportLastScan(); report.generateReport(getView(), getModel(), ReportLastScan.ReportType.HTML); }); } return menuItemHtmlReport; }</code><technical_language>type is needed, changed statement, e.g.: Java menuItemHtmlReport.addActionListener(e -> new ReportLastScan().generateReport(...)); - if code indentation surrounding code</technical_language>

Target:
private ZapMenuItem getMenuItemHtmlReport() { if (menuItemHtmlReport == null) { menuItemHtmlReport = new ZapMenuItem("menu.report.html.generate"); menuItemHtmlReport.addActionListener(e -> new ReportLastScan().generateReport(getView(), getModel(), ReportLastScan.ReportType.HTML)); } return menuItemHtmlReport; }
Source:
<code>public String getPathForHadoop(String dataSource) { <START> return String.format("file://%s/%s", config.getStorageDirectory().getAbsoluteFile(), dataSource); <END> }</code><technical_language>is standard URI building here? hadoop FS path building java File Path constructs</technical_language>

Target:
public String getPathForHadoop(String dataSource) { return new File(config.getStorageDirectory().getAbsoluteFile(), dataSource).toURI().toString(); }
Source:
<code>public void stopActiveOutPatientVisits() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat formatterExt = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatterExt.format(new Date()) + " " + "00:00:00"; AdministrationService administrationService = Context.getAdministrationService(); String visitTypeUUID =administrationService.getGlobalProperty("ugandaemr.autoCloseVisit.visitTypeUUID"); VisitService visitService = Context.getVisitService(); List activeVisitList = null; <START> activeVisitList = administrationService.executeSQL("select visit.visit_id from visit inner join visit_type on (visit.visit_type_id = visit_type.visit_type_id) where visit_type.uuid='"+visitTypeUUID+"' AND visit.date_stopped IS NULL AND visit.date_started < '" + formattedDate + "'", true); <END> for (Object object : activeVisitList) { ArrayList<Integer> integers = (ArrayList) object; Visit visit = visitService.getVisit(integers.get(0)); try{ visitService.endVisit(visit, OpenmrsUtil.getLastMomentOfDay(visit.getStartDatetime())); }catch (Exception e){ log.error("Failed to auto close visit",e); } } }</code><technical_language>@slubwama visit.date_started < CURR_DATE() get unopened dates</technical_language>

Target:
public void stopActiveOutPatientVisits() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat formatterExt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentDate = formatterExt.format(OpenmrsUtil.firstSecondOfDay(new Date())); AdministrationService administrationService = Context.getAdministrationService(); String visitTypeUUID =administrationService.getGlobalProperty("ugandaemr.autoCloseVisit.visitTypeUUID"); VisitService visitService = Context.getVisitService(); List activeVisitList = null; activeVisitList = administrationService.executeSQL("select visit.visit_id from visit inner join visit_type on (visit.visit_type_id = visit_type.visit_type_id) where visit_type.uuid='"+visitTypeUUID+"' AND visit.date_stopped IS NULL AND visit.date_started < '" + currentDate + "'", true); for (Object object : activeVisitList) { ArrayList<Integer> integers = (ArrayList) object; Visit visit = visitService.getVisit(integers.get(0)); try{ visitService.endVisit(visit, OpenmrsUtil.getLastMomentOfDay(visit.getStartDatetime())); }catch (Exception e){ log.error("Failed to auto close visit",e); } } }
Source:
<code>private Node<Object[]> visit(RelNode rel) { <START> return visit(igniteRel(rel)); <END> }</code><technical_language>Intensive of igniteRel() method affects readability convenience of debugging. get rid of it</technical_language>

Target:
private Node<Object[]> visit(RelNode rel) { return visit((IgniteRel) rel); }
Source:
<code>public boolean removeMucClient(String id) { <START> synchronized (syncRoot) <END> { MucClient mucClient = mucClients.remove(id); if (mucClient == null) { logger.info("Can not find MucClient to remove."); return false; } mucClient.stop(); return true; } }</code><technical_language>this need synchronized? a concurrent map? of logic remove need happen atomically remove itself</technical_language>

Target:
public boolean removeMucClient(String id) { MucClient mucClient = mucClients.remove(id); if (mucClient == null) { logger.info("Can not find MucClient to remove."); return false; } mucClient.stop(); return true; }
Source:
<code>public void testEntityCopyright() { builder.beginDocument(); builder.entityReference("copy"); builder.characters(" AT"); builder.entityReference("amp"); builder.characters("T 2014"); builder.endDocument(); <START> assertMarkup("&copy; AT&T 2014\n\n"); <END> }</code><technical_language>real company names in test data</technical_language>

Target:
public void testEntityCopyright() { builder.beginDocument(); builder.entityReference("copy"); builder.characters(" XY"); builder.entityReference("amp"); builder.characters("Z 2014"); builder.endDocument(); assertMarkup("&copy; XY&Z 2014\n\n"); }
Source:
<code>private static FlatMapFunction<Tuple2<AssemblyRegion, SimpleInterval>, VariantContext> callVariantsFromAssemblyRegions( final AuthHolder authHolder, final SAMFileHeader header, final Broadcast<ReferenceMultiSource> referenceBroadcast, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast) { return regionAndInterval -> { final ReferenceMultiSourceAdaptor referenceReader = new ReferenceMultiSourceAdaptor(referenceBroadcast.getValue(), authHolder); final HaplotypeCallerEngine hcEngine = new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceReader); final List<VariantContext> variantContexts = hcEngine.callRegion(regionAndInterval._1(), new FeatureContext()); final SimpleInterval shardBoundary = regionAndInterval._2(); <START> return variantContexts.stream().filter(shardBoundary::contains).collect(Collectors.toList()); <END> }; }</code><technical_language>BUGBUG: checking shard contains start position, entire event</technical_language>

Target:
private static FlatMapFunction<Iterator<Tuple2<AssemblyRegion, SimpleInterval>>, VariantContext> callVariantsFromAssemblyRegions( final AuthHolder authHolder, final SAMFileHeader header, final Broadcast<ReferenceMultiSource> referenceBroadcast, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast) { return regionAndIntervals -> { final ReferenceMultiSourceAdapter referenceReader = new ReferenceMultiSourceAdapter(referenceBroadcast.getValue(), authHolder); final HaplotypeCallerEngine hcEngine = new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceReader); return iteratorToStream(regionAndIntervals).flatMap(regionToVariants(hcEngine)).iterator(); }; }
Source:
<code>public void setToState(EntityRef entity, CharacterStateEvent state) { LocationComponent location = entity.getComponent(LocationComponent.class); CharacterMovementComponent movementComp = entity.getComponent(CharacterMovementComponent.class); if (location == null || Float.isNaN(location.getWorldPosition().x) || movementComp == null) { return; } location.setWorldPosition(state.getPosition()); location.setWorldRotation(state.getRotation()); entity.saveComponent(location); movementComp.mode = state.getMode(); movementComp.setVelocity(state.getVelocity()); movementComp.grounded = state.isGrounded(); movementComp.footstepDelta = state.getFootstepDelta(); entity.saveComponent(movementComp); setPhysicsLocation(entity, JomlUtil.from(state.getPosition())); <START> Quaternionf rotation = new Quaternionf().rotationYXZ(0f, TeraMath.DEG_TO_RAD * state.getPitch(), 0f); <END> EntityRef gazeEntity = GazeAuthoritySystem.getGazeEntityForCharacter(entity); if (!gazeEntity.equals(entity)) { LocationComponent gazeLocation = gazeEntity.getComponent(LocationComponent.class); gazeLocation.setLocalRotation(JomlUtil.from(rotation)); gazeEntity.saveComponent(gazeLocation); } }</code><technical_language>simplified to: suggestion Quaternionf rotation = new Quaternionf().rotationX(TeraMath.DEG_TO_RAD * state.getPitch());</technical_language>

Target:
public void setToState(EntityRef entity, CharacterStateEvent state) { LocationComponent location = entity.getComponent(LocationComponent.class); CharacterMovementComponent movementComp = entity.getComponent(CharacterMovementComponent.class); if (location == null || Float.isNaN(location.getWorldPosition().x) || movementComp == null) { return; } location.setWorldPosition(state.getPosition()); location.setWorldRotation(state.getRotation()); entity.saveComponent(location); movementComp.mode = state.getMode(); movementComp.setVelocity(state.getVelocity()); movementComp.grounded = state.isGrounded(); movementComp.footstepDelta = state.getFootstepDelta(); entity.saveComponent(movementComp); setPhysicsLocation(entity, JomlUtil.from(state.getPosition())); Quaternionf rotation = new Quaternionf().rotationX(TeraMath.DEG_TO_RAD * state.getPitch()); EntityRef gazeEntity = GazeAuthoritySystem.getGazeEntityForCharacter(entity); if (!gazeEntity.equals(entity)) { LocationComponent gazeLocation = gazeEntity.getComponent(LocationComponent.class); gazeLocation.setLocalRotation(JomlUtil.from(rotation)); gazeEntity.saveComponent(gazeLocation); } }
Source:
<code>private static String buildH2JdbcUrl(int embeddedDatabasePort) { <START> return "jdbc:h2:tcp://" + InetAddress.getLoopbackAddress().getHostAddress() + ":" + embeddedDatabasePort + "/sonar"; <END> }</code><technical_language>Small note here, IPv6 is requiring host separated bracket (because : is in IPv6 address) cf. <LINK_0></technical_language>

Target:
private static String buildH2JdbcUrl(int embeddedDatabasePort) { InetAddress ip = InetAddress.getLoopbackAddress(); String host; if (ip instanceof Inet6Address) { host = "[" + ip.getHostAddress() + "]"; } else { host = ip.getHostAddress(); } return format("jdbc:h2:tcp://%s:%d/sonar", host, embeddedDatabasePort); }
Source:
<code>public String toString() { <START> return this == Element.BLUE_FIRE ? this.getColor() + "Blue Fire": this.getColor() + this.getName(); <END> }</code><technical_language>written this: (this == Element.BLUE_FIRE) ? this.getColor() + "Blue Fire" : this.getColor() + this.getName();</technical_language>

Target:
public String toString() { return (this == Element.BLUE_FIRE) ? this.getColor() + "Blue Fire": this.getColor() + this.getName(); }
Source:
<code>public Response getApplication(final @PathParam("clientId") String clientId) { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS); ClientModel client = realm.getClientByClientId(clientId); if (client == null) { return Cors.add(request, Response.status(Response.Status.NOT_FOUND).entity("No client with clientId: " + clientId + " found.")).build(); } List<String> inUseClients = new LinkedList<>(); if(!session.sessions().getUserSessions(realm, client).isEmpty()) { inUseClients.add(clientId); } List<String> offlineClients = new LinkedList<>(); if(session.sessions().getOfflineSessionsCount(realm, client) > 0) { offlineClients.add(clientId); } <START> return Cors.add(request, Response.ok(modelToRepresentation(client, inUseClients, offlineClients))).build(); <END> }</code><technical_language>I a potential security issue. If I right, this endpoint return clients hidden user bearer-only clients clients active session consents, etc. In other words, this endpoint match /applications endpoint returns</technical_language>

Target:
public Response getApplication(final @PathParam("clientId") String clientId) { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS); ClientModel client = realm.getClientByClientId(clientId); if (client == null || client.isBearerOnly() || client.getBaseUrl() == null) { return Cors.add(request, Response.status(Response.Status.NOT_FOUND).entity("No client with clientId: " + clientId + " found.")).build(); } List<String> inUseClients = new LinkedList<>(); if(!session.sessions().getUserSessions(realm, client).isEmpty()) { inUseClients.add(clientId); } List<String> offlineClients = new LinkedList<>(); if(session.sessions().getOfflineSessionsCount(realm, client) > 0) { offlineClients.add(clientId); } UserConsentModel consentModel = session.users().getConsentByClient(realm, user.getId(), client.getId()); Map<String, UserConsentModel> consentModels = Collections.singletonMap(client.getClientId(), consentModel); return Cors.add(request, Response.ok(modelToRepresentation(client, inUseClients, offlineClients, consentModels))).build(); }
Source:
<code>public void addDestroyAction(UUID registrationId, Callable<Boolean> removeAction) { <START> removeListenerActions.put(registrationId, removeAction); <END> if (destroyed) { callRemoveAction(removeAction); removeDestroyAction(registrationId); } }</code><technical_language>I fix leak call removeAction in code path java @Override public void addDestroyAction(UUID registrationId, Callable<Boolean> removeAction) { synchronized (removeListenerActions) { if (destroyed) { callRemoveAction(removeAction); } else { removeListenerActions.put(registrationId, removeAction); } } }</technical_language>

Target:
public void addDestroyAction(UUID registrationId, Callable<Boolean> removeAction) { removeListenerActions.put(registrationId, removeAction); if (destroyed) { removeAndCallRemoveAction(registrationId); } }
Source:
<code>protected String buildDocumentDescription(String departmentName) { String documentDescriptionBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_DOCUMENT_DESCRIPTION_FORMAT); String documentDescription = MessageFormat.format(documentDescriptionBase, findMonthName(), departmentName); <START> return StringUtils.substring(documentDescription, 0, 40); <END> }</code><technical_language>I suggest moving "40" literal constant finding a derive needed max length</technical_language>

Target:
protected String buildDocumentDescription(String departmentName) { String documentDescriptionBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_DOCUMENT_DESCRIPTION_FORMAT); String documentDescription = MessageFormat.format(documentDescriptionBase, findMonthName(), findProcessYear(), departmentName); int descriptionMaxLength = dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KFSPropertyConstants.DOCUMENT_DESCRIPTION); return StringUtils.substring(documentDescription, 0, descriptionMaxLength); }
Source:
<code>private boolean isRetryable(@NonNull Throwable t) { return !(t instanceof IllegalArgumentException || t instanceof UnknownHostException || <START> ThrowableUtil.is404(t)); <END> }</code><technical_language>consider 5xx errors retryable? idea IllegalArgumentException is from? unmarshalling failures (maybe GeoIPCookieUnmarshaller?)</technical_language>

Target:
private boolean isRetryable(@NonNull Throwable t) { return !(t instanceof IllegalArgumentException || ThrowableUtil.is404(t)); }
Source:
<code>private Map<Category, Integer> resolveIntoCategoryEntities(List<WeightedTerm> terms) { Set<String> termStrings = terms.stream() .map(WeightedTerm::getTerm) .collect(Collectors.toSet()); Collection<Category> existingCategories = parentService.hibernateTemplate.execute(session -> { Query query = session.createQuery("FROM Category WHERE path IN (:terms)"); query.setParameterList("terms", termStrings); return query.list(); }); Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath); Map<Category, Integer> categories = Maps.newLinkedHashMapWithExpectedSize(terms.size()); for (WeightedTerm term : terms) { Category category = existingCategoryMap.get(term.getTerm()); if (category == null) { <START> category = new Category(); <END> category.setPath(term.getTerm()); } categories.put(category, term.getWeight()); } return categories; }</code><technical_language>So, this is improvement Ambra lib doing, worried this a bug if articles populated concurrently. categories duplicate paths created inserted. code capable of a similar race condition, _unless_ @Transactional annotation investigating preventing that, is unclear</technical_language>

Target:
private Map<Category, Integer> resolveIntoCategoryEntities(List<WeightedTerm> terms) { Set<String> termStrings = terms.stream() .map(WeightedTerm::getPath) .collect(Collectors.toSet()); Collection<Category> existingCategories = parentService.hibernateTemplate.execute(session -> { Query query = session.createQuery("FROM Category WHERE path IN (:terms)"); query.setParameterList("terms", termStrings); return query.list(); }); Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath); Map<Category, Integer> categories = Maps.newLinkedHashMapWithExpectedSize(terms.size()); for (WeightedTerm term : terms) { Category category = existingCategoryMap.get(term.getPath()); if (category == null) { category = new Category(); category.setPath(term.getPath()); parentService.hibernateTemplate.save(category); } categories.put(category, term.getWeight()); } return categories; }
Source:
<code>public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); final String Down = "Down".intern(); VM vm = (VM) entity; <START> switch (taskType){ <END> case START_VM: vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay, PoweringUp); break; case START_VM_AS_UP: vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up); break; case SHUTDOWN_VM: vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down); break; default: log.error("Unhandled status detected."); break; } }</code><technical_language>I need a bit more states here. need cover vm life cycle</technical_language>

Target:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch"; final String PoweringUp = "Powering up"; final String Up = "Up"; final String PoweredDown = "Powering down"; final String Down = "Down"; VM vm = (VM) entity; switch (taskType){ case START_VM: vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch, service, false); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay, PoweringUp, service, false); break; case START_VM_AS_UP: vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up, service, true); break; case SHUTDOWN_VM: vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown, service, false); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down, service, true); break; default: log.error("Unhandled status detected."); break; } }
Source:
<code>private void appendBoxedListExpressionItem(final ListSeleniumModel list, final String item) { expandDecisionNavigatorDock(); final WebElement node = waitOperation().until(element(LIST, list.getName())); assertThat(node) <START> .as("Decision table of '" + list.getName() + "'was not present in the list of nodes") <END> .isNotNull(); node.click(); final WebElement editor = getEditor(); for (int i = 0; i < list.getItems().size() - 1; i++) { editor.sendKeys(Keys.ARROW_DOWN); } editor.sendKeys(Keys.CONTROL, Keys.SPACE); final WebElement listEntry = waitOperation().until(element(MENU_ENTRY, "Insert below")); assertThat(listEntry) .as("Entry in context menu not available") .isNotNull(); listEntry.click(); editor.sendKeys(Keys.ARROW_DOWN); editor.sendKeys(Keys.ENTER); getAutocompleteEditor().sendKeys(item, Keys.TAB); collapseDecisionNavigatorDock(); }</code><technical_language>a "Decision table" in this test</technical_language>

Target:
private void appendBoxedListExpressionItem(final ListSeleniumModel list, final String item) { expandDecisionNavigatorDock(); final WebElement node = waitOperation().until(element(LIST, list.getName())); assertThat(node) .as("List expression '" + list.getName() + NOT_PRESENT_IN_NAVIGATOR) .isNotNull(); node.click(); final WebElement editor = getEditor(); for (int i = 0; i < list.getItems().size() - 1; i++) { editor.sendKeys(Keys.ARROW_DOWN); } editor.sendKeys(Keys.CONTROL, Keys.SPACE); final WebElement insertBelow = waitOperation().until(element(MENU_ENTRY, "Insert below")); assertThat(insertBelow) .as("Insert below entry in context menu not available") .isNotNull(); insertBelow.click(); editor.sendKeys(Keys.ARROW_DOWN, Keys.ENTER); getAutocompleteEditor().sendKeys(item, Keys.TAB); collapseDecisionNavigatorDock(); }
Source:
<code>public void testVersionRecordManagerIsInitializedOnRename() { Mockito.reset(versionRecordManager); when(versionRecordManager.getCurrentPath()).thenReturn(observablePath); baseEditor.onRename(); verify(versionRecordManager).init(any(), <START> any(), <END> any()); }</code><technical_language>nice check path observablePath _any_ path</technical_language>

Target:
public void testVersionRecordManagerIsInitializedOnRename() { Mockito.reset(versionRecordManager); when(versionRecordManager.getCurrentPath()).thenReturn(observablePath); baseEditor.onRename(); verify(versionRecordManager).init(any(), eq(observablePath), any()); }
Source:
<code>public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<SortingColumn> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s may be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } <START> if (bucketCount > 32_000) { <END> throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s should be no more than 32000", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }</code><technical_language>want fail queries? Presto query table if disable bucket-by-bucket right -- depends configuration hive.max-outstanding-splits-size right</technical_language>

Target:
public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<SortingColumn> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s may be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } if (bucketCount > 1_000_000) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s should be no more than 1000000", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }
Source:
<code>public void insertRollups(List<SingleRollupWriteContext> writeContexts) throws IOException { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = rollupTypeToIO.get(rollupType); if ( io == null ) { throw new InvalidDataException( String.format("insertRollups(locator=%s, granularity=%s): unsupported rollupType=%s", locator, granularity, rollupType.name())); } ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } for (ResultSetFuture future : futureLocatorMap.keySet()) { try { future.getUninterruptibly().all(); } catch (Exception ex) { SingleRollupWriteContext writeContext = futureLocatorMap.get(future); <START> LOG.error(String.format("error writing to locator %s, granularity %s", writeContext.getLocator(), writeContext.getGranularity()), ex); <END> } } } finally { ctx.stop(); } }</code><technical_language>I dont instrumentation for errors. below. Instrumentation.markWriteError(e);</technical_language>

Target:
public void insertRollups(List<SingleRollupWriteContext> writeContexts) { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = getIO( rollupType.name().toLowerCase(), granularity ); ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } for (ResultSetFuture future : futureLocatorMap.keySet()) { try { future.getUninterruptibly().all(); } catch (Exception ex) { Instrumentation.markWriteError(); SingleRollupWriteContext writeContext = futureLocatorMap.get(future); LOG.error(String.format("error writing to locator %s, granularity %s", writeContext.getLocator(), writeContext.getGranularity()), ex); } } } finally { ctx.stop(); } }
Source:
<code>public void vdsNotResponding(final VDS vds, final boolean executeSshSoftFencing) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("ResourceManager::vdsNotResponding entered for Host {0}, {1}", vds.getId(), vds.getHostName()); boolean sshSoftFencingSuccessful = false; if (executeSshSoftFencing) { VdcReturnValueBase retVal = Backend.getInstance().runInternalAction(VdcActionType.SshSoftFencing, new VdsActionParameters(vds.getId()), ExecutionHandler.createInternalJobContext()); sshSoftFencingSuccessful = retVal.getSucceeded(); } <START> if (!sshSoftFencingSuccessful) { <END> Backend.getInstance().runInternalAction(VdcActionType.VdsNotRespondingTreatment, new FenceVdsActionParameters(vds.getId(), FenceActionType.Restart), ExecutionHandler.createInternalJobContext()); } } }); }</code><technical_language>actually, success is kinda misleading, right? a true success is if host Up. return vdsNotResponding, if ssh soft restart bring host up, right? elaborate code changes, eventually host fenced</technical_language>

Target:
public void vdsNotResponding(final VDS vds, final boolean executeSshSoftFencing) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("ResourceManager::vdsNotResponding entered for Host {0}, {1}", vds.getId(), vds.getHostName()); boolean shouldExecRealFencing = true; if (executeSshSoftFencing) { VdcReturnValueBase retVal = Backend.getInstance().runInternalAction(VdcActionType.SshSoftFencing, new VdsActionParameters(vds.getId()), ExecutionHandler.createInternalJobContext()); shouldExecRealFencing = !retVal.getSucceeded(); } if (shouldExecRealFencing) { Backend.getInstance().runInternalAction(VdcActionType.VdsNotRespondingTreatment, new FenceVdsActionParameters(vds.getId(), FenceActionType.Restart), ExecutionHandler.createInternalJobContext()); } } }); }
Source:
<code>public HttpClientConnectionManager httpClientConnectionManager( IClientConfig config, ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { Integer maxTotalConnections = config.getPropertyAsInteger( CommonClientConfigKey.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); Integer maxConnectionsPerHost = config.getPropertyAsInteger( CommonClientConfigKey.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); Integer timerRepeat = config.getPropertyAsInteger( CommonClientConfigKey.ConnectionCleanerRepeatInterval, DefaultClientConfigImpl.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS); Integer timeToLive = config.get( CommonClientConfigKey.PoolKeepAliveTime, <START> (int)DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME); <END> Object ttlUnitObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTimeUnits); TimeUnit ttlUnit = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; if (ttlUnitObj instanceof TimeUnit) { ttlUnit = (TimeUnit) ttlUnitObj; } final HttpClientConnectionManager connectionManager = connectionManagerFactory .newConnectionManager(false, maxTotalConnections, maxConnectionsPerHost, (long)timeToLive, ttlUnit, registryBuilder); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { connectionManager.closeExpiredConnections(); } }, 30000, timerRepeat); return connectionManager; }</code><technical_language>check if is a String convert string a Long</technical_language>

Target:
public HttpClientConnectionManager httpClientConnectionManager( IClientConfig config, ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { Integer maxTotalConnections = config.getPropertyAsInteger( CommonClientConfigKey.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); Integer maxConnectionsPerHost = config.getPropertyAsInteger( CommonClientConfigKey.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); Integer timerRepeat = config.getPropertyAsInteger( CommonClientConfigKey.ConnectionCleanerRepeatInterval, DefaultClientConfigImpl.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS); Object timeToLiveObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTime); Long timeToLive = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME; Object ttlUnitObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTimeUnits); TimeUnit ttlUnit = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; if (timeToLiveObj instanceof Long) { timeToLive = (Long) timeToLiveObj; } else if (timeToLiveObj instanceof String) { timeToLive = Long.valueOf((String)timeToLiveObj); } if (ttlUnitObj instanceof TimeUnit) { ttlUnit = (TimeUnit) ttlUnitObj; } final HttpClientConnectionManager connectionManager = connectionManagerFactory .newConnectionManager(false, maxTotalConnections, maxConnectionsPerHost, timeToLive, ttlUnit, registryBuilder); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { connectionManager.closeExpiredConnections(); } }, 30000, timerRepeat); return connectionManager; }