auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); if (getMarshallerType() == Marshaller.NEW) { assertNotNull(executionSet.getCancelActivity()); assertNotNull(executionSet.getSlaDueDate()); assertEquals(isCancelling, executionSet.getCancelActivity().getValue()); assertEquals(slaDueDate, executionSet.getSlaDueDate().getValue()); } assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); }

Target:
private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); assertEventCancelActivity(executionSet, isCancelling); assertTimerEventSlaDueDate(executionSet, slaDueDate); }
Source:
public String getArchive(String archiveId) { String responseString = null; Future<Response> request = null; String url = this.apiUrl+"/v2/partner/"+this.apiKey+"/archive/"+archiveId; try { request = this.prepareGet(url).execute(); } catch (IOException e) { e.printStackTrace(); } try { Response response = request.get(); responseString = response.getResponseBody(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseString; }

Target:
public String getArchive(String archiveId) throws RequestException { String responseString = null; Future<Response> request = null; String url = this.apiUrl + "/v2/partner/" + this.apiKey + "/archive/" + archiveId; try { request = this.prepareGet(url).execute(); } catch (IOException e) { throw new RequestException("Could not get an OpenTok Archive", e); } try { Response response = request.get(); switch (response.getStatusCode()) { case 200: responseString = response.getResponseBody(); break; case 400: throw new RequestException("Could not get an OpenTok Archive. The archiveId was invalid. " + "archiveId: " + archiveId); case 403: throw new RequestException("Could not get an OpenTok Archive. The request was not authorized."); case 500: throw new RequestException("Could not get an OpenTok Archive. A server error occurred."); default: throw new RequestException("Could not get an OpenTok Archive. The server response was invalid." + " response code: " + response.getStatusCode()); } } catch (InterruptedException e) { throw new RequestException("Could not get an OpenTok Archive", e); } catch (ExecutionException e) { throw new RequestException("Could not get an OpenTok Archive", e); } catch (IOException e) { throw new RequestException("Could not get an OpenTok Archive", e); } return responseString; }
Source:
private void showCaseDetails(int selectedRowViewIdx) { String caseDisplayName = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noCaseNameError(); String details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(); try { if (-1 != selectedRowViewIdx) { EamDb dbManager = EamDb.getInstance(); int selectedRowModelIdx = filesTable.convertRowIndexToModel(selectedRowViewIdx); List<OtherOccurrenceNodeData> rowList = filesTableModel.getListOfNodesForFile(selectedRowModelIdx); if (rowList.get(0) instanceof OtherOccurrenceNodeInstanceData) { if (!rowList.isEmpty()) { CorrelationCase eamCasePartial = ((OtherOccurrenceNodeInstanceData) rowList.get(0)).getCorrelationAttributeInstance().getCorrelationCase(); caseDisplayName = eamCasePartial.getDisplayName(); CorrelationCase eamCase = dbManager.getCaseByUUID(eamCasePartial.getCaseUUID()); if (eamCase != null) { details = eamCase.getCaseDetailsOptionsPaneDialog(); } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(); } } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetailsReference(); } } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_notSelected(); } } } catch (EamDbException ex) { LOGGER.log(Level.SEVERE, "Error loading case details", ex); } finally { JOptionPane.showConfirmDialog(showCaseDetailsMenuItem, details, caseDisplayName, DEFAULT_OPTION, PLAIN_MESSAGE); } }

Target:
private void showCaseDetails(int selectedRowViewIdx) { String caseDisplayName = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noCaseNameError(); String details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(); try { if (-1 != selectedRowViewIdx) { EamDb dbManager = EamDb.getInstance(); int selectedRowModelIdx = filesTable.convertRowIndexToModel(selectedRowViewIdx); List<OtherOccurrenceNodeData> rowList = filesTableModel.getListOfNodesForFile(selectedRowModelIdx); if (!rowList.isEmpty()) { if (rowList.get(0) instanceof OtherOccurrenceNodeInstanceData) { CorrelationCase eamCasePartial = ((OtherOccurrenceNodeInstanceData) rowList.get(0)).getCorrelationAttributeInstance().getCorrelationCase(); caseDisplayName = eamCasePartial.getDisplayName(); CorrelationCase eamCase = dbManager.getCaseByUUID(eamCasePartial.getCaseUUID()); if (eamCase != null) { details = eamCase.getCaseDetailsOptionsPaneDialog(); } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetails(); } } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_notSelected(); } } else { details = Bundle.DataContentViewerOtherCases_caseDetailsDialog_noDetailsReference(); } } } catch (EamDbException ex) { LOGGER.log(Level.SEVERE, "Error loading case details", ex); } finally { JOptionPane.showConfirmDialog(showCaseDetailsMenuItem, details, caseDisplayName, DEFAULT_OPTION, PLAIN_MESSAGE); } }
Source:
private void show(final DirCacheTree tree) { out.print("\""); out.print(tree.getPathString()); out.print("\""); out.print(": "); out.print(tree.getEntrySpan()); out.print(" "); out.print(CLIText.get().entriesLabel); out.print(", "); out.print(tree.getChildCount()); out.print(" "); out.print(CLIText.get().childrenLabel); out.println(); for (int i = 0; i < tree.getChildCount(); i++) show(tree.getChild(i)); }

Target:
private void show(final DirCacheTree tree) { out.println(MessageFormat.format(CLIText.get().cacheTreePathInfo , tree.getPathString(), tree.getEntrySpan(), tree.getChildCount())); for (int i = 0; i < tree.getChildCount(); i++) show(tree.getChild(i)); }
Source:
public SortedMap<String, ReadyCheck.Result> runReadyChecks(ExecutorService executor) { final Map<String, Future<ReadyCheck.Result>> futures = new HashMap<>(); for (final Map.Entry<String, ReadyCheck> entry : readyChecks.entrySet()) { final String name = entry.getKey(); final ReadyCheck readyCheck = entry.getValue(); futures.put(name, executor.submit(readyCheck::execute)); } final SortedMap<String, ReadyCheck.Result> results = new TreeMap<>(); for (Map.Entry<String, Future<ReadyCheck.Result>> entry : futures.entrySet()) { try { results.put(entry.getKey(), entry.getValue().get()); } catch (Exception e) { LOGGER.warn("Error executing ready check {}", entry.getKey(), e); results.put(entry.getKey(), ReadyCheck.Result.unready(e)); } } return Collections.unmodifiableSortedMap(results); }

Target:
public SortedMap<String, Result> runReadyChecks(ExecutorService executor) { final Map<String, Future<Result>> futures = new HashMap<>(); for (final Map.Entry<String, ReadyCheck> entry : readyChecks.entrySet()) { final String name = entry.getKey(); final ReadyCheck readyCheck = entry.getValue(); futures.put(name, executor.submit(readyCheck::execute)); } final SortedMap<String, Result> results = new TreeMap<>(); for (Map.Entry<String, Future<Result>> entry : futures.entrySet()) { try { results.put(entry.getKey(), entry.getValue().get()); } catch (Exception e) { LOGGER.warn("Error executing ready check {}", entry.getKey(), e); results.put(entry.getKey(), Result.unready(e)); } } return Collections.unmodifiableSortedMap(results); }
Source:
private void joinGame(Pane gameBox, Specializations spec) { System.out.println("trying to join game"); try { if(broker != null) { broker.unregisterAll(this); } broker = new Broker(); broker.register(Observation.SERVER_OFFLINE, this, (Observable, data)->brokerException()); GameDTO map = ibs.joinGame(clientPlayer.getId(), spec.getValue()); try { broker.readSessionId(map.getSessionId()); } catch (IOException e) { e.printStackTrace(); } clientPlayer.createNewCharacter(map.getCharacterId(), spec); cMap = new ClientMap(map, gameBox, broker, clientPlayer); inGame = true; } catch (RemoteException e) { e.printStackTrace(); } characterController = new CharacterController(clientPlayer.getCharacter(), gameBox, sceneRelativeLocation); cMap.activate(); }

Target:
private void joinGame(Pane gameBox, Specializations spec) { System.out.println("trying to join game"); try { if(cMap != null) { cMap.getBroker().unregisterAll(this); } Broker broker = new Broker(); broker.register(Observation.SERVER_OFFLINE, this, (Observable, data)->brokerError()); GameDTO map = ibs.joinGame(clientPlayer.getId(), spec.getValue()); try { broker.readSessionId(map.getSessionId()); } catch (IOException e) { e.printStackTrace(); } clientPlayer.createNewCharacter(map.getCharacterId(), spec); cMap = new ClientMap(map, gameBox, broker, clientPlayer); inGame = true; } catch (RemoteException e) { e.printStackTrace(); } characterController = new CharacterController(clientPlayer.getCharacter(), gameBox, sceneRelativeLocation); cMap.activate(); }
Source:
public Set<DataSegment> findUsedSegments(Set<SegmentIdWithShardSpec> identifiers) throws IOException { final Map<String, Set<SegmentIdWithShardSpec>> identifiersByDataSource = new TreeMap<>(); for (SegmentIdWithShardSpec identifier : identifiers) { identifiersByDataSource.putIfAbsent(identifier.getDataSource(), new HashSet<>()); identifiersByDataSource.get(identifier.getDataSource()).add(identifier); } final Set<DataSegment> retVal = new HashSet<>(); for (Map.Entry<String, Set<SegmentIdWithShardSpec>> entry : identifiersByDataSource.entrySet()) { final List<Interval> intervals = JodaUtils.condenseIntervals( Iterables.transform(entry.getValue(), input -> input.getInterval()) ); final List<DataSegment> usedSegmentsForIntervals = taskActionClient.submit( new SegmentListUsedAction(entry.getKey(), null, intervals) ); for (DataSegment segment : usedSegmentsForIntervals) { if (identifiers.contains(SegmentIdWithShardSpec.fromDataSegment(segment))) { retVal.add(segment); } } } return retVal; }

Target:
public Set<DataSegment> findUsedSegments(Set<SegmentIdWithShardSpec> identifiers) throws IOException { final Map<String, Set<SegmentIdWithShardSpec>> identifiersByDataSource = new TreeMap<>(); for (SegmentIdWithShardSpec identifier : identifiers) { identifiersByDataSource.computeIfAbsent(identifier.getDataSource(), k -> new HashSet<>()); identifiersByDataSource.get(identifier.getDataSource()).add(identifier); } final Set<DataSegment> retVal = new HashSet<>(); for (Map.Entry<String, Set<SegmentIdWithShardSpec>> entry : identifiersByDataSource.entrySet()) { final List<Interval> intervals = JodaUtils.condenseIntervals( Iterables.transform(entry.getValue(), input -> input.getInterval()) ); final List<DataSegment> usedSegmentsForIntervals = taskActionClient.submit( new SegmentListUsedAction(entry.getKey(), null, intervals) ); for (DataSegment segment : usedSegmentsForIntervals) { if (identifiers.contains(SegmentIdWithShardSpec.fromDataSegment(segment))) { retVal.add(segment); } } } return retVal; }
Source:
private boolean ensureCountsEqual(Map<String, Integer> beforeCounts, Map<String, Integer> afterCounts) throws Exception { if (beforeCounts.size() != afterCounts.size()) { System.err.println("There are a different number of tables."); return false; } for (String key : beforeCounts.keySet()) { if (beforeCounts.get(key) != afterCounts.get(key)) { System.err.println("The " + key + " table has a different number of rows (" + beforeCounts.get(key) + " before, " + afterCounts.get(key) + " after)."); showTableContents(key); return false; } } return true; }

Target:
private boolean ensureCountsEqual(Map<String, Integer> beforeCounts, Map<String, Integer> afterCounts) throws Exception { for (String key : beforeCounts.keySet()) { if (beforeCounts.get(key) != afterCounts.get(key)) { System.err.println("The " + key + " table has a different number of rows (" + beforeCounts.get(key) + " before, " + afterCounts.get(key) + " after)."); return false; } } return true; }
Source:
public void testGetAccount() { Account account = api().getMyAccount(); assertNotNull(account); assertEquals("devlab1-online-vendor-devuser1", account.userName()); assertEquals("Donal Lunny", account.fullName()); assertEquals("Donal", account.firstName()); assertEquals("Lunny", account.lastName()); assertEquals("devlab1-online-vendor-devuser1@opsource.net", account.emailAddress()); assertThat(account.roles().contains(Account.RoleType.create("storage"))); assertThat(account.roles().contains(Account.RoleType.create("primary administrator"))); assertEquals("1", account.phone().countryCode()); assertEquals("1234567", account.phone().number()); assertEquals("6ac1e746-b1ea-4da5-a24e-caf1a978789d", account.organization().id()); assertEquals("Eng Customer of DevLab1-homed online sign-up Vendor", account.organization().name()); assertEquals("DevLab1Geo1", account.organization().homeGeoName()); assertEquals("apidevlab1.opsourcecloud.net", account.organization().homeGeoApiHost()); assertEquals("DEVLAB1GEO1", account.organization().homeGeoId()); assertEquals("NORMAL", account.state()); }

Target:
public void testGetAccount() { Account account = api().getMyAccount(); assertNotNull(account); assertNotNull(account.userName()); assertNotNull(account.fullName()); assertNotNull(account.firstName()); assertNotNull(account.lastName()); assertNotNull(account.emailAddress()); assertNotNull(account.organization()); assertNotNull(account.organization().id()); assertNotNull(account.organization().name()); assertNotNull(account.organization().homeGeoName()); assertNotNull(account.organization().homeGeoApiHost()); assertNotNull(account.organization().homeGeoId()); assertNotNull(account.state()); }
Source:
public void testUpdateConflictAccounts() throws Exception { Collection<Account> idConflictAccounts = new ArrayList<>(); idConflictAccounts.add(new AccountBuilder((short) 1, "account1", Account.AccountStatus.INACTIVE, null).build()); idConflictAccounts.add(new AccountBuilder((short) 1, "account2", Account.AccountStatus.INACTIVE, null).build()); try { createOrUpdateAccountsAndWait(idConflictAccounts); fail("Should have thrown."); } catch (IllegalArgumentException e) { } assertEquals("Wrong number of accounts in accountService", 0, accountService.getAllAccounts().size()); Collection<Account> nameConflictAccounts = new ArrayList<>(); nameConflictAccounts.add(new AccountBuilder((short) 1, "account1", Account.AccountStatus.INACTIVE, null).build()); nameConflictAccounts.add(new AccountBuilder((short) 2, "account1", Account.AccountStatus.INACTIVE, null).build()); try { createOrUpdateAccountsAndWait(nameConflictAccounts); fail("Should have thrown."); } catch (IllegalArgumentException e) { } assertEquals("Wrong number of accounts in accountService", 0, accountService.getAllAccounts().size()); }

Target:
public void testUpdateConflictAccounts() throws Exception { Collection<Account> idConflictAccounts = new ArrayList<>(); idConflictAccounts.add(new AccountBuilder((short) 1, "account1", Account.AccountStatus.INACTIVE, null).build()); idConflictAccounts.add(new AccountBuilder((short) 1, "account2", Account.AccountStatus.INACTIVE, null).build()); try { createOrUpdateAccountsAndWait(idConflictAccounts); fail("Should have thrown."); } catch (IllegalArgumentException e) { } Thread.sleep(100); assertEquals("Wrong number of accounts in accountService", 0, accountService.getAllAccounts().size()); Collection<Account> nameConflictAccounts = new ArrayList<>(); nameConflictAccounts.add(new AccountBuilder((short) 1, "account1", Account.AccountStatus.INACTIVE, null).build()); nameConflictAccounts.add(new AccountBuilder((short) 2, "account1", Account.AccountStatus.INACTIVE, null).build()); try { createOrUpdateAccountsAndWait(nameConflictAccounts); fail("Should have thrown."); } catch (IllegalArgumentException e) { } Thread.sleep(100); assertEquals("Wrong number of accounts in accountService", 0, accountService.getAllAccounts().size()); }
Source:
private void testConversion(IdConverter idConverter, RestMethod restMethod, String input, String expectedOutput) throws Exception { JSONObject requestData = new JSONObject(); requestData.put(MockRestRequest.REST_METHOD_KEY, restMethod); requestData.put(MockRestRequest.URI_KEY, "/"); RestRequest restRequest = new MockRestRequest(requestData, null); IdConversionCallback callback = new IdConversionCallback(); assertEquals("IdConverter should not have converted ID (Future)", expectedOutput, idConverter.convert(restRequest, input, callback).get()); assertEquals("IdConverter should not have converted ID (Callback)", expectedOutput, callback.result); }

Target:
private void testConversion(IdConverter idConverter, RestMethod restMethod, String input, String expectedOutput) throws Exception { JSONObject requestData = new JSONObject(); requestData.put(MockRestRequest.REST_METHOD_KEY, restMethod); requestData.put(MockRestRequest.URI_KEY, "/"); RestRequest restRequest = new MockRestRequest(requestData, null); IdConversionCallback callback = new IdConversionCallback(); assertEquals("Converted ID does not match expected (Future)", expectedOutput, idConverter.convert(restRequest, input, callback).get()); assertEquals("Converted ID does not match expected (Callback)", expectedOutput, callback.result); }
Source:
public Response systemScopesGet(MessageContext messageContext) throws APIManagementException{ try { Map<String, String> scopeRoleMapping = APIUtil.getRESTAPIScopesForTenant(MultitenantUtils .getTenantDomain(RestApiUtil.getLoggedInUsername())); ScopeListDTO scopeListDTO = SystemScopesMappingUtil.fromScopeListToScopeListDTO(scopeRoleMapping); return Response.ok().entity(scopeListDTO).build(); } catch (Exception e) { String errorMessage = "Error when getting the list of scopes-role mapping."; RestApiUtil.handleInternalServerError(errorMessage, e, log); } return null; }

Target:
public Response systemScopesGet(MessageContext messageContext) throws APIManagementException { try { Map<String, String> scopeRoleMapping = APIUtil.getRESTAPIScopesForTenant(MultitenantUtils .getTenantDomain(RestApiUtil.getLoggedInUsername())); ScopeListDTO scopeListDTO = SystemScopesMappingUtil.fromScopeListToScopeListDTO(scopeRoleMapping); return Response.ok().entity(scopeListDTO).build(); } catch (APIManagementException e) { String errorMessage = "Error when getting the list of scopes-role mapping."; RestApiUtil.handleInternalServerError(errorMessage, e, log); } return null; }
Source:
void setCurrentPacket(ICTFPacketInformation currentPacket) throws CTFReaderException { ICTFPacketInformation prevPacket = null; fCurrentPacket = currentPacket; if (fCurrentPacket != null) { ByteBuffer bb = null; try { bb = getByteBufferAt(fCurrentPacket.getOffsetBytes(), (fCurrentPacket.getPacketSizeBits() + BITS_PER_BYTE - 1) / BITS_PER_BYTE); } catch (IOException e) { throw new CTFReaderException(e.getMessage(), e); } BitBuffer bitBuffer = new BitBuffer(bb); fBitBuffer = bitBuffer; if (fTracePacketHeaderDecl != null) { fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(bitBuffer); } if (fStreamPacketContextDecl != null) { fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(bitBuffer); if (getCurrentPacket().getTarget() != null) { fCurrentCpu = (int) getCurrentPacket().getTargetId(); } fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents(); if (fLostEventsInThisPacket != 0) { fHasLost = true; long lostEventsStartTime; int index = fStreamInputReader.getStreamInput().getIndex().indexOf(currentPacket); if (index == 0) { lostEventsStartTime = currentPacket.getTimestampBegin() + 1; } else { prevPacket = fStreamInputReader.getStreamInput().getIndex().getElement(index - 1); lostEventsStartTime = prevPacket.getTimestampEnd(); } fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin()); } } fLastTimestamp = currentPacket.getTimestampBegin(); } else { fBitBuffer = null; fLastTimestamp = 0; } }

Target:
void setCurrentPacket(ICTFPacketInformation currentPacket) throws CTFException { ICTFPacketInformation prevPacket = null; fCurrentPacket = currentPacket; if (fCurrentPacket != null) { ByteBuffer bb = null; try { bb = getByteBufferAt(fCurrentPacket.getOffsetBytes(), (fCurrentPacket.getPacketSizeBits() + BITS_PER_BYTE - 1) / BITS_PER_BYTE); } catch (IOException e) { throw new CTFIOException(e.getMessage(), e); } BitBuffer bitBuffer = new BitBuffer(bb); fBitBuffer = bitBuffer; if (fTracePacketHeaderDecl != null) { fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(bitBuffer); } if (fStreamPacketContextDecl != null) { fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(bitBuffer); if (getCurrentPacket().getTarget() != null) { fCurrentCpu = (int) getCurrentPacket().getTargetId(); } fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents(); if (fLostEventsInThisPacket != 0) { fHasLost = true; long lostEventsStartTime; int index = fStreamInputReader.getStreamInput().getIndex().indexOf(currentPacket); if (index == 0) { lostEventsStartTime = currentPacket.getTimestampBegin() + 1; } else { prevPacket = fStreamInputReader.getStreamInput().getIndex().getElement(index - 1); lostEventsStartTime = prevPacket.getTimestampEnd(); } fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin()); } } fLastTimestamp = currentPacket.getTimestampBegin(); } else { fBitBuffer = null; fLastTimestamp = 0; } }
Source:
private <V> ListenableFuture<V> runAsyncInternal(String callableName, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { ListenableFuture<V> newResultFuture = runInternal(callableName, callable, retryStatus); return Futures.catchingAsync(newResultFuture, Exception.class, e -> { checkState(e != null, "input exception is null"); if (shouldStopRetry(e, retryStatus)) { throw propagate(e); } log.warn("Failed on executing %s with attempt %d, will perform async retry. Exception: %s", callableName, retryStatus.getAttempts(), e.getMessage()); long delayInMs = getRetryDelayInMs(retryStatus); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, callable, retryStatus), delayInMs, TimeUnit.MILLISECONDS)); }); }

Target:
private <V> ListenableFuture<V> runAsyncInternal(String callableName, Callable<ListenableFuture<V>> callable, RetryStatus retryStatus) { retryStatus.nextAttempt(); ListenableFuture<V> resultFuture; try { resultFuture = callable.call(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw propagate(ie); } catch (Exception e) { resultFuture = immediateFailedFuture(e); } return Futures.catchingAsync(resultFuture, Exception.class, e -> { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw propagate(e); } else if (retryStatus.shouldStopRetry(e)) { throw propagate(e); } log.warn(e, "Failed on executing %s with attempt %d, will perform async retry.", callableName, retryStatus.getAttempts()); return Futures.dereference(retryExecutorService.schedule(() -> runAsyncInternal(callableName, callable, retryStatus), retryStatus.getRetryDelayInMs(), MILLISECONDS)); }); }
Source:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getstatus() != VDSStatus.Down) { if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || lastUpdate + (TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))) > System.currentTimeMillis()) { boolean result = false; if (vds.getstatus() != VDSStatus.Connecting && vds.getstatus() != VDSStatus.PreparingForMaintenance && vds.getstatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getstatus() == VDSStatus.NonResponsive || vds.getstatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.errorFormat( "VDS::handleNetworkException Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}", vds.getId(), vds.getvds_name(), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }

Target:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getstatus() != VDSStatus.Down) { if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || lastUpdate + (TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))) > System.currentTimeMillis()) { boolean result = false; if (vds.getstatus() != VDSStatus.Connecting && vds.getstatus() != VDSStatus.PreparingForMaintenance && vds.getstatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getstatus() == VDSStatus.NonResponsive || vds.getstatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.errorFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}", vds.getId(), vds.getvds_name(), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }
Source:
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { if (req.hasParameter("reset")) { j.setSlaveAgentPort(getExpectedPort()); } rsp.sendRedirect2(req.getContextPath() + "/manage"); }

Target:
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { j.forceSetSlaveAgentPort(getExpectedPort()); rsp.sendRedirect2(req.getContextPath() + "/manage"); }
Source:
protected void initWidget(Widget widget) { container = DataCenterClusterListUiBinder.uiBinder.createAndBindUi(this); super.initWidget(container); container.insert(widget, 0); getListBox().addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { updateGroupLabel(); } }); }

Target:
protected void initWidget(Widget widget) { container = GroupedListUiBinder.uiBinder.createAndBindUi(this); super.initWidget(container); container.insert(widget, 0); getListBox().addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { updateGroupLabel(); } }); }
Source:
public Response act(final Request request) throws IOException { final Opt<Identity> optUsers = this.pass.enter(request); final Response response; if (optUsers.has()) { response = this.act(request, optUsers.get()); } else { response = this.origin.act(request); } return response; }

Target:
public Response act(final Request request) throws IOException { final Opt<Identity> user = this.pass.enter(request); final Response response; if (user.has()) { response = this.act(request, user.get()); } else { response = this.origin.act(request); } return response; }
Source:
private void fetchCourseUpgradeStatus() { if (getCourseUpgradeStatus == null) { getCourseUpgradeStatus = courseApi.getCourseUpgradeStatus(courseData.getCourse().getId()); getCourseUpgradeStatus.enqueue(new Callback<CourseUpgradeResponse>() { @Override public void onResponse(Call<CourseUpgradeResponse> call, Response<CourseUpgradeResponse> response) { getCourseUpgradeStatus = null; if (getActivity() != null) { EdxCookieManager.getSharedInstance(getActivity()).setMobileCookie(); courseUpgradeData = response.body(); if (courseUpgradeData != null && courseUpgradeData.showUpsell() && !TextUtils.isEmpty(courseUpgradeData.getBasketUrl())) { PaymentsBannerFragment.Companion.loadPaymentsBannerFragment( R.id.fragment_container, courseData, null, courseUpgradeData, true, getChildFragmentManager(), true); EventBus.getDefault().postSticky(new CourseUpgradeDataReceivedEvent( courseData.getCourse().getId(), courseUpgradeData)); } else { final View view = getView(); if(view != null) { view.findViewById(R.id.fragment_container).setVisibility(View.GONE); } } } } @Override public void onFailure(Call<CourseUpgradeResponse> call, Throwable t) { getCourseUpgradeStatus = null; } }); } }

Target:
private void fetchCourseUpgradeStatus() { if (getCourseUpgradeStatus == null) { getCourseUpgradeStatus = courseApi.getCourseUpgradeStatus(courseData.getCourse().getId()); getCourseUpgradeStatus.enqueue(new Callback<CourseUpgradeResponse>() { @Override public void onResponse(Call<CourseUpgradeResponse> call, Response<CourseUpgradeResponse> response) { getCourseUpgradeStatus = null; if (getActivity() != null) { EdxCookieManager.getSharedInstance(getActivity()).setMobileCookie(); CourseUpgradeResponse courseUpgrade = response.body(); if (courseUpgrade != null && courseUpgrade.getShowUpsell() && !TextUtils.isEmpty(courseUpgrade.getBasketUrl())) { courseUpgradeData = courseUpgrade; PaymentsBannerFragment.Companion.loadPaymentsBannerFragment( R.id.fragment_container, courseData, null, courseUpgradeData, true, getChildFragmentManager(), true); } else { hidePaymentsBanner(); } } } @Override public void onFailure(Call<CourseUpgradeResponse> call, Throwable t) { getCourseUpgradeStatus = null; hidePaymentsBanner(); } }); } }
Source:
public void addContents(@NonNull Container container) { container.add(new Content("buildqueue.md") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { List<Queue.Item> items = Jenkins.getInstance().getQueue().getApproximateItemsQuickly(); out.println("Current build queue has " + items.size() + " item(s)."); out.println("---------------"); for (Queue.Item item : items) { out.println(" * Name of item: " + item.task.getFullDisplayName()); out.println(" - In queue for: " + item.getInQueueForString()); out.println(" - Is blocked: " + item.isBlocked()); out.println(" - Why in queue: " + item.getWhy()); for (Cause cause : item.getCauses()) { out.println(" - Current queue trigger cause: " + cause.getShortDescription()); } out.println(); } } finally { out.flush(); } } } ); }

Target:
public void addContents(@NonNull Container container) { container.add(new Content("buildqueue.md") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { List<Queue.Item> items = Jenkins.getInstance().getQueue().getApproximateItemsQuickly(); out.println("Current build queue has " + items.size() + " item(s)."); out.println("---------------"); for (Queue.Item item : items) { if (item instanceof Item) { out.println(" * Name of item: " + ((Item) item).getFullName()); } else { out.println(" * Name of item: " + Functions.escape(item.task.getFullDisplayName())); } out.println(" - In queue for: " + item.getInQueueForString()); out.println(" - Is blocked: " + item.isBlocked()); out.println(" - Why in queue: " + item.getWhy()); for (Cause cause : item.getCauses()) { out.println(" - Current queue trigger cause: " + cause.getShortDescription()); } out.println(); } } finally { out.flush(); } } } ); }
Source:
public Class getType() { return B3DState.class; }

Target:
public Class<B3DState> getType() { return B3DState.class; }
Source:
private void checkNodeExists( Long nodeID ) { EvalHierarchyNode node = getNodeById( nodeID.toString() ); if( node == null ) { throw new IllegalArgumentException( "Node ID (" + nodeID + ") provided is invalid, node does not exist" ); } }

Target:
private void checkNodeExists( Long nodeID ) { if( nodeID == null ) { throw new IllegalArgumentException( "Node ID provided is invalid (null)" ); } EvalHierarchyNode node = getNodeById( nodeID.toString() ); if( node == null ) { throw new IllegalArgumentException( "Node ID (" + nodeID + ") provided is invalid, node does not exist" ); } }
Source:
private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(tags -> operation.setTags(tags)); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); operation.setSummary(apiOperation.summary()); operation.setDescription(apiOperation.description()); OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(externalDocumentation -> operation.setExternalDocs(externalDocumentation)); operation.setOperationId(getOperationId(apiOperation.operationId())); OperationParser.getParametersList(apiOperation.parameters()).ifPresent(parameters -> operation.setParameters(parameters)); OperationParser.getRequestBody(apiOperation.requestBody()).ifPresent(requestBody -> operation.setRequestBody(requestBody)); operation.setDeprecated(apiOperation.deprecated()); OperationParser.getServers(apiOperation.servers()).ifPresent(servers -> operation.setServers(servers)); }

Target:
private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(tags -> operation.setTags(tags)); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(externalDocumentation -> operation.setExternalDocs(externalDocumentation)); operation.setOperationId(getOperationId(apiOperation.operationId())); OperationParser.getRequestBody(apiOperation.requestBody()).ifPresent(requestBody -> operation.setRequestBody(requestBody)); operation.setDeprecated(apiOperation.deprecated()); OperationParser.getServers(apiOperation.servers()).ifPresent(servers -> operation.setServers(servers)); }
Source:
public void setUp() throws Exception { setFixture(ModelelementsFactory.eINSTANCE.createStakeholder()); model = SysMLTestResources.createSysMLModel(houseKeeper.createResourceSet()); if(model == null) { fail("The model is not created."); } if(model.getAppliedProfiles().isEmpty()) { fail(" the profile Sysml has not be applied."); } defaultClass = model.createOwnedClass("defaultClass", false); default_stakeholder = (Stakeholder)StereotypeApplicationHelper.getInstance(null).applyStereotype(defaultClass, ModelelementsPackage.eINSTANCE.getStakeholder()); comment1=UMLFactory.eINSTANCE.createComment(); comment1.setBody(THIS_IS_THE_BODY_OF_COMMENT1); model.getOwnedComments().add(comment1); comment2=UMLFactory.eINSTANCE.createComment(); comment2.setBody(THIS_IS_THE_BODY_OF_COMMENT2); model.getOwnedComments().add(comment2); default_stakeholder.getConcernList().add(comment1); default_stakeholder.getConcernList().add(comment2); }

Target:
public void setUp() { setFixture(ModelelementsFactory.eINSTANCE.createStakeholder()); model = SysMLTestResources.createSysMLModel(houseKeeper.createResourceSet()); if(model.getAppliedProfiles().isEmpty()) { fail(" the profile Sysml has not be applied."); } defaultClass = model.createOwnedClass("defaultClass", false); default_stakeholder = (Stakeholder)StereotypeApplicationHelper.getInstance(null).applyStereotype(defaultClass, ModelelementsPackage.eINSTANCE.getStakeholder()); comment1=UMLFactory.eINSTANCE.createComment(); comment1.setBody(THIS_IS_THE_BODY_OF_COMMENT1); model.getOwnedComments().add(comment1); comment2=UMLFactory.eINSTANCE.createComment(); comment2.setBody(THIS_IS_THE_BODY_OF_COMMENT2); model.getOwnedComments().add(comment2); default_stakeholder.getConcernList().add(comment1); default_stakeholder.getConcernList().add(comment2); }
Source:
private boolean suppressed(File root, File resolved) { try { return suppressBare && !resolved.getName().equals(Constants.DOT_GIT) && Files.isSameFile(root.toPath(), resolved.toPath()); } catch (IOException e) { return false; } }

Target:
private boolean suppressed(File root, File resolved) { return !allowBare && !Constants.DOT_GIT.equals(resolved.getName()) && isSameFile(root, resolved); }
Source:
public void testSendAndReceive() { long blobSize = 1028; BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort, 10000, 10000, 10000, 2000, sslSocketFactory); try { byte[] bytesToSend = new byte[(int) blobSize]; new Random().nextBytes(bytesToSend); ByteBuffer byteBufferToSend = ByteBuffer.wrap(bytesToSend); byteBufferToSend.putLong(0, blobSize); BoundedByteBufferSend bufferToSend = new BoundedByteBufferSend(byteBufferToSend); channel.connect(); channel.send(bufferToSend); InputStream streamResponse = channel.receive().getInputStream(); DataInputStream input = new DataInputStream(streamResponse); byte[] bytesReceived = new byte[(int) blobSize - 8]; input.readFully(bytesReceived); for (int i = 0; i < blobSize - 8; i++) { Assert.assertEquals(bytesToSend[8 + i], bytesReceived[i]); } channel.disconnect(); } catch (IOException e) { fail("Unexpected error in testing SSLBlockingChannel"); e.printStackTrace(); } }

Target:
public void testSendAndReceive() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort, 10000, 10000, 10000, 2000, sslSocketFactory); sendAndReceive(channel); channel.disconnect(); }
Source:
protected void applySteering(SteeringAcceleration<Vector2> steering, float tpf) { position.add(linearVelocity.x * tpf, linearVelocity.y * tpf); linearVelocity.mulAdd(steering.linear, tpf).limit(getMaxLinearSpeed()); if (steering.isZero()) { steeringBehavior = null; stopMoving = false; return; } if (!stopMoving) { position.add(linearVelocity.x * tpf, linearVelocity.y * tpf); linearVelocity.mulAdd(steering.linear, tpf).limit(maxLinearSpeed); float newOrientation = vectorToAngle(linearVelocity); angularVelocity = (newOrientation - getOrientation()) * tpf; setOrientation(newOrientation); } else { orientation += angularVelocity * tpf; angularVelocity += steering.angular * tpf; } if (steering.angular != 0 && steering.linear.isZero(speedThreshold)) { stopMoving = true; } }

Target:
protected void applySteering(SteeringAcceleration<Vector2> steering, float tpf) { if (steering.isZero()) { steeringBehavior = null; stopMoving = false; return; } if (!stopMoving) { position.add(linearVelocity.x * tpf, linearVelocity.y * tpf); linearVelocity.mulAdd(steering.linear, tpf).limit(maxLinearSpeed); float newOrientation = vectorToAngle(linearVelocity); angularVelocity = (newOrientation - getOrientation()) * tpf; setOrientation(newOrientation); } else { orientation += angularVelocity * tpf; angularVelocity += steering.angular * tpf; } if (steering.angular != 0 && steering.linear.isZero(speedThreshold)) { stopMoving = true; } }
Source:
protected List<Section> getScrolledCompositeSections() { List<Section> sections = new ArrayList<Section>(); if (scrolledComposite.getChildren().length != 0 && scrolledComposite.getChildren()[0] instanceof Composite) { Composite sectionContainer = (Composite) scrolledComposite.getChildren()[0]; sectionContainer.addMouseListener(createRemoveCommentEditorListener()); sections = FluentIterable.from( Iterables.filter(Arrays.asList(sectionContainer.getChildren()), Section.class)).toList(); } return sections; }

Target:
protected List<Section> getScrolledCompositeSections() { List<Section> sections = new ArrayList<Section>(); if (scrolledComposite.getChildren().length != 0 && scrolledComposite.getChildren()[0] instanceof Composite) { Composite sectionContainer = (Composite) scrolledComposite.getChildren()[0]; sections = FluentIterable.from( Iterables.filter(Arrays.asList(sectionContainer.getChildren()), Section.class)).toList(); } return sections; }
Source:
public Set<cgWaypoint> loadWaypoints(final Viewport viewport, boolean excludeMine, boolean excludeDisabled, CacheType type) { final StringBuilder where = new StringBuilder(buildCoordinateWhere(dbTableWaypoints, viewport)); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".own == 0 and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '" + type.id + "'"); } init(); final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints).append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where); final Cursor cursor = database.rawQuery(query.toString(), null); try { if (!cursor.moveToFirst()) { return Collections.emptySet(); } final Set<cgWaypoint> waypoints = new HashSet<cgWaypoint>(); do { waypoints.add(createWaypointFromDatabaseContent(cursor)); } while (cursor.moveToNext()); return waypoints; } finally { cursor.close(); } }

Target:
public Set<cgWaypoint> loadWaypoints(final Viewport viewport, boolean excludeMine, boolean excludeDisabled, CacheType type) { final StringBuilder where = new StringBuilder(buildCoordinateWhere(dbTableWaypoints, viewport)); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".own == 0 and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append("'"); } init(); final StringBuilder query = new StringBuilder("SELECT "); for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints).append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where); final Cursor cursor = database.rawQuery(query.toString(), null); try { if (!cursor.moveToFirst()) { return Collections.emptySet(); } final Set<cgWaypoint> waypoints = new HashSet<cgWaypoint>(); do { waypoints.add(createWaypointFromDatabaseContent(cursor)); } while (cursor.moveToNext()); return waypoints; } finally { cursor.close(); } }
Source:
public void stopPortForwarding() { if(!isPortForwarding(pod)) return; IPortForwardable cap = REGISTRY.remove(pod); try { final MessageConsole console = ConsoleUtils.findMessageConsole(getMessageConsoleName()); MessageConsoleStream stream = console.newMessageStream(); stream.println("Stopping port-forwarding..."); cap.stop(); for (int i = 0; i < 50 && hasPortInUse(); i++) { if(i % 10 == 0) { stream.println("Waiting for port-forwarding to stop..."); } try { Thread.sleep(100); } catch (InterruptedException e) { break; } } for (IPortForwardable.PortPair port : ports) { stream.println(NLS.bind("{0} {1} -> {2}", new Object {port.getName(), port.getLocalPort(), port.getRemotePort()})); } if(!hasPortInUse()) { stream.println("done."); } else { stream.println("Ports remain in use yet. Stopping ports is requested and eventually will be completed."); } ConsoleUtils.displayConsoleView(console); firePropertyChange(PROPERTY_PORT_FORWARDING, true, getPortForwarding()); updatePortForwardingAllowed(); }finally { ConsoleUtils.deregisterConsoleListener(consoleListener); } }

Target:
public void stopPortForwarding() { if(!isPortForwarding(pod)) return; IPortForwardable cap = REGISTRY.remove(pod); MessageConsoleStream stream = null; try { final MessageConsole console = ConsoleUtils.findMessageConsole(getMessageConsoleName()); stream = console.newMessageStream(); stream.println("Stopping port-forwarding..."); cap.stop(); waitForStoppingProcessComplete(stream); for (IPortForwardable.PortPair port : ports) { stream.println(NLS.bind("{0} {1} -> {2}", new Object {port.getName(), port.getLocalPort(), port.getRemotePort()})); } if(!hasPortInUse()) { stream.println("done."); } else { stream.println("Ports remain in use yet. Stopping ports is requested and eventually will be completed."); } ConsoleUtils.displayConsoleView(console); firePropertyChange(PROPERTY_PORT_FORWARDING, true, getPortForwarding()); updatePortForwardingAllowed(); }finally { if(stream != null) { try { stream.close(); } catch (IOException e) { } } ConsoleUtils.deregisterConsoleListener(consoleListener); } }
Source:
private Map<String, String> getUserNames(final Collection<String> identity) throws DatabaseAccessException { final List<ObjectId> identityList = new ArrayList<>(); for (String userId : identity) { identityList.add(new ObjectId(userId)); } final DBCollection collection = database.getCollection(DatabaseStringConstants.USER_COLLECTION); final DBCursor cursor = collection.find( new BasicDBObject(DatabaseStringConstants.SELF_ID, new BasicDBObject(DatabaseStringConstants.IN_COMMAND, identityList)), new BasicDBObject(DatabaseStringConstants.SELF_ID, 1).append(DatabaseStringConstants.USER_NAME, 1)); if (!cursor.hasNext()) { throw new DatabaseAccessException("No users were found with the given userIds"); } final Map<String, String> userNameMap = new HashMap<>(); while (cursor.hasNext()) { final DBObject userName = cursor.next(); userNameMap.put(userName.get(DatabaseStringConstants.SELF_ID).toString(), userName.get(DatabaseStringConstants.USER_NAME).toString()); } if (identity.size() != userNameMap.size() && LOG.isWarnEnabled()) { for (String userId : identity) { if (!userNameMap.containsKey(userId)) { LOG.warn("User id not found in the database", userId); } } } return userNameMap; }

Target:
private Map<String, String> getUserNames(final Collection<String> identity) throws DatabaseAccessException { final List<ObjectId> identityList = new ArrayList<>(); for (String userId : identity) { identityList.add(new ObjectId(userId)); } final DBCollection collection = database.getCollection(DatabaseStringConstants.USER_COLLECTION); final DBCursor cursor = collection.find( new BasicDBObject(DatabaseStringConstants.SELF_ID, new BasicDBObject(DatabaseStringConstants.IN_COMMAND, identityList)), new BasicDBObject(DatabaseStringConstants.SELF_ID, 1).append(DatabaseStringConstants.USER_NAME, 1)); if (!cursor.hasNext()) { throw new DatabaseAccessException("No users were found with the given userIds"); } final Map<String, String> userNameMap = new HashMap<>(); for (DBObject userName: cursor) { userNameMap.put(userName.get(DatabaseStringConstants.SELF_ID).toString(), userName.get(DatabaseStringConstants.USER_NAME).toString()); } if (identity.size() != userNameMap.size() && LOG.isWarnEnabled()) { for (String userId : identity) { if (!userNameMap.containsKey(userId)) { LOG.warn("User id not found in the database", userId); } } } return userNameMap; }