auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void testStarredOrganizationEvents(OrganizationsApi organizationsApiUser2, Organization organization) { organizationsApiUser2.starOrganization(organization.getId(), SwaggerUtility.createStarRequest(true)); final io.dockstore.openapi.client.ApiClient openAPIWebClientUser2 = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); EventsApi eventsApi = new EventsApi(openAPIWebClientUser2); List<io.dockstore.openapi.client.model.Event> events = eventsApi .getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), null, null); Assert.assertEquals("Should have 1 create, 1 approve, 4 modify events", 6, events.size()); events = eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), 5, null); Assert.assertEquals("Should have 1 create, 1 approve, 4 modify events", 5, events.size()); try { eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), EventDAO.MAX_LIMIT + 1, 0); Assert.fail("Should've failed because it's over the limit"); } catch (io.dockstore.openapi.client.ApiException e) { Assert.assertEquals("{\"errors\":[\"query param limit must be less than or equal to " + EventDAO.MAX_LIMIT + "\"]}", e.getMessage()); } try { eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), 0, 0); Assert.fail("Should've failed because it's under the limit"); } catch (io.dockstore.openapi.client.ApiException e) { Assert.assertEquals("{\"errors\":[\"query param limit must be greater than or equal to 1\"]}", e.getMessage()); } }

Target:
private void testStarredOrganizationEvents(OrganizationsApi organizationsApiUser2, Organization organization) { organizationsApiUser2.starOrganization(organization.getId(), SwaggerUtility.createStarRequest(true)); final io.dockstore.openapi.client.ApiClient openAPIWebClientUser2 = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); EventsApi eventsApi = new EventsApi(openAPIWebClientUser2); List<io.dockstore.openapi.client.model.Event> events = eventsApi .getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), null, null); Assert.assertEquals("Should have the correct amount of events", 6, events.size()); events = eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), 5, null); Assert.assertEquals("Should have the correct amount of events", 5, events.size()); Assert.assertFalse("The create org event is the oldest, it should not be returned", events.stream().anyMatch(event -> event.getType().equals(io.dockstore.openapi.client.model.Event.TypeEnum.CREATE_ORG))); try { eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), EventDAO.MAX_LIMIT + 1, 0); Assert.fail("Should've failed because it's over the limit"); } catch (io.dockstore.openapi.client.ApiException e) { Assert.assertEquals("{\"errors\":[\"query param limit must be less than or equal to " + EventDAO.MAX_LIMIT + "\"]}", e.getMessage()); } try { eventsApi.getEvents(EventSearchType.STARRED_ORGANIZATION.toString(), 0, 0); Assert.fail("Should've failed because it's under the limit"); } catch (io.dockstore.openapi.client.ApiException e) { Assert.assertEquals("{\"errors\":[\"query param limit must be greater than or equal to 1\"]}", e.getMessage()); } }
Source:
public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { List<Set<String>> hostGroups = newArrayList( hostComponentMap.entrySet().stream().collect( groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toCollection(TreeSet::new))) ).values()); hostGroups.sort(comparing(hosts -> hosts.iterator().next())); Map<String, Set<String>> hostgroupMap = IntStream.range(0, hostGroups.size()) .mapToObj(i -> Pair.of("host_group_" + (i + 1), hostGroups.get(i))) .collect(toMap(Pair::getKey, Pair::getValue)); return hostgroupMap; }

Target:
public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { List<Set<String>> hostGroups = newArrayList( hostComponentMap.entrySet().stream().collect( groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toCollection(TreeSet::new))) ).values()); hostGroups.sort(comparing(hosts -> hosts.iterator().next())); Map<String, Set<String>> hostgroupMap = IntStream.range(0, hostGroups.size()).boxed() .collect(toMap(i -> "host_group_" + (i + 1), i -> hostGroups.get(i))); return hostgroupMap; }
Source:
private void updateImpactCache(Pattern pattern) { impactCache.keySet().forEach(uri -> impactCache.remove(uri, pattern)); Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream().map(p -> p.eResource().getURI()).collect(Collectors.toSet()); referredUris.forEach(u -> impactCache.put(u, pattern)); }

Target:
private void updateImpactCache(Pattern pattern) { dependencyCache.keySet().forEach(uri -> dependencyCache.remove(uri, pattern)); Set<URI> referredUris = PatternLanguageHelper.getReferencedPatternsTransitive(pattern).stream() .map(p -> p.eResource().getURI()).collect(Collectors.toSet()); referredUris.forEach(u -> dependencyCache.put(u, pattern)); }
Source:
public static void checkPermissionsAndPerformAction(Activity activity, String permission, Runnable onPermissionGranted, Runnable onPermissionDenied, @StringRes int rationaleTitle, @StringRes int rationaleMessage) { Dexter.withActivity(activity) .withPermission(permission) .withListener(new BasePermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { onPermissionGranted.run(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(R.string.navigation_item_settings), null, () -> askUserToManuallyEnablePermissionFromSettings(activity), null); } else { onPermissionDenied.run(); } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(android.R.string.ok), activity.getString(android.R.string.cancel), token::continuePermissionRequest, token::cancelPermissionRequest); } }) .check(); }

Target:
public static void checkPermissionsAndPerformAction(Activity activity, String permission, Runnable onPermissionGranted, Runnable onPermissionDenied, @StringRes int rationaleTitle, @StringRes int rationaleMessage) { Dexter.withActivity(activity) .withPermission(permission) .withListener(new BasePermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { onPermissionGranted.run(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { if (response.isPermanentlyDenied()) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(R.string.navigation_item_settings), null, () -> askUserToManuallyEnablePermissionFromSettings(activity), null); } else { if (null != onPermissionDenied) { onPermissionDenied.run(); } } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { DialogUtil.showAlertDialog(activity, activity.getString(rationaleTitle), activity.getString(rationaleMessage), activity.getString(android.R.string.ok), activity.getString(android.R.string.cancel), token::continuePermissionRequest, token::cancelPermissionRequest); } }) .check(); }
Source:
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { List<ModelNode> list = value.asList(); int size = list.size(); if (size < min) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMinSize(size, parameterName, min)); } else if (size > max) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMaxSize(size, parameterName, max)); } else { if (!allowDuplicates){ HashSet<ModelNode> dups = new HashSet<>(); for (ModelNode element : list) { if (dups.contains(element)){ throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.duplicateElementsInList(parameterName)); } dups.add(element); } dups.clear(); } for (ModelNode element : list) { elementValidator.validateParameter(parameterName, element); } } } }

Target:
public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined()) { List<ModelNode> list = value.asList(); int size = list.size(); if (size < min) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMinSize(size, parameterName, min)); } else if (size > max) { throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.invalidMaxSize(size, parameterName, max)); } else { if (!allowDuplicates){ HashSet<ModelNode> dups = new HashSet<>(); for (ModelNode element : list) { if (!dups.add(element)){ throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.duplicateElementsInList(parameterName)); } } dups.clear(); } for (ModelNode element : list) { elementValidator.validateParameter(parameterName, element); } } } }
Source:
public AsyncFuture<FindTags> findTags(FindTags.Request request) { return delegateGroup.findTags(request).catchFailed(wrapExceptionTransform()); }

Target:
public AsyncFuture<FindTags> findTags(FindTags.Request request) { return delegateGroup.findTags(request); }
Source:
protected void configureOAuth20Client(final Collection<IndirectClient> properties) { val pac4jProperties = casProperties.getAuthn().getPac4j(); val index = new AtomicInteger(); pac4jProperties.getOauth2() .stream() .filter(oauth -> oauth.isEnabled() && StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret())) .forEach(oauth -> { val client = new GenericOAuth20Client(); client.setProfileId(StringUtils.defaultIfBlank(oauth.getPrincipalAttributeId(), pac4jProperties.getPrincipalAttributeId())); client.setKey(oauth.getId()); client.setSecret(oauth.getSecret()); client.setProfileAttrs(oauth.getProfileAttrs()); client.setProfileNodePath(oauth.getProfilePath()); client.setProfileUrl(oauth.getProfileUrl()); client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase())); client.setTokenUrl(oauth.getTokenUrl()); client.setAuthUrl(oauth.getAuthUrl()); client.setScope(oauth.getScope()); client.setCustomParams(oauth.getCustomParams()); client.getConfiguration().setResponseType(oauth.getResponseType()) System.out.println(oauth.getResponseType()); if (StringUtils.isBlank(oauth.getClientName())) { val count = index.intValue(); client.setName(client.getClass().getSimpleName() + count); } configureClient(client, oauth); index.incrementAndGet(); LOGGER.debug("Created client [{}]", client); properties.add(client); }); }

Target:
protected void configureOAuth20Client(final Collection<IndirectClient> properties) { val pac4jProperties = casProperties.getAuthn().getPac4j(); val index = new AtomicInteger(); pac4jProperties.getOauth2() .stream() .filter(oauth -> oauth.isEnabled() && StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret())) .forEach(oauth -> { val client = new GenericOAuth20Client(); client.setProfileId(StringUtils.defaultIfBlank(oauth.getPrincipalAttributeId(), pac4jProperties.getPrincipalAttributeId())); client.setKey(oauth.getId()); client.setSecret(oauth.getSecret()); client.setProfileAttrs(oauth.getProfileAttrs()); client.setProfileNodePath(oauth.getProfilePath()); client.setProfileUrl(oauth.getProfileUrl()); client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase())); client.setTokenUrl(oauth.getTokenUrl()); client.setAuthUrl(oauth.getAuthUrl()); client.setScope(oauth.getScope()); client.setCustomParams(oauth.getCustomParams()); client.getConfiguration().setResponseType(oauth.getResponseType()); if (StringUtils.isBlank(oauth.getClientName())) { val count = index.intValue(); client.setName(client.getClass().getSimpleName() + count); } configureClient(client, oauth); index.incrementAndGet(); LOGGER.debug("Created client [{}]", client); properties.add(client); }); }
Source:
private <T> void registerHandler(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly, long timeoutID) { checkStarted(); Objects.requireNonNull(address, "address"); Objects.requireNonNull(registration.handler, "handler"); ContextImpl context = vertx.getContext(); boolean hasContext = context != null; if (!hasContext) { context = vertx.createEventLoopContext(null, new JsonObject(), Thread.currentThread().getContextClassLoader()); } HandlerHolder holder = new HandlerHolder<T>(registration, replyHandler, localOnly, context, timeoutID); Handlers handlers = handlerMap.get(address); if (handlers == null) { handlers = new Handlers(); Handlers prevHandlers = handlerMap.putIfAbsent(address, handlers); if (prevHandlers != null) { handlers = prevHandlers; } if (subs != null && !replyHandler && !localOnly) { subs.add(address, serverID, ar -> { holder.context.runOnContext(v -> { registration.setResult(ar); }); }); } else { holder.context.runOnContext(v -> { registration.setResult(Future.succeededFuture()); }); } } else { holder.context.runOnContext(v -> { registration.setResult(Future.succeededFuture()); }); } handlers.list.add(holder); if (hasContext) { HandlerEntry entry = new HandlerEntry<T>(address, registration); context.addCloseHook(entry); } }

Target:
private <T> void registerHandler(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly, long timeoutID) { checkStarted(); Objects.requireNonNull(address, "address"); Objects.requireNonNull(registration.handler, "handler"); ContextImpl context = vertx.getContext(); boolean hasContext = context != null; Handler<AsyncResult<Void>> register; if (!hasContext) { Context newContext = context = vertx.createEventLoopContext(null, new JsonObject(), Thread.currentThread().getContextClassLoader()); register = fut -> { newContext.runOnContext(v -> registration.setResult(fut)); }; } else { register = registration::setResult; } HandlerHolder holder = new HandlerHolder<T>(registration, replyHandler, localOnly, context, timeoutID); Handlers handlers = handlerMap.get(address); if (handlers == null) { handlers = new Handlers(); Handlers prevHandlers = handlerMap.putIfAbsent(address, handlers); if (prevHandlers != null) { handlers = prevHandlers; } if (subs != null && !replyHandler && !localOnly) { subs.add(address, serverID, ar -> { register.handle(ar); }); } else { register.handle(Future.succeededFuture()); } } else { register.handle(Future.succeededFuture()); } handlers.list.add(holder); if (hasContext) { HandlerEntry entry = new HandlerEntry<T>(address, registration); context.addCloseHook(entry); } }
Source:
protected void onLoad() throws IOException, ConfigInvalidException { ObjectId rev = getRevision(); if (rev == null) { loadDefaults(); return; } RevWalk walk = new RevWalk(reader); try (ChangeNotesParser parser = new ChangeNotesParser(change, rev, walk, repoManager)) { parser.parseAll(); if (parser.status != null) { change.setStatus(parser.status); } approvals = parser.buildApprovals(); changeMessages = parser.buildMessages(); commentsForBase = ImmutableListMultimap.copyOf(parser.commentsForBase); commentsForPS = ImmutableListMultimap.copyOf(parser.commentsForPs); noteMap = parser.commentNoteMap; if (parser.hashtags != null) { hashtags = ImmutableSet.copyOf(parser.hashtags); } ImmutableSetMultimap.Builder<ReviewerState, Account.Id> reviewers = ImmutableSetMultimap.builder(); for (Map.Entry<Account.Id, ReviewerState> e : parser.reviewers.entrySet()) { reviewers.put(e.getValue(), e.getKey()); } this.reviewers = reviewers.build(); this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers); submitRecords = ImmutableList.copyOf(parser.submitRecords); } catch (ParseException e1) { throw new IOException(e1); } finally { walk.release(); } }

Target:
protected void onLoad() throws IOException, ConfigInvalidException { ObjectId rev = getRevision(); if (rev == null) { loadDefaults(); return; } RevWalk walk = new RevWalk(reader); try (ChangeNotesParser parser = new ChangeNotesParser(change, rev, walk, repoManager)) { parser.parseAll(); if (parser.status != null) { change.setStatus(parser.status); } approvals = parser.buildApprovals(); changeMessages = parser.buildMessages(); commentsForBase = ImmutableListMultimap.copyOf(parser.commentsForBase); commentsForPS = ImmutableListMultimap.copyOf(parser.commentsForPs); noteMap = parser.commentNoteMap; if (parser.hashtags != null) { hashtags = ImmutableSet.copyOf(parser.hashtags); } else { hashtags = ImmutableSet.of(); } ImmutableSetMultimap.Builder<ReviewerState, Account.Id> reviewers = ImmutableSetMultimap.builder(); for (Map.Entry<Account.Id, ReviewerState> e : parser.reviewers.entrySet()) { reviewers.put(e.getValue(), e.getKey()); } this.reviewers = reviewers.build(); this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers); submitRecords = ImmutableList.copyOf(parser.submitRecords); } catch (ParseException e1) { throw new IOException(e1); } finally { walk.release(); } }
Source:
public Tuple next() { Tuple current = createTuple( entityCache.get( this.next ) ); this.next = next( this.iterator ); return current; }

Target:
public Tuple next() { if ( hasNext ) { Tuple current = createTuple( entityCache.get( this.next ) ); this.next = next( this.iterator ); return current; } throw new NoSuchElementException(); }
Source:
public void init(AdaptorContext context) throws Exception { this.context = context; this.params = new Params(context.getConfig()); try (Connection connection = getConnection()) { logger.log(Level.INFO, "Connecting to object store {0}", params.getObjectStore()); factory.getObjectStore(connection, params.getObjectStore()); } catch (EngineRuntimeException e) { throw new StartupException( "Failed to access content engine's object store", e); } documentTraverser = new MockTraverser(params); }

Target:
public void init(AdaptorContext context) throws Exception { this.context = context; this.configOptions = new ConfigOptions(context); try (Connection connection = configOptions.getConnection()) { configOptions.getObjectStore(connection); } catch (EngineRuntimeException e) { throw new StartupException( "Failed to access content engine's object store", e); } documentTraverser = new MockTraverser(configOptions); }
Source:
public void testDroppingColumnWhileCreatingIndex() throws Exception { String schemaName = "S1"; String tableName = generateUniqueName(); String viewSchemaName = "S1"; String fullTableName = SchemaUtil.getTableName(schemaName, tableName); String indexName = "IND_" + generateUniqueName(); String viewName = "VIEW_" + generateUniqueName(); String fullViewName = SchemaUtil.getTableName(viewSchemaName, viewName); createBaseTable(schemaName, tableName, false, null, null, true); try (Connection conn = getConnection()) { conn.setAutoCommit(true); conn.createStatement().execute("CREATE VIEW " + fullViewName + " AS SELECT * FROM " + fullTableName); conn.commit(); final int[] exceptionCode = new int[1]; final CountDownLatch doneSignal = new CountDownLatch(2); Runnable r1 = new Runnable() { @Override public void run() { try { conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + fullViewName + " (v1)"); } catch (SQLException e) { exceptionCode[0] = e.getErrorCode(); throw new RuntimeException(e); } finally { doneSignal.countDown(); } } }; Runnable r2 = new Runnable() { @Override public void run() { try { conn.createStatement().execute("ALTER TABLE " + fullTableName + " DROP COLUMN v1"); } catch (SQLException e) { exceptionCode[0] = e.getErrorCode(); throw new RuntimeException(e); } finally { doneSignal.countDown(); } } }; Thread t1 = new Thread(r1); t1.start(); Thread t2 = new Thread(r2); t2.start(); t1.join(); t2.join(); doneSignal.await(60, TimeUnit.SECONDS); assertEquals(exceptionCode[0], 301); } }

Target:
public void testDroppingColumnWhileCreatingIndex() throws Exception { String schemaName = "S1"; String tableName = generateUniqueName(); String viewSchemaName = "S1"; String fullTableName = SchemaUtil.getTableName(schemaName, tableName); String indexName = "IND_" + generateUniqueName(); String viewName = "VIEW_" + generateUniqueName(); String fullViewName = SchemaUtil.getTableName(viewSchemaName, viewName); createBaseTable(schemaName, tableName, false, null, null, true); try (Connection conn = getConnection()) { conn.setAutoCommit(true); conn.createStatement().execute("CREATE VIEW " + fullViewName + " AS SELECT * FROM " + fullTableName); conn.commit(); final AtomicInteger exceptionCode = new AtomicInteger(); final CountDownLatch doneSignal = new CountDownLatch(2); Runnable r1 = new Runnable() { @Override public void run() { try { conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + fullViewName + " (v1)"); } catch (SQLException e) { exceptionCode.set(e.getErrorCode()); throw new RuntimeException(e); } finally { doneSignal.countDown(); } } }; Runnable r2 = new Runnable() { @Override public void run() { try { conn.createStatement().execute("ALTER TABLE " + fullTableName + " DROP COLUMN v1"); } catch (SQLException e) { exceptionCode.set(e.getErrorCode()); throw new RuntimeException(e); } finally { doneSignal.countDown(); } } }; Thread t1 = new Thread(r1); t1.start(); Thread t2 = new Thread(r2); t2.start(); t1.join(); t2.join(); doneSignal.await(60, TimeUnit.SECONDS); assertEquals(exceptionCode.get(), 301); } }
Source:
public void initialize() throws SchedulerConfigException { if (threadCount < 0) { throw new SchedulerConfigException("Thread count must be > 0"); } }

Target:
public void initialize() throws SchedulerConfigException { if (threadCount <= 0) { throw new SchedulerConfigException("Thread count must be > 0"); } }
Source:
public void notFound() { String newUrl = GWT.getHostPageBaseURL() + "?standalone&" + "perspective=" + NotFoundPerspective.ID + "&" + DASHBOARD_PARAM + "=" + dashboard; DomGlobal.window.history.pushState(null, "Dashbuilder Runtime | Not Found", newUrl); this.hideLoading(); }

Target:
public void notFound() { String newUrl = GWT.getHostPageBaseURL() + "?standalone&" + PERSPECTIVE_PARAM + "=" + NotFoundPerspective.ID + "&" + DASHBOARD_PARAM + "=" + dashboard; DomGlobal.window.history.pushState(null, "Dashbuilder Runtime | Not Found", newUrl); this.hideLoading(); }
Source:
public void login(String serverUrl, String username, String password) { showProgress(); mLoginActivityStrategy.login(); final Credentials credentials = new Credentials(serverUrl, username, password); mLoginUseCase.execute(credentials, new LoginUseCase.Callback() { @Override public void onLoginSuccess() { hideProgress(); GetUserAccountUseCase getUserAccountUseCase = new GetUserAccountUseCase( new AsyncExecutor(), new UIThreadExecutor(), new UserAccountRepository( new UserAccountAPIDataSource(Session.getCredentials()), new UserAccountLocalDataSource()) ); getUserAccountUseCase.execute(NetworkStrategy.NETWORK_FIRST, new GetUserAccountUseCase.Callback() { @Override public void onSuccess(UserAccount userAccount) { onGetUserSuccess(userAccount.isClosed()); } @Override public void onError() { System.out.println("Error pulling closed user date."); } }); } @Override public void onServerURLNotValid() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getText( R.string .error_not_found).toString()); } @Override public void onInvalidCredentials() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getText( R.string.error_unauthorized) .toString()); } @Override public void onNetworkError() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getString( R.string .title_error_unexpected)); } }); }

Target:
public void login(String serverUrl, String username, String password) { showProgress(); mLoginActivityStrategy.login(); final Credentials credentials = new Credentials(serverUrl, username, password); mLoginUseCase.execute(credentials, new LoginUseCase.Callback() { @Override public void onLoginSuccess() { hideProgress(); GetUserAccountUseCase getUserAccountUseCase = new GetUserAccountUseCase( new AsyncExecutor(), new UIThreadExecutor(), new UserAccountRepository( new UserAccountAPIDataSource(Session.getCredentials()), new UserAccountLocalDataSource()) ); getUserAccountUseCase.execute(NetworkStrategy.NETWORK_FIRST, new GetUserAccountUseCase.Callback() { @Override public void onSuccess(UserAccount userAccount) { onGetUserSuccess(userAccount.isClosed()); } @Override public void onError() { System.out.println("Error pulling closed user date."); } }); } @Override public void onServerURLNotValid() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getText( R.string .error_not_found).toString()); } @Override public void onInvalidCredentials() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getText( R.string.error_unauthorized) .toString()); } @Override public void onNetworkError() { mLoginActivityStrategy.onLoginError(); showError(PreferencesState.getInstance().getContext().getString( R.string .title_error_unexpected)); } @Override public void onUnsupportedServerVersion() { showError(PreferencesState.getInstance().getContext().getString( R.string.login_error_unsupported_server_version)); } }); }
Source:
void addConstrainingMembersToMap( Exp arg, Map<Dimension, List<RolapMember>> memberLists) { if (arg instanceof ResolvedFunCall) { ResolvedFunCall call = (ResolvedFunCall) arg; for (Exp callArg : call.getArgs()) { addConstrainingMembersToMap(callArg, memberLists); } } Exp[] tupleArgs = getCalculatedTupleArgs(arg); for (Exp tupleArg : tupleArgs) { Dimension dimension = tupleArg.getType().getDimension(); if (tupleArg instanceof ResolvedFunCall) { addConstrainingMembersToMap(tupleArg, memberLists); } else if (dimension != null && !dimension.isMeasures()) { List<RolapMember> members; if (memberLists.containsKey(dimension)) { members = memberLists.get(dimension); } else { members = new ArrayList<RolapMember>(); } members .add((RolapMember) ((MemberExpr) tupleArg).getMember()); memberLists.put(dimension, members); } else if (isConstrainedMeasure(tupleArg)) { addConstrainingMembersToMap(tupleArg, memberLists); } } }

Target:
private void addConstrainingMembersToMap( Exp arg, Map<Dimension, List<RolapMember>> memberLists) { if (arg instanceof ResolvedFunCall) { ResolvedFunCall call = (ResolvedFunCall) arg; for (Exp callArg : call.getArgs()) { addConstrainingMembersToMap(callArg, memberLists); } } Exp[] tupleArgs = getCalculatedTupleArgs(arg); for (Exp tupleArg : tupleArgs) { Dimension dimension = tupleArg.getType().getDimension(); if (tupleArg instanceof ResolvedFunCall) { addConstrainingMembersToMap(tupleArg, memberLists); } else if (dimension != null && !dimension.isMeasures()) { List<RolapMember> members; if (memberLists.containsKey(dimension)) { members = memberLists.get(dimension); } else { members = new ArrayList<RolapMember>(); } members.add((RolapMember) ((MemberExpr) tupleArg).getMember()); memberLists.put(dimension, members); } else if (isConstrainedMeasure(tupleArg)) { addConstrainingMembersToMap(tupleArg, memberLists); } } }
Source:
public void errorHandler_manualExecuteClientReset() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/default"; final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail("Wrong error " + error.toString()); } @Override public void onClientReset(SyncSession session, ClientResetRequiredError error) { try { error.executeClientReset(); fail("All Realms should be closed before executing Client Reset can be allowed"); } catch(IllegalStateException ignored) { } looperThread.testRealms.get(0).close(); error.executeClientReset(); assertFalse(error.getOriginalFile().exists()); assertTrue(error.getBackupFile().exists()); looperThread.testComplete(); } }) .build(); Realm realm = Realm.getInstance(config); looperThread.testRealms.add(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }

Target:
public void errorHandler_manualExecuteClientReset() { SyncUser user = createTestUser(); String url = "realm://objectserver.realm.io/default"; final SyncConfiguration config = configFactory.createSyncConfigurationBuilder(user , url) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail("Wrong error " + error.toString()); } @Override public void onClientResetRequired(SyncSession session, ClientResetHandler handler) { try { handler.executeClientReset(); fail("All Realms should be closed before executing Client Reset can be allowed"); } catch(IllegalStateException ignored) { } looperThread.testRealms.get(0).close(); handler.executeClientReset(); assertFalse(handler.getOriginalFile().exists()); assertTrue(handler.getBackupFile().exists()); looperThread.testComplete(); } }) .build(); Realm realm = Realm.getInstance(config); looperThread.testRealms.add(realm); SyncManager.simulateClientReset(SyncManager.getSession(config)); }
Source:
public void onExit() { try { freePartitions(new HashSet<>(listeners.keySet())); } catch (final NakadiRuntimeException | NakadiBaseException ex) { getLog().error("Failed to transfer partitions when leaving ClosingState", ex); TracingService.logErrorInSpan(getContext().getCurrentSpan(), "Failed to transfer partitions when leaving ClosingState " + ex.getMessage()); } finally { if (null != topologyListener) { try { topologyListener.close(); } finally { topologyListener = null; } } } }

Target:
public void onExit() { try { freePartitions(new HashSet<>(listeners.keySet())); } catch (final NakadiRuntimeException | NakadiBaseException ex) { getLog().error("Failed to transfer partitions when leaving ClosingState", ex); } finally { if (null != topologyListener) { try { topologyListener.close(); } finally { topologyListener = null; } } } }
Source:
public static MainPlayer.PlayerType getType() { if (player == null) { return null; } return player.videoPlayerSelected() ? MainPlayer.PlayerType.VIDEO : player.popupPlayerSelected() ? MainPlayer.PlayerType.POPUP : player.audioPlayerSelected() ? MainPlayer.PlayerType.AUDIO : null; }

Target:
public static MainPlayer.PlayerType getType() { if (player == null) { return null; } return player.getPlayerType(); }
Source:
private boolean isKnoxSSOEnabled() { Collection realmsList = SecurityUtils.getRealmsList(); if (realmsList != null) { for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); if (LOG.isDebugEnabled()) { LOG.debug("RealmClass.getName: " + name); } if (name.equals("org.apache.zeppelin.realm.jwt.KnoxJwtRealm")) { return true; } } } return false; }

Target:
private boolean isKnoxSSOEnabled() { Collection realmsList = SecurityUtils.getRealmsList(); if (realmsList != null) { for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) { Realm realm = iterator.next(); String name = realm.getClass().getName(); LOG.debug("RealmClass.getName: " + name); if (name.equals("org.apache.zeppelin.realm.jwt.KnoxJwtRealm")) { return true; } } } return false; }
Source:
private String login(String host, String username, String password) throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(host); URL url = new URL(host); String sessionCookie = authenticatorClient.login(username, password, "localhost"); return sessionCookie; } catch (Exception e) { throw new APIManagementException("Unable login to Host: " + host, e); } }

Target:
private String login(String host, String username, String password) throws APIManagementException { AuthenticatorClient authenticatorClient = null; try { authenticatorClient = new AuthenticatorClient(host); String sessionCookie = authenticatorClient.login(username, password, "localhost"); return sessionCookie; } catch (Exception e) { throw new APIManagementException("Unable login to Host: " + host, e); } }
Source:
public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); CBreakIterator iterator = new CBreakIterator(); iterator.setText(fieldName); int firstWordStart = -1; int secondWordStart = -1; int lastWordEnd = -1; int end; for (int start = iterator.first(); (end = iterator.next()) != BreakIterator.DONE; start = end) { if (Character.isLetterOrDigit(fieldName.charAt(start))) { int pos = end; while (--pos >= start && !Character.isLetterOrDigit(fieldName.charAt(pos))) { } lastWordEnd = pos + 1; if (firstWordStart < 0) { firstWordStart = start; } else if (secondWordStart < 0) { secondWordStart = start; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }

Target:
public static String trimFieldName(String fieldName) { IPreferencesService preferences = Platform.getPreferencesService(); String prefix = preferences.getString(CUIPlugin.PLUGIN_ID, PreferenceConstants.NAME_STYLE_FIELD_PREFIX, "", null); if (fieldName.startsWith(prefix)) fieldName = fieldName.substring(prefix.length()); int firstWordStart = -1; int lastWordEnd = -1; for (int i = 0; i < fieldName.length(); ++i) { if (Character.isLetterOrDigit(fieldName.charAt(i))) { int pos = i + 1; while (--pos >= i && !Character.isLetterOrDigit(fieldName.charAt(pos))) { } lastWordEnd = pos + 1; if (firstWordStart < 0) { firstWordStart = i; } } } if (firstWordStart < 0) { return fieldName; } else { return fieldName.substring(firstWordStart, lastWordEnd); } }
Source:
public void setup() { Robolectric.getBackgroundThreadScheduler().pause(); Robolectric.getForegroundThreadScheduler().pause(); ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory()); setupPrototypeFactory(); TestAppInstaller appTestInstaller = new TestAppInstaller("jr://resource/commcare-apps/flipper/profile.ccpr", "fp", "123"); appTestInstaller.installAppAndLogin(); }

Target:
public void setup() { ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory()); setupPrototypeFactory(); TestAppInstaller appTestInstaller = new TestAppInstaller("jr://resource/commcare-apps/flipper/profile.ccpr", "fp", "123"); appTestInstaller.installAppAndLogin(); }
Source:
public void testNotFoundGetTTL() throws IOException { TestUtils.verifyException(HttpFailureException.class, new Callable<Void>() { @Override public Void call() throws Exception { streamClient.getTTL(TestUtils.NOT_FOUND_STREAM_NAME); return null; } }); }

Target:
public void testNotFoundGetTTL() throws IOException { try { streamClient.getTTL(TestUtils.NOT_FOUND_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getStatusCode()); } }
Source:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { return indexService.getIndexProxy( NewIndexDescriptorFactory.forSchema( descriptor ) ).getIndexPopulationProgress(); }

Target:
public PopulationProgress indexGetPopulationProgress( LabelSchemaDescriptor descriptor ) throws IndexNotFoundKernelException { return indexService.getIndexProxy( descriptor ).getIndexPopulationProgress(); }
Source:
public void addStateTo(StateDumpCollector dump) { ClusterTierManagerDump.dump(dump, clusterTierManagerConfig); { Map<ClientDescriptor, ClientState> clients = new HashMap<>(clientStateMap); dump.addState("clientCount", String.valueOf(clients.size())); List<Map> allClients = new ArrayList<>(); for (Map.Entry<ClientDescriptor, ClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); allClients.add(clientMap); } dump.addState("clients", allClients); } }

Target:
public void addStateTo(StateDumpCollector dump) { ClusterTierManagerDump.dump(dump, clusterTierManagerConfig); { Map<ClientDescriptor, ClientState> clients = new HashMap<>(clientStateMap); List<Map> allClients = new ArrayList<>(); for (Map.Entry<ClientDescriptor, ClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(3); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); allClients.add(clientMap); } dump.addState("clientCount", String.valueOf(allClients.size())); dump.addState("clients", allClients); } }
Source:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new LinkedList<IRecord>(); ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }

Target:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new ArrayList<IRecord>(); ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }
Source:
private KijiFuture<Object> deleteGroupFamily( final EntityId entityId, final FamilyLayout familyLayout, final long upToTimestamp ) throws IOException { final String familyName = Preconditions.checkNotNull(familyLayout.getName()); final HBaseColumnNameTranslator colNameTranslator = mWriterLayoutCapsule.getColumnNameTranslator(); int i = 0; final int numColumnLayouts = familyLayout.getColumnMap().size(); byte[][] qualifiers = new byte[numColumnLayouts][]; for (ColumnLayout columnLayout : familyLayout.getColumnMap().values()) { final String qualifier = columnLayout.getName(); final KijiColumnName column = KijiColumnName.create(familyName, qualifier); final HBaseColumnName hbaseColumnName = colNameTranslator.toHBaseColumnName(column); qualifiers[i] = hbaseColumnName.getQualifier(); i ++; } final byte[] hbaseFamilyName = mWriterLayoutCapsule.getColumnNameTranslator(). toHBaseFamilyName(familyLayout.getLocalityGroup()); final DeleteRequest delete = new DeleteRequest( mTableName, entityId.getHBaseRowKey(), hbaseFamilyName, qualifiers, upToTimestamp); Deferred<Object> deferred = mHBClient.delete(delete); return AsyncHBaseKijiFuture.create(deferred); }

Target:
private KijiFuture<Object> deleteGroupFamily( final EntityId entityId, final FamilyLayout familyLayout, final long upToTimestamp ) throws IOException { final String familyName = familyLayout.getName(); final HBaseColumnNameTranslator colNameTranslator = mWriterLayoutCapsule.getColumnNameTranslator(); int i = 0; final int numColumnLayouts = familyLayout.getColumnMap().size(); byte[][] qualifiers = new byte[numColumnLayouts][]; for (ColumnLayout columnLayout : familyLayout.getColumnMap().values()) { final String qualifier = columnLayout.getName(); final KijiColumnName column = KijiColumnName.create(familyName, qualifier); final HBaseColumnName hbaseColumnName = colNameTranslator.toHBaseColumnName(column); qualifiers[i] = hbaseColumnName.getQualifier(); i++; } final byte[] hbaseFamilyName = mWriterLayoutCapsule.getColumnNameTranslator(). toHBaseFamilyName(familyLayout.getLocalityGroup()); final DeleteRequest delete = new DeleteRequest( mTableName, entityId.getHBaseRowKey(), hbaseFamilyName, qualifiers, upToTimestamp); Deferred<Object> deferred = mHBClient.delete(delete); return AsyncHBaseKijiFuture.create(deferred); }
Source:
default CacheContainerAdmin administration() { throw new UnsupportedOperationException(); }

Target:
default CacheContainerAdmin<?> administration() { throw new UnsupportedOperationException(); }
Source:
public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, Set<Integer> requestsToDrop, int pollTimeoutMs) { if (closed) { throw new IllegalStateException("The client is closed."); } if (processorId < 0) { throw new IllegalStateException("The processorId has not been set."); } long startTime = time.milliseconds(); try { for (RequestInfo requestInfo : requestInfos) { ByteBuffer buffer = LocalRequestResponseChannel.byteBufferFromPayload(requestInfo.getRequest()); channel.sendRequest(new LocalChannelRequest(requestInfo, processorId, new ByteBufferInputStream(buffer))); } } catch (Exception e) { logger.error("Received an unexpected error during sendAndPoll(): ", e); networkMetrics.networkClientException.inc(); } List<ResponseInfo> responses = channel.receiveResponses(processorId); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime, TimeUnit.MILLISECONDS); return responses; }

Target:
public List<ResponseInfo> sendAndPoll(List<RequestInfo> requestInfos, Set<Integer> requestsToDrop, int pollTimeoutMs) { if (closed) { throw new IllegalStateException("The client is closed."); } long startTime = time.milliseconds(); try { for (RequestInfo requestInfo : requestInfos) { ByteBuffer buffer = LocalRequestResponseChannel.byteBufferFromPayload(requestInfo.getRequest()); channel.sendRequest(new LocalChannelRequest(requestInfo, processorId, new ByteBufferInputStream(buffer))); } } catch (Exception e) { logger.error("Received an unexpected error during sendAndPoll(): ", e); networkMetrics.networkClientException.inc(); } List<ResponseInfo> responses = channel.receiveResponses(processorId, pollTimeoutMs); networkMetrics.networkClientSendAndPollTime.update(time.milliseconds() - startTime, TimeUnit.MILLISECONDS); return responses; }
Source:
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { Function<SecurityDomain, IdentityCache> cacheFunction = createIdentityCacheFunction(request); if (cacheFunction!= null && attemptReAuthentication(request, cacheFunction)) { httpClientCert.trace("ClientCertAuthenticationMechanism: re-authentication succeed"); return; } if (attemptAuthentication(request, cacheFunction)) { return; } httpClientCert.trace("ClientCertAuthenticationMechanism: both, re-authentication and authentication, failed"); fail(request); }

Target:
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { Function<SecurityDomain, IdentityCache> cacheFunction = createIdentityCacheFunction(request); if (cacheFunction!= null && attemptReAuthentication(request, cacheFunction)) { httpClientCert.trace("Re-authentication succeed"); return; } if (attemptAuthentication(request, cacheFunction)) { return; } httpClientCert.trace("Both, re-authentication and authentication, failed"); fail(request); }
Source:
public SampleClass inferStockFromAliquot(SampleClass sampleClass) { SampleClass aliquotClass = sampleClassDao.getSampleClass(sampleClass.getId()); if (aliquotClass == null || !aliquotClass.getSampleCategory().equals(SampleAliquot.CATEGORY_NAME)) { throw new IllegalArgumentException("Sample class " + sampleClass.getId() + " is not a valid aliquot class."); } SampleClass stockClass = null; for (SampleValidRelationship relationship : sampleValidRelationshipDao.getSampleValidRelationship()) { if (relationship.getChild().getId() == aliquotClass.getId() && relationship.getParent().getSampleCategory().equals(SampleStock.CATEGORY_NAME)) { if (stockClass == null) { stockClass = relationship.getParent(); } else { throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has multiple stock class parents."); } } } if (stockClass == null) throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has no stock class."); return stockClass; }

Target:
public SampleClass inferStockFromAliquot(SampleClass sampleClass) { SampleClass aliquotClass = sampleClassDao.getSampleClass(sampleClass.getId()); if (aliquotClass == null || !aliquotClass.getSampleCategory().equals(SampleAliquot.CATEGORY_NAME)) { throw new IllegalArgumentException("Sample class " + sampleClass.getId() + " is not a valid aliquot class."); } SampleClass stockClass = null; for (SampleValidRelationship relationship : sampleValidRelationshipDao.getSampleValidRelationship()) { if (!relationship.getArchived() && relationship.getChild().getId() == aliquotClass.getId() && relationship.getParent().getSampleCategory().equals(SampleStock.CATEGORY_NAME)) { if (stockClass == null) { stockClass = relationship.getParent(); } else { throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has multiple stock class parents."); } } } if (stockClass == null) throw new IllegalStateException("Aliquot class " + sampleClass.getId() + " has no stock class."); return stockClass; }
Source:
public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Model Type Id: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); END: com.azure.ai.formrecognizer.FormTrainingAsyncClient.getCustomModel#string }

Target:
public void getCustomModel() { String modelId = "{model_id}"; formTrainingAsyncClient.getCustomModel(modelId).subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); END: com.azure.ai.formrecognizer.FormTrainingAsyncClient.getCustomModel#string }
Source:
public synchronized int getLoadBalanceFactor(Engine engine) { boolean nodeUnavailable = false; int totalWeight = 0; double totalWeightedLoad = 0; for (Map.Entry<LoadMetric, List<Double>> entry : this.loadHistory.entrySet()) { LoadMetric metric = entry.getKey(); int weight = metric.getWeight(); if (weight > 0) { List<Double> metricLoadHistory = entry.getValue(); try { this.recordLoad(metricLoadHistory, metric.getLoad(engine) / metric.getCapacity()); totalWeight += weight; totalWeightedLoad += this.average(metricLoadHistory) * weight; } catch (NodeUnavailableException e) { nodeUnavailable = true; } catch (Exception e) { this.log.error(e.getLocalizedMessage(), e); } } } if (nodeUnavailable) { return -1; } else { int load = (int) Math.round(100 * totalWeightedLoad / totalWeight); return 100 - Math.max(0, Math.min(load, 99)); } }

Target:
public synchronized int getLoadBalanceFactor(Engine engine) { boolean nodeUnavailable = false; int totalWeight = 0; double totalWeightedLoad = 0; for (Map.Entry<LoadMetric, List<Double>> entry : this.loadHistory.entrySet()) { LoadMetric metric = entry.getKey(); int weight = metric.getWeight(); if (weight > 0) { List<Double> metricLoadHistory = entry.getValue(); try { this.recordLoad(metricLoadHistory, metric.getLoad(engine) / metric.getCapacity()); totalWeight += weight; totalWeightedLoad += this.average(metricLoadHistory) * weight; } catch (NodeUnavailableException e) { nodeUnavailable = true; } catch (Exception e) { this.log.error(e.getLocalizedMessage(), e); } } } if (nodeUnavailable) { return -1; } int load = (int) Math.round(100 * totalWeightedLoad / totalWeight); return 100 - Math.max(0, Math.min(load, 99)); }