auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testExpiredRequestAllocationOnAnyHost() throws Exception { MockClusterResourceManager spyManager = spy(new MockClusterResourceManager(callback, state)); spyAllocator = Mockito.spy(new ContainerAllocator(spyManager, config, state, true, Optional.empty())); spyAllocator.requestResources(new HashMap<String, String>() { { put("0", "abc"); put("1", "def"); } }); spyAllocatorThread = new Thread(spyAllocator); spyAllocatorThread.start(); Thread.sleep(10); assertTrue(state.preferredHostRequests.get() == 2); assertTrue(state.expiredPreferredHostRequests.get() == 2); verify(spyAllocator, times(1)).handleExpiredRequest(eq("0"), eq("abc"), any(SamzaResourceRequest.class)); verify(spyAllocator, times(1)).handleExpiredRequest(eq("1"), eq("def"), any(SamzaResourceRequest.class)); ArgumentCaptor<SamzaResourceRequest> cancelledRequestCaptor = ArgumentCaptor.forClass(SamzaResourceRequest.class); verify(spyManager, atLeast(2)).cancelResourceRequest(cancelledRequestCaptor.capture()); assertTrue(cancelledRequestCaptor.getAllValues().stream().map(resourceRequest -> resourceRequest.getPreferredHost()).collect( Collectors.toSet()).size() > 2); assertTrue(state.matchedResourceRequests.get() == 0); assertTrue(state.anyHostRequests.get() > 2); containerAllocator.stop(); }

Target:
public void testExpiredRequestAllocationOnAnyHost() throws Exception { MockClusterResourceManager spyManager = spy(new MockClusterResourceManager(callback, state)); spyAllocator = Mockito.spy(new ContainerAllocator(spyManager, config, state, true, Optional.empty())); spyAllocator.requestResources(new HashMap<String, String>() { { put("0", "hostname-0"); put("1", "hostname-1"); } }); spyAllocatorThread = new Thread(spyAllocator); spyAllocatorThread.start(); Thread.sleep(10); assertTrue(state.preferredHostRequests.get() == 2); assertTrue(state.expiredPreferredHostRequests.get() == 2); verify(spyAllocator, times(1)).handleExpiredRequest(eq("0"), eq("hostname-0"), any(SamzaResourceRequest.class)); verify(spyAllocator, times(1)).handleExpiredRequest(eq("1"), eq("hostname-1"), any(SamzaResourceRequest.class)); ArgumentCaptor<SamzaResourceRequest> cancelledRequestCaptor = ArgumentCaptor.forClass(SamzaResourceRequest.class); verify(spyManager, atLeast(2)).cancelResourceRequest(cancelledRequestCaptor.capture()); assertTrue(cancelledRequestCaptor.getAllValues().stream().map(resourceRequest -> resourceRequest.getPreferredHost()).collect( Collectors.toSet()).size() > 2); assertTrue(state.matchedResourceRequests.get() == 0); assertTrue(state.anyHostRequests.get() > 2); containerAllocator.stop(); }
Source:
public void deactivate() { expr = null; }

Target:
public void deactivate() { }
Source:
public Event getEvent() { return event; }

Target:
Event getEvent() { return event; }
Source:
public void setTouchEnabled(boolean enabled) { if (enabled) { webView.loadUrl("javascript:setTouchEnabled(true);"); } else { webView.loadUrl("javascript:setTouchEnabled(false);"); } }

Target:
public void setTouchEnabled(boolean enabled) { webView.loadUrl("javascript:setTouchEnabled(" + enabled + ");"); }
Source:
private static WorkspaceConfigDto asDto(UsersWorkspaceImpl workspace, String projectPath) throws ConflictException { final List<CommandDto> commands = workspace.getCommands() .stream() .map(DtoConverter::asDto) .collect(toList()); Predicate<ProjectConfigImpl> predicate = new Predicate<ProjectConfigImpl>() { @Override public boolean test(ProjectConfigImpl projectConfig) { if (projectPath != null) { if (!projectConfig.getPath().equals(projectPath)) { return false; } } return projectConfig.getSource() != null && projectConfig.getSource().getType() != null && !projectConfig.getSource().getType().isEmpty() && projectConfig.getSource().getLocation() != null && !projectConfig.getSource().getLocation().isEmpty(); } }; final List<ProjectConfigDto> projects = workspace.getProjects() .stream() .filter(predicate) .map(DtoConverter::asDto) .collect(toList()); if (projects.isEmpty()) { throw new ConflictException( "Unable to create factory from this workspace, because it does not contains projects with source storage set and/or specified path"); } final Map<String, EnvironmentDto> environments = workspace.getEnvironments() .values() .stream() .collect(toMap(EnvironmentStateImpl::getName, FactoryService::asDto)); return DtoFactory.newDto(WorkspaceConfigDto.class) .withName(workspace.getName()) .withDefaultEnvName(workspace.getDefaultEnvName()) .withCommands(commands) .withProjects(projects) .withEnvironments(environments) .withDescription(workspace.getDescription()) .withAttributes(workspace.getAttributes()); }

Target:
private static WorkspaceConfigDto asDto(UsersWorkspaceImpl workspace, String projectPath) throws ConflictException { final List<CommandDto> commands = workspace.getCommands() .stream() .map(DtoConverter::asDto) .collect(toList()); Predicate<ProjectConfigImpl> predicate = new Predicate<ProjectConfigImpl>() { @Override public boolean test(ProjectConfigImpl projectConfig) { if (projectPath != null && !projectConfig.getPath().equals(projectPath)) { return false; } return projectConfig.getSource() != null && !isNullOrEmpty(projectConfig.getSource().getType()) && !isNullOrEmpty(projectConfig.getSource().getLocation()); } }; final List<ProjectConfigDto> projects = workspace.getProjects() .stream() .filter(predicate) .map(DtoConverter::asDto) .collect(toList()); if (projects.isEmpty()) { throw new ConflictException( "Unable to create factory from this workspace, because it does not contains projects with source storage set and/or specified path"); } final Map<String, EnvironmentDto> environments = workspace.getEnvironments() .values() .stream() .collect(toMap(EnvironmentStateImpl::getName, FactoryService::asDto)); return newDto(WorkspaceConfigDto.class) .withName(workspace.getName()) .withDefaultEnvName(workspace.getDefaultEnvName()) .withCommands(commands) .withProjects(projects) .withEnvironments(environments) .withDescription(workspace.getDescription()) .withAttributes(workspace.getAttributes()); }
Source:
public static <T> Digraph<T> buildFilteredDigraph(Digraph<T> initialGraph, Predicate<T> filterOut, Class<T> clazz) { Digraph<T> res = new Digraph<>(clazz); Set<Vertex<T>> toRemove = new LinkedHashSet<>(); for (Vertex<T> vertex : initialGraph.vertexList) { if (!filterOut.test(vertex.id)) { res.addVertex(vertex.id); } else { toRemove.add(vertex); } } Set<Edge<T>> edges = new LinkedHashSet<>(initialGraph.getEdges()); for (Vertex<T> vertexToRemove : toRemove) { Set<Edge<T>> incoming = edges.stream().filter(edge -> edge.to == vertexToRemove.id).collect(Collectors.toSet()); Set<Edge<T>> outgoing = edges.stream().filter(edge -> edge.from == vertexToRemove.id).collect(Collectors.toSet()); edges.removeAll(incoming); edges.removeAll(outgoing); incoming.forEach(incomingEdge -> outgoing.forEach(outgoingEdge -> edges.add(new Edge<>(incomingEdge.from, outgoingEdge.to)))); } edges.forEach(edge -> res.addEdge(edge.from, edge.to)); return res; }

Target:
public static <T> Digraph<T> buildFilteredDigraph(Digraph<T> initialGraph, Predicate<T> filterOut, Class<T> clazz) { Digraph<T> res = new Digraph<>(clazz); Set<Vertex<T>> toRemove = new LinkedHashSet<>(); for (Vertex<T> vertex : initialGraph.vertexList) { if (!filterOut.test(vertex.id)) { res.addVertex(vertex.id); } else { toRemove.add(vertex); } } Set<Edge<T>> edges = new LinkedHashSet<>(initialGraph.getEdges()); for (Vertex<T> vertexToRemove : toRemove) { Set<Edge<T>> incoming = edges.stream().filter(edge -> edge.to == vertexToRemove.id).collect(Collectors.toCollection(LinkedHashSet::new)); Set<Edge<T>> outgoing = edges.stream().filter(edge -> edge.from == vertexToRemove.id).collect(Collectors.toCollection(LinkedHashSet::new)); edges.removeAll(incoming); edges.removeAll(outgoing); incoming.forEach(incomingEdge -> outgoing.forEach(outgoingEdge -> edges.add(new Edge<>(incomingEdge.from, outgoingEdge.to)))); } edges.forEach(edge -> res.addEdge(edge.from, edge.to)); return res; }
Source:
public VelocityContext getConfiguredVelocityContext() { Properties p = new Properties(); p.setProperty(RuntimeConstants.RESOURCE_LOADER, "file, class"); p.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "/etc/sw360"); p.setProperty("file.resource.loader.class", FileResourceLoader.class.getName()); p.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(p); ToolManager velocityToolManager = new ToolManager(); velocityToolManager.configure(VELOCITY_TOOLS_FILE); return new VelocityContext(velocityToolManager.createContext()); }

Target:
public VelocityContext getConfiguredVelocityContext() { Properties p = new Properties(); p.setProperty(RuntimeConstants.RESOURCE_LOADER, "file, class"); p.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CommonUtils.SYSTEM_CONFIGURATION_PATH); p.setProperty("file.resource.loader.class", FileResourceLoader.class.getName()); p.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName()); Velocity.init(p); ToolManager velocityToolManager = new ToolManager(); velocityToolManager.configure(VELOCITY_TOOLS_FILE); return new VelocityContext(velocityToolManager.createContext()); }
Source:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { stderr.println("The Jenkins instance has not been started, or was already shut down!"); return -1; } final HashSet<String> hs = new HashSet<String>(); hs.addAll(nodes); for (String node_s : hs) { Node node = null; try { node = jenkins.getNode(node_s); if(node == null) { stderr.format("No such node '%s'\n", node_s); errorOccurred = true; continue; } try { node.checkPermission(Computer.DELETE); } catch (Exception e) { stderr.println(e.getMessage()); errorOccurred = true; continue; } jenkins.removeNode(node); } catch (Exception e) { stderr.format("Unexpected exception occurred during deletion of node '%s': %s\n", node == null ? "(null)" : node.toComputer().getName(), e.getMessage() ); errorOccurred = true; continue; } } return errorOccurred ? -1 : 0; }

Target:
protected int run() throws Exception { boolean errorOccurred = false; final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { stderr.println("The Jenkins instance has not been started, or was already shut down!"); return -1; } final HashSet<String> hs = new HashSet<String>(); hs.addAll(nodes); for (String node_s : hs) { Node node = null; try { node = jenkins.getNode(node_s); if(node == null) { stderr.format("No such node '%s'\n", node_s); errorOccurred = true; continue; } try { node.checkPermission(Computer.DELETE); } catch (Exception e) { stderr.println(e.getMessage()); errorOccurred = true; continue; } jenkins.removeNode(node); } catch (Exception e) { final String errorMsg = String.format("Unexpected exception occurred during deletion of node '%s': %s", node == null ? "(null)" : node.toComputer().getName(), e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; continue; } } return errorOccurred ? -1 : 0; }
Source:
public void setWillNotDraw(boolean willNotDraw) { if (willNotDraw) { throw new DeveloperError("setWillNotDraw(true) is not compatible with custom drawing."); } super.setWillNotDraw(false); }

Target:
public void setWillNotDraw(boolean willNotDraw) { throw new DeveloperError("Changing setWillNotDraw() is not compatible with custom drawing."); }
Source:
protected void run() throws UnloggedFailure, Failure, Exception { for (AccountGroup.Id groupId : groups) { GroupResource resource = toResource(groupId); if (!accountsToRemove.isEmpty()) { deleteMembers.apply(resource, fromMembers(accountsToRemove)); } if (!groupsToRemove.isEmpty()) { deleteIncludedGroups.apply(resource, fromGroups(groupsToRemove)); } if (!accountsToAdd.isEmpty()) { reportMembersAdded(resource.getName(), addMembers.apply(resource, fromMembers(accountsToAdd))); } if (!groupsToInclude.isEmpty()) { reportGroupsAdded(resource.getName(), addIncludedGroups.apply(resource, fromGroups(groupsToInclude))); } } }

Target:
protected void run() throws UnloggedFailure, Failure, Exception { for (AccountGroup.UUID groupUuid : groups) { GroupResource resource = groupsCollection.parse(TopLevelResource.INSTANCE, IdString.fromUrl(groupUuid.get())); if (!accountsToRemove.isEmpty()) { deleteMembers.get().apply(resource, fromMembers(accountsToRemove)); reportMembersAction("removed from", resource, accountsToRemove); } if (!groupsToRemove.isEmpty()) { deleteIncludedGroups.get().apply(resource, fromGroups(groupsToRemove)); reportGroupsAction("excluded from", resource, groupsToRemove); } if (!accountsToAdd.isEmpty()) { addMembers.get().apply(resource, fromMembers(accountsToAdd)); reportMembersAction("added to", resource, accountsToAdd); } if (!groupsToInclude.isEmpty()) { addIncludedGroups.get().apply(resource, fromGroups(groupsToInclude)); reportGroupsAction("included to", resource, groupsToInclude); } } }
Source:
public <B extends RenderedReport.Builder<B, ?>> CompletionStage<B> render( final S source, final F format, final TimeRange timeRange, final B builder, final Duration timeout ) { LOGGER.debug() .setMessage("rendering") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); final CompletableFuture<DevToolsService> createDts = CompletableFuture.supplyAsync(() -> _devToolsFactory.create(getIgnoreCertificateErrors(source), _chromeArgs) ); final CompletableFuture<B> result = createDts.thenCompose(dts -> dts.navigate(getUri(source).toString()).thenCompose(nothing -> { LOGGER.debug() .setMessage("page load completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); return whenLoaded(dts, source, format, timeRange, builder); }) ).toCompletableFuture(); result.whenComplete((x, e) -> { LOGGER.debug() .setMessage("rendering completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .addData("result", x) .addData("exception", e) .log(); createDts.thenAccept(DevToolsService::close); }); _timeoutExecutor.schedule(() -> result.cancel(true), timeout.toNanos(), TimeUnit.NANOSECONDS); return result; }

Target:
public <B extends RenderedReport.Builder<B, ?>> CompletionStage<B> render( final S source, final F format, final TimeRange timeRange, final B builder, final Duration timeout ) { LOGGER.debug() .setMessage("rendering") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); final CompletableFuture<DevToolsService> createDts = CompletableFuture.supplyAsync( () -> _devToolsFactory.create(getIgnoreCertificateErrors(source), _chromeArgs), _executor ); final CompletableFuture<B> result = createDts.thenCompose(dts -> dts.navigate(getUri(source).toString(), _executor).thenCompose(nothing -> { LOGGER.debug() .setMessage("page load completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .log(); return whenLoaded(dts, source, format, timeRange, builder); }) ).toCompletableFuture(); result.whenComplete((x, e) -> { LOGGER.debug() .setMessage("rendering completed") .addData("source", source) .addData("format", format) .addData("timeRange", timeRange) .addData("result", x) .addData("exception", e) .log(); createDts.thenAccept(DevToolsService::close); }); _executor.schedule(() -> result.cancel(true), timeout.toNanos(), TimeUnit.NANOSECONDS); return result; }
Source:
public void addReport(IOnDemandAnalysisReport report) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath nodePath = this.getResource().getFullPath(); String reportDisplayName = report.getName(); if (fCurrentReports.containsKey(reportDisplayName)) { reportDisplayName = reportDisplayName + " #2"; for (int nb = 3; fCurrentReports.containsKey(reportDisplayName); nb++) { Matcher matcher = DIGITS_AT_END_PATTERN.matcher(reportDisplayName); reportDisplayName = matcher.replaceFirst(String.valueOf(nb)); } } fCurrentReports.put(reportDisplayName, report); IFolder analysisRes = checkNotNull(root.getFolder(nodePath.append(reportDisplayName))); TmfReportElement elem = new TmfReportElement(reportDisplayName, analysisRes, this, report); addChild(elem); refresh(); }

Target:
public void addReport(IOnDemandAnalysisReport report) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath nodePath = getResource().getFullPath(); String reportDisplayName = report.getName(); int i = 1; while (fCurrentReports.containsKey(reportDisplayName)) { i++; reportDisplayName = report.getName() + " #" + i; } fCurrentReports.put(reportDisplayName, report); IFolder analysisRes = checkNotNull(root.getFolder(nodePath.append(reportDisplayName))); TmfReportElement elem = new TmfReportElement(reportDisplayName, analysisRes, this, report); addChild(elem); refresh(); }
Source:
private void emptyQueue() { if (restRequestInfoQueue.size() > 0) { logger.warn("There were residual RestRequestInfos in queue during shutdown", restRequestInfoQueue.size()); restServerMetrics.asyncRequestHandlerResidualQueueSize.inc(restRequestInfoQueue.size()); RestRequestInfo dequeuedPart = restRequestInfoQueue.poll(); while (dequeuedPart != null) { queuingTimeTracker.stopTracking(dequeuedPart, false); if (dequeuedPart.getRestRequestContent() != null) { dequeuedPart.getRestRequestContent().release(); } if (dequeuedPart.isFirstPart()) { requestsInFlight.putIfAbsent(dequeuedPart.getRestRequestMetadata(), true); } dequeuedPart = restRequestInfoQueue.poll(); } } logger.info("There were requests in flight when the DequeuedRequestHandler was shut down", requestsInFlight.size()); Iterator<Map.Entry<RestRequestMetadata, Boolean>> requestMetadata = requestsInFlight.entrySet().iterator(); while (requestMetadata.hasNext()) { requestMetadata.next().getKey().release(); requestMetadata.remove(); } }

Target:
private void emptyQueue() { if (restRequestInfoQueue.size() > 0) { logger.warn("There were residual RestRequestInfos in queue during shutdown", restRequestInfoQueue.size()); restServerMetrics.asyncRequestHandlerResidualQueueSize.inc(restRequestInfoQueue.size()); RestRequestInfo residualRestRequestInfo = restRequestInfoQueue.poll(); while (residualRestRequestInfo != null) { queuingTimeTracker.stopTracking(residualRestRequestInfo); if (residualRestRequestInfo.getRestRequestContent() != null) { residualRestRequestInfo.getRestRequestContent().release(); } if (residualRestRequestInfo.isFirstPart()) { requestsInFlight.putIfAbsent(residualRestRequestInfo.getRestRequestMetadata(), true); } residualRestRequestInfo = restRequestInfoQueue.poll(); } } logger.info("There were requests in flight when the AsyncRequestHandler was shut down", requestsInFlight.size()); Iterator<Map.Entry<RestRequestMetadata, Boolean>> requestMetadata = requestsInFlight.entrySet().iterator(); while (requestMetadata.hasNext()) { requestMetadata.next().getKey().release(); requestMetadata.remove(); } }
Source:
public PaymentMethod(String code, LocalizedString description) { super(); setBennu(Bennu.getInstance()); setCode(code); setDescription(description); createLog(Bundle.MESSAGING, "log.paymentMethod.created", code, description.getContent(I18N.getLocale())); }

Target:
public PaymentMethod(String code, LocalizedString description) { super(); setBennu(Bennu.getInstance()); setCode(code); setDescription(description); createLog(Bundle.MESSAGING, "log.paymentMethod.created", code, getFormattedDescriptionForLog(description)); }
Source:
private void validateVnicMappings(Action action) { if (!(action.isSetVnicProfileMappings() && action.getVnicProfileMappings().isSetVnicProfileMappings())) { return; } action.getVnicProfileMappings().getVnicProfileMappings().forEach(this::validateVnicProfileMapping); }

Target:
private void validateVnicMappings(Action action) { if (action.isSetVnicProfileMappings() && action.getVnicProfileMappings().isSetVnicProfileMappings()) { action.getVnicProfileMappings().getVnicProfileMappings().forEach(this::validateVnicProfileMapping); } }
Source:
public static IndexedFixtureIndex lookupIndexedFixturePaths(SQLiteDatabase db, String fixtureName) { Cursor c = db.query(INDEXED_FIXTURE_PATHS_TABLE, new String[]{INDEXED_FIXTURE_PATHS_COL_BASE, INDEXED_FIXTURE_PATHS_COL_CHILD, INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES}, INDEXED_FIXTURE_PATHS_COL_NAME + "=?", new String[]{fixtureName}, null, null, null); try { if (c.getCount() == 0) { return null; } else { c.moveToFirst(); TreeElement attrsHolder = null; byte[] attrsBlob = c.getBlob(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES)); if (attrsBlob != null) { attrsHolder = SerializationUtil.deserialize(attrsBlob, TreeElement.class); } return new IndexedFixtureIndex(fixtureName, c.getString(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_BASE)), c.getString(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_CHILD)), attrsHolder); } } finally { c.close(); } }

Target:
public static IndexedFixtureIdentifier lookupIndexedFixturePaths(SQLiteDatabase db, String fixtureName) { Cursor c = db.query(INDEXED_FIXTURE_PATHS_TABLE, new String[]{INDEXED_FIXTURE_PATHS_COL_BASE, INDEXED_FIXTURE_PATHS_COL_CHILD, INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES}, INDEXED_FIXTURE_PATHS_COL_NAME + "=?", new String[]{fixtureName}, null, null, null); try { if (c.getCount() == 0) { return null; } else { c.moveToFirst(); return new IndexedFixtureIdentifier( c.getString(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_BASE)), c.getString(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_CHILD)), c.getBlob(c.getColumnIndexOrThrow(INDEXED_FIXTURE_PATHS_COL_ATTRIBUTES))); } } finally { c.close(); } }
Source:
public SimpleScript(URL url, Serializable[] parameters) throws InvalidScriptException { super(url, parameters, !PASharedProperties.LAZY_FETCH_SCRIPT.getValueAsBoolean()); }

Target:
public SimpleScript(URL url, Serializable[] parameters) throws InvalidScriptException { super(url, parameters, !isLazyFetch()); }
Source:
public Job createJob(InputStream workflowStream, Map<String, String> replacementVariables, Map<String, String> replacementGenericInfos) throws JobCreationException { try { File temporaryJobContentFile = File.createTempFile("jobContent" + workflowStream.toString().replaceAll("\\W+", ""), ".tmp"); FileUtils.copyInputStreamToFile(workflowStream, temporaryJobContentFile); return createJob(temporaryJobContentFile, replacementVariables, replacementGenericInfos); } catch (JobCreationException jce) { throw jce; } catch (Exception e) { throw new JobCreationException(e); } }

Target:
public Job createJob(InputStream workflowStream, Map<String, String> replacementVariables, Map<String, String> replacementGenericInfos) throws JobCreationException { try { return createJobFromInputStream(workflowStream, replacementVariables, replacementGenericInfos); } catch (JobCreationException jce) { throw jce; } catch (Exception e) { throw new JobCreationException(e); } }
Source:
public void finishTree(DetailAST ast) { if (!defined) { if (ast == null) { log(1, 0, MSG_KEY_MISSING); } else { log(ast, MSG_KEY_MISSING); } } }

Target:
public void finishTree(DetailAST ast) { if (!defined) { if (ast == null) { log(DEFAULT_LINE_NUMBER, MSG_KEY_MISSING); } else { log(ast, MSG_KEY_MISSING); } } }
Source:
public void testRuleFlowGroup() throws Exception { }

Target:
public void testRuleFlowGroup() throws Exception { TrackingAgendaEventListener agenda = new TrackingAgendaEventListener(); RuntimeManager manager = deploymentService.getRuntimeManager(kieJar); RuntimeEngine engine = manager.getRuntimeEngine(ProcessInstanceIdContext.get()); engine.getKieSession().addEventListener(agenda); Long processInstanceId = startProcessInstance(PROCESS_ID); UserTransaction ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); processService.signalProcessInstance(processInstanceId, "start", "rfg"); Assertions.assertThat(hasNodeLeft(processInstanceId, "rfg")).isTrue(); ut.rollback(); agenda.clear(); processService.execute(kieJar, new FireAllRulesCommand()); Assertions.assertThat(agenda.isRuleFired("dummyRule")).isFalse(); agenda.clear(); ut = InitialContext.doLookup(USER_TRANSACTION_NAME); ut.begin(); processService.signalProcessInstance(processInstanceId, "start", "rfg"); ut.commit(); Assertions.assertThat(hasNodeLeft(processInstanceId, "rfg")).isTrue(); processService.execute(kieJar, new FireAllRulesCommand()); processService.signalProcessInstance(processInstanceId, "finish", null); Assertions.assertThat(agenda.isRuleFired("dummyRule")).isTrue(); Assertions.assertThat(hasProcessInstanceCompleted(processInstanceId)).isTrue(); }
Source:
public void waitOrganizationName(String name) { WaitUtils.sleepQuietly(1); redrawUiElementsTimeout.until( (WebDriver driver) -> driver .findElement(By.xpath(Locators.ORGANIZATION_NAME)) .getAttribute("value") .equals(name)); }

Target:
public void waitOrganizationName(String name) { redrawUiElementsTimeout.until( ExpectedConditions.attributeToBeNotEmpty(organizationName, "value")); redrawUiElementsTimeout.until( (WebDriver driver) -> driver .findElement(By.xpath(Locators.ORGANIZATION_NAME)) .getAttribute("value") .equals(name)); }
Source:
public Set<Xid> getInflightXids(String parentNodeName) { Iterator<TransactionImpleHolder> iterator = _transactions.values().iterator(); Set<Xid> toReturn = new HashSet<Xid>(); while (iterator.hasNext()) { TransactionImpleHolder next = iterator.next(); TransactionImple imported = null; try { imported = next.getImported(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (imported != null && imported.getParentNodeName().equals(parentNodeName)) { toReturn.add(imported.baseXid()); } } return toReturn; }

Target:
public Set<Xid> getInflightXids(String parentNodeName) { Iterator<AtomicReference<TransactionImple>> iterator = _transactions.values().iterator(); Set<Xid> toReturn = new HashSet<Xid>(); while (iterator.hasNext()) { AtomicReference<TransactionImple> holder = iterator.next(); TransactionImple imported = holder.get(); if (imported != null && imported.getParentNodeName().equals(parentNodeName)) { toReturn.add(imported.baseXid()); } } return toReturn; }
Source:
public RealmObjectSchema create(String className) { checkEmpty(className, EMPTY_STRING_MSG); String internalTableName = Table.getTableNameForClass(className); if (internalTableName.length() > Table.TABLE_MAX_LENGTH) { throw new IllegalArgumentException("Class name is too long. Limit is 56 characters: " + className.length()); } if (realm.getSharedRealm().hasTable(internalTableName)) { throw new IllegalArgumentException("Class already exists: " + className); } return new StandardRealmObjectSchema(realm, this, realm.getSharedRealm().createTable(internalTableName)); }

Target:
public RealmObjectSchema create(String className) { checkEmpty(className, EMPTY_STRING_MSG); String internalTableName = Table.getTableNameForClass(className); if (internalTableName.length() > Table.TABLE_MAX_LENGTH) { throw new IllegalArgumentException("Class name is too long. Limit is 56 characters: " + className.length()); } return new StandardRealmObjectSchema(realm, this, realm.getSharedRealm().createTable(internalTableName)); }
Source:
public String toString() { String name = getName(); if (name == null) { name = Participant.UNKNOWN_NAME; } StringBuilder sb = new StringBuilder(name); sb.append(": "); if (!alternatives.isEmpty()) { sb.append('[') .append(alternatives.get(0).getConfidence()) .append("] ") .append(alternatives.get(0).getTranscription()); } return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(getName()); sb.append(": "); if (!alternatives.isEmpty()) { sb.append('[') .append(alternatives.get(0).getConfidence()) .append("] ") .append(alternatives.get(0).getTranscription()); } return sb.toString(); }
Source:
public void setStreak(FeedData.Streak streak) { mStreak = streak; init(); }

Target:
public void setStreak(FeedData.Streak streak) { mStreak = streak; if(mStreak != null) { setOrientation(LinearLayout.VERTICAL); setGravity(Gravity.CENTER_VERTICAL); mLayoutContainer = (LinearLayout) getChildAt(0); mStreakBarContainer = (RelativeLayout) mLayoutContainer.getChildAt(0); mStreakBar = mStreakBarContainer.getChildAt(0); setBarHeight(mStreak.getCount()); mImageContainer = (RelativeLayout) mLayoutContainer.getChildAt(1); mStreakCheckImage = (ImageView) mImageContainer.getChildAt(0); mStreakDay = (TextView) mLayoutContainer.getChildAt(2); mStreakDay.setText(mStreak.getDayAbbrev()); if (!mStreak.completed()) { mStreakCheckImage.setVisibility(View.INVISIBLE); } } }
Source:
public Map<Dependency, FileValidationStatus> getValidationStatuses(final Set<Dependency> deps, final String validationKey) throws SQLException { Map<Dependency, FileValidationStatus> depValidationStatuses = new HashMap<>(); if (deps.size() == 0) { return depValidationStatuses; } Map<String, Dependency> hashAndFileNameToDep = new HashMap<>(); PreparedStatement stmnt = this.dbOperator.getDataSource().getConnection().prepareStatement( "select file_name, file_sha1, validation_status from validated_dependencies where validation_key = ? and (" + makeStrWithQuestionMarks(deps.size()) + ")"); stmnt.setString(1, validationKey); int index = 2; for (Dependency d : deps) { stmnt.setString(index++, d.getFileName()); stmnt.setString(index++, d.getSHA1()); hashAndFileNameToDep.put(d.getFileName() + d.getSHA1(), d); } ResultSet rs = stmnt.executeQuery(); while (rs.next()) { Dependency d = hashAndFileNameToDep.remove(rs.getString(1) + rs.getString(2)); FileValidationStatus v = FileValidationStatus.valueOf(rs.getInt(3)); depValidationStatuses.put(d, v); } hashAndFileNameToDep.values().stream().forEach(d -> depValidationStatuses.put(d, FileValidationStatus.NEW)); return depValidationStatuses; }

Target:
public Map<Dependency, FileValidationStatus> getValidationStatuses(final Set<Dependency> deps, final String validationKey) throws SQLException { Map<Dependency, FileValidationStatus> depValidationStatuses = new HashMap<>(); if (deps.isEmpty()) { return depValidationStatuses; } Map<String, Dependency> hashAndFileNameToDep = new HashMap<>(); PreparedStatement stmnt = this.dbOperator.getDataSource().getConnection().prepareStatement( String.format("SELECT file_name, file_sha1, validation_status FROM validated_dependencies " + "WHERE validation_key = ? AND (%s)", makeStrWithQuestionMarks(deps.size()))); stmnt.setString(1, validationKey); int index = 2; for (Dependency d : deps) { stmnt.setString(index++, d.getFileName()); stmnt.setString(index++, d.getSHA1()); hashAndFileNameToDep.put(d.getFileName() + d.getSHA1(), d); } ResultSet rs = stmnt.executeQuery(); while (rs.next()) { Dependency d = hashAndFileNameToDep.remove(rs.getString(1) + rs.getString(2)); FileValidationStatus v = FileValidationStatus.valueOf(rs.getInt(3)); depValidationStatuses.put(d, v); } hashAndFileNameToDep.values().stream().forEach(d -> depValidationStatuses.put(d, FileValidationStatus.NEW)); return depValidationStatuses; }
Source:
public void shouldHaveHealthMetricConfiguredGloballyOnSystemProperty() throws Exception { assertThat("if used .ADD_HEALTH_METRICS system property, global configuration should have all folder health metrics", AbstractFolderConfiguration.get().getHealthMetrics(), hasSize((int) FolderHealthMetricDescriptor.all().stream().filter(d -> d.createDefault() != null).count())); Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); DescribableList<FolderHealthMetric, FolderHealthMetricDescriptor> healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics.toList(), containsInAnyOrder(AbstractFolderConfiguration.get().getHealthMetrics().toArray())); AbstractFolderConfiguration.get().setHealthMetrics(null); folder = j.jenkins.createProject(Folder.class, "myFolder2"); healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics, iterableWithSize(0)); System.clearProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS"); }

Target:
public void shouldHaveHealthMetricConfiguredGloballyOnSystemProperty() throws Exception { assertThat("if used .ADD_HEALTH_METRICS system property, global configuration should have all folder health metrics", AbstractFolderConfiguration.get().getHealthMetrics(), hasSize((int) FolderHealthMetricDescriptor.all().stream().filter(d -> d.createDefault() != null).count())); Folder folder = j.jenkins.createProject(Folder.class, "myFolder"); DescribableList<FolderHealthMetric, FolderHealthMetricDescriptor> healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics.toList(), containsInAnyOrder(AbstractFolderConfiguration.get().getHealthMetrics().toArray())); AbstractFolderConfiguration.get().setHealthMetrics(null); folder = j.jenkins.createProject(Folder.class, "myFolder2"); healthMetrics = folder.getHealthMetrics(); assertThat("a new created folder should have all the folder health metrics configured globally", healthMetrics, iterableWithSize(0)); }
Source:
private void includeGlobalResources(Config config) { PageFactory pageFactory = Context.getRegisteredComponents(PageFactory.class).get(0); GlobalResourceIncluder globalResourceIncluder = new GlobalResourceIncluder(); String cssResourcePath = "styles/".concat(config.getCountry().name().toLowerCase()).concat(".").concat(Resource.CATEGORY_CSS); String jsResourcePath = "scripts/".concat(config.getCountry().name().toLowerCase()).concat(".").concat(Resource.CATEGORY_JS); globalResourceIncluder.addResource(new Resource(Resource.CATEGORY_CSS, MirebalaisConstants.MIREBALAIS_MODULE_ID, cssResourcePath, -100)); globalResourceIncluder.addResource(new Resource(Resource.CATEGORY_JS, MirebalaisConstants.MIREBALAIS_MODULE_ID, jsResourcePath, null)); pageFactory.getModelConfigurators().add(globalResourceIncluder); }

Target:
private void includeGlobalResources(Config config) { String cssResourcePath = "styles/".concat(config.getCountry().name().toLowerCase()).concat(".").concat(Resource.CATEGORY_CSS); String providerName = MirebalaisConstants.MIREBALAIS_MODULE_ID; ResourceFactory resourceFactory = ResourceFactory.getInstance(); File resource = resourceFactory.getResource(providerName, cssResourcePath); if (resource != null) { PageFactory pageFactory = Context.getRegisteredComponents(PageFactory.class).get(0); GlobalResourceIncluder globalResourceIncluder = new GlobalResourceIncluder(); globalResourceIncluder.addResource(new Resource(Resource.CATEGORY_CSS, providerName, cssResourcePath, -100)); pageFactory.getModelConfigurators().add(globalResourceIncluder); } }
Source:
public ChannelSetBuilder(Type type, Optional<Integer> hashChannel, int expectedPositions, OperatorContext operatorContext, JoinCompiler joinCompiler) { List<Type> types = ImmutableList.of(type); this.hash = createGroupByHash( types, HASH_CHANNELS, hashChannel, expectedPositions, isDictionaryAggregationEnabled(operatorContext.getSession()), joinCompiler, this::updateMemoryReservation); this.operatorContext = operatorContext; this.nullBlockPage = new Page(type.createBlockBuilder(new BlockBuilderStatus(), 1, UNKNOWN.getFixedSize()).appendNull().build()); }

Target:
public ChannelSetBuilder(Type type, Optional<Integer> hashChannel, int expectedPositions, OperatorContext operatorContext, JoinCompiler joinCompiler) { List<Type> types = ImmutableList.of(type); this.hash = createGroupByHash( types, HASH_CHANNELS, hashChannel, expectedPositions, isDictionaryAggregationEnabled(operatorContext.getSession()), joinCompiler, this::updateMemoryReservation); this.nullBlockPage = new Page(type.createBlockBuilder(new BlockBuilderStatus(), 1, UNKNOWN.getFixedSize()).appendNull().build()); this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.localMemoryContext = operatorContext.localUserMemoryContext(); }
Source:
protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IMap<Integer, SerializedPage> map = hazelcast.getMap(sessionIdentifier); if (map != null) { SerializedPage page = map.get(id); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Got for session '{}' and page id '{}'", page, sessionIdentifier, id); } if (page != null) { return page; } } return null; }

Target:
protected IManageablePage getPersistedPage(String sessionIdentifier, int id) { IMap<Integer, SerializedPage> map = hazelcast.getMap(sessionIdentifier); if (map != null) { SerializedPage page = map.get(id); LOGGER.debug("Got for session '{}' and page id '{}'", page, sessionIdentifier, id); if (page != null) { return page; } } return null; }
Source:
private CompletionStage<String> convertId(String input, RestRequest restRequest) throws RestServiceException, IOException { CompletionStage<String> conversionFuture; if (input.startsWith(NAMED_BLOB_PREFIX)) { String[] slashFields = parseInput(input); conversionFuture = get(slashFields[2], slashFields[3], slashFields[4]); } else if (restRequest.getRestMethod().equals(RestMethod.PUT) && restRequest.getUri().startsWith(NAMED_BLOB_PREFIX)) { String[] slashFields = parseInput(restRequest.getPath()); StoreKey blobId = new BlobId(RestUtils.stripSlashAndExtensionFromId(input), clusterMap); conversionFuture = put(slashFields[2], slashFields[3], slashFields[4], blobId); } else { String decryptedInput = parseSignedIdIfRequired(restRequest, input.startsWith("/") ? input.substring(1) : input); conversionFuture = CompletableFuture.completedFuture(RestUtils.stripSlashAndExtensionFromId(decryptedInput)); } return conversionFuture; }

Target:
private CompletionStage<String> convertId(String input, RestRequest restRequest) throws RestServiceException { CompletionStage<String> conversionFuture; if (input.startsWith(NAMED_BLOB_PREFIX)) { NamedBlobPath namedBlobPath = RestUtils.parseInput(input); conversionFuture = get(namedBlobPath.getAccountName(), namedBlobPath.getContainerName(), namedBlobPath.getBlobName()); } else if (restRequest.getRestMethod().equals(RestMethod.PUT) && restRequest.getUri() .startsWith(NAMED_BLOB_PREFIX)) { NamedBlobPath namedBlobPath = RestUtils.parseInput(RestUtils.getRequestPath(restRequest).getOperationOrBlobId(false)); String blobId = RestUtils.stripSlashAndExtensionFromId(input); conversionFuture = put(namedBlobPath.getAccountName(), namedBlobPath.getContainerName(), namedBlobPath.getBlobName(), blobId); } else { String decryptedInput = parseSignedIdIfRequired(restRequest, input.startsWith("/") ? input.substring(1) : input); conversionFuture = CompletableFuture.completedFuture(RestUtils.stripSlashAndExtensionFromId(decryptedInput)); } return conversionFuture; }
Source:
protected void writeJson(HttpServletRequest req, HttpServletResponse res, JsonNode json) throws IOException { String type = getParam(req, "type", "json"); res.setCharacterEncoding("UTF-8"); boolean debug = getBooleanParam(req, "debug", false) || getBooleanParam(req, "pretty", false); if ("jsonp".equals(type)) { res.setContentType("application/javascript"); if (!jsonpAllowed) { writeError(res, SC_BAD_REQUEST, "Server is not configured to allow jsonp!"); return; } String callbackName = getParam(req, "callback", null); if (callbackName == null) { writeError(res, SC_BAD_REQUEST, "No callback provided, necessary if type=jsonp"); return; } if (debug) writeResponse(res, callbackName + "(" + objectMapper.writeValueAsString(json) + ")"); else writeResponse(res, callbackName + "(" + objectMapper.writeValueAsString(json) + ")"); } else { res.setContentType("application/json"); if (debug) writeResponse(res, objectMapper.writeValueAsString(json) ); else writeResponse(res, objectMapper.writeValueAsString(json) ); } }

Target:
protected void writeJson(HttpServletRequest req, HttpServletResponse res, JsonNode json) throws IOException { String type = getParam(req, "type", "json"); res.setCharacterEncoding("UTF-8"); final boolean indent = getBooleanParam(req, "debug", false) || getBooleanParam(req, "pretty", false); ObjectWriter objectWriter = indent ? objectMapper.writer().with(SerializationFeature.INDENT_OUTPUT) : objectMapper.writer(); if ("jsonp".equals(type)) { res.setContentType("application/javascript"); if (!jsonpAllowed) { writeError(res, SC_BAD_REQUEST, "Server is not configured to allow jsonp!"); return; } String callbackName = getParam(req, "callback", null); if (callbackName == null) { writeError(res, SC_BAD_REQUEST, "No callback provided, necessary if type=jsonp"); return; } writeResponse(res, callbackName + "(" + objectWriter.writeValueAsString(json) + ")"); } else { res.setContentType("application/json"); writeResponse(res, objectWriter.writeValueAsString(json)); } }
Source:
public HDFSDDFManager(String fsUri) throws DDFException { assert !Strings.isNullOrEmpty(fsUri); this.fsUri = fsUri; try { Configuration conf; if (fsUri.equals("hdfs:;")) { conf = SparkHadoopUtil.get().conf(); } else { conf = new Configuration(); conf.set("fs.defaultFS", fsUri); } this.fs = FileSystem.get(conf); } catch (Exception e) { throw new DDFException(e); } Logger.getLogger(HDFSDDFManager.class).info("Init HDFSDDFManager( fsUri="+fsUri +")"); Logger.getLogger(HDFSDDFManager.class).info("-- FS Scheme:"+fs.getScheme()+")"); Logger.getLogger(HDFSDDFManager.class).info("-- FS URI:"+fs.getUri()+")"); }

Target:
public HDFSDDFManager(String fsUri) throws DDFException { assert !Strings.isNullOrEmpty(fsUri); this.fsUri = fsUri; try { Configuration conf; if (fsUri.equals("hdfs:;")) { conf = SparkHadoopUtil.get().conf(); } else { conf = new Configuration(); conf.set("fs.defaultFS", fsUri); } this.fs = FileSystem.get(conf); } catch (Exception e) { throw new DDFException(e); } }
Source:
private Map<SystemStreamPartition, TaskSideInputStorageManager> createSideInputStorageManagers(Clock clock) { Map<SystemStreamPartition, TaskSideInputStorageManager> sideInputStorageManagers = new HashMap<>(); containerModel.getTasks().forEach((taskName, taskModel) -> { if (!sideInputSystemStreams.isEmpty()) { Map<String, StorageEngine> sideInputStores = getSideInputStores(taskName); Map<String, Set<SystemStreamPartition>> sideInputStoresToSSPs = new HashMap<>(); for (String storeName : sideInputStores.keySet()) { Set<SystemStreamPartition> storeSSPs = taskSideInputSSPs.get(taskName).get(storeName); sideInputStoresToSSPs.put(storeName, storeSSPs); } TaskSideInputStorageManager taskSideInputStorageManager = new TaskSideInputStorageManager(taskName, taskModel.getTaskMode(), streamMetadataCache, loggedStoreBaseDirectory, sideInputStores, taskSideInputProcessors.get(taskName), sideInputStoresToSSPs, systemAdmins, config, clock); sideInputStoresToSSPs.values().stream().flatMap(Set::stream).forEach(ssp -> { sideInputStorageManagers.put(ssp, taskSideInputStorageManager); }); LOG.info("Created taskSideInputStorageManager for task {}, sideInputStores and loggedStoreBaseDirectory {}", taskName, sideInputStores, loggedStoreBaseDirectory); } }); return sideInputStorageManagers; }

Target:
private Map<SystemStreamPartition, TaskSideInputStorageManager> createSideInputStorageManagers(Clock clock) { Map<TaskName, Map<String, SideInputsProcessor>> taskSideInputProcessors = createSideInputProcessors(new StorageConfig(config), this.containerModel, this.sideInputSystemStreams, this.taskInstanceMetrics); Map<SystemStreamPartition, TaskSideInputStorageManager> sideInputStorageManagers = new HashMap<>(); if (sideInputsPresent()) { containerModel.getTasks().forEach((taskName, taskModel) -> { Map<String, StorageEngine> sideInputStores = getSideInputStores(taskName); Map<String, Set<SystemStreamPartition>> sideInputStoresToSSPs = new HashMap<>(); for (String storeName : sideInputStores.keySet()) { Set<SystemStreamPartition> storeSSPs = taskSideInputSSPs.get(taskName).get(storeName); sideInputStoresToSSPs.put(storeName, storeSSPs); } TaskSideInputStorageManager taskSideInputStorageManager = new TaskSideInputStorageManager(taskName, taskModel.getTaskMode(), streamMetadataCache, loggedStoreBaseDirectory, sideInputStores, taskSideInputProcessors.get(taskName), sideInputStoresToSSPs, systemAdmins, config, clock); sideInputStoresToSSPs.values().stream().flatMap(Set::stream).forEach(ssp -> { sideInputStorageManagers.put(ssp, taskSideInputStorageManager); }); LOG.info("Created taskSideInputStorageManager for task {}, sideInputStores and loggedStoreBaseDirectory {}", taskName, sideInputStores, loggedStoreBaseDirectory); }); } return sideInputStorageManagers; }
Source:
public static void main(String[] args) { Configuration config = new Configuration(args); try { if (!config.validate()) { System.exit(-1); } else { if (config.m_startAction == StartAction.GET) { cli(config); } else { initialize(config); instance().run(); } } } catch (OutOfMemoryError e) { new VoltLogger("HOST").fatal("VoltDB has encountered an OutOfMemory error."); String errmsg = "VoltDB Main thread: ran out of Java memory. This node will shut down."; VoltDB.crashLocalVoltDB(errmsg, false, e); } }

Target:
public static void main(String[] args) { Configuration config = new Configuration(args); try { if (!config.validate()) { System.exit(-1); } else { if (config.m_startAction == StartAction.GET) { cli(config); } else { initialize(config); instance().run(); } } } catch (OutOfMemoryError e) { String errmsg = "VoltDB Main thread: ran out of Java memory. This node will shut down."; VoltDB.crashLocalVoltDB(errmsg, false, e); } }
Source:
public void start() throws Exception { for (TrackerServer server: serverList) { try { server.start(); } catch (BindException e) { LOGGER.warn("One of the protocols is disabled due to port conflict: " + server.getPort()); } } }

Target:
public void start() throws Exception { for (TrackerServer server: serverList) { try { server.start(); } catch (BindException e) { LOGGER.warn("Port %d is disabled due to conflict", server.getPort()); } } }
Source:
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application .showBanner(true) .sources(ResourceServer.class); }

Target:
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { application.application().setDefaultProperties(NAMING_STRATEGY); return application.sources(ResourceServer.class); }
Source:
public void updateUsage(List<Quota> quotaList) { lock.writeLock().lock(); try { for (Quota quotaExternal : quotaList) { Quota quota = null; for (Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { quota = quotaMap.get(quotaExternal.getId()); if (quota != null) { break; } } if (quota == null) { quota = getQuotaDAO().getById(quotaExternal.getId()); if (quota != null) { if (!storagePoolQuotaMap.containsKey(quota.getStoragePoolId())) { storagePoolQuotaMap.put(quota.getStoragePoolId(), new HashMap<Guid, Quota>()); } storagePoolQuotaMap.get(quota.getStoragePoolId()).put(quota.getId(), quota); } } copyUsageData(quota, quotaExternal); } } finally { lock.writeLock().unlock(); } }

Target:
public void updateUsage(List<Quota> quotaList) { List<Quota> needToCache = new ArrayList<Quota>(); lock.readLock().lock(); try { for (Quota quotaExternal : quotaList) { Quota quota = null; for (Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { quota = quotaMap.get(quotaExternal.getId()); if (quota != null) { break; } } if (quota == null) { needToCache.add(quotaExternal); } else { copyUsageData(quota, quotaExternal); } } } finally { lock.readLock().unlock(); } if (!needToCache.isEmpty()) { lock.writeLock().lock(); try { for (Quota quotaExternal : needToCache) { Quota quota = null; for (Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { quota = quotaMap.get(quotaExternal.getId()); if (quota != null) { break; } } if (quota == null) { quota = getQuotaDAO().getById(quotaExternal.getId()); if (quota != null) { if (!storagePoolQuotaMap.containsKey(quota.getStoragePoolId())) { storagePoolQuotaMap.put(quota.getStoragePoolId(), new HashMap<Guid, Quota>()); } storagePoolQuotaMap.get(quota.getStoragePoolId()).put(quota.getId(), quota); } } copyUsageData(quota, quotaExternal); } } finally { lock.writeLock().unlock(); } } }