List of usage examples for java.util Map toString
public String toString()
From source file:dev.meng.wikipedia.profiler.metadata.Metadata.java
private void queryFileInfo(String lang, String title, FileInfo file) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("titles", title); params.put("prop", "imageinfo"); params.put("iiprop", "size"); try {/* ww w . j a va2 s.c o m*/ String urlString = StringUtils.replace(Configure.METADATA.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params); URL url = new URL(urlString); JSONObject response = queryForJSONResponse(url); try { JSONObject pageMap = response.getJSONObject("query").getJSONObject("pages"); JSONObject pageRecord = pageMap.getJSONObject((String) pageMap.keys().next()); if (pageRecord.has("imageinfo")) { JSONArray fileInfoList = pageRecord.getJSONArray("imageinfo"); file.setSize(fileInfoList.getJSONObject(0).getLong("size")); } else { file.setSize(0L); } } catch (JSONException ex) { LogHandler.log(this, LogLevel.WARN, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { LogHandler.log(this, LogLevel.WARN, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } catch (IOException ex) { LogHandler.log(this, LogLevel.ERROR, ex); } }
From source file:org.apache.cloudstack.region.RegionManagerImpl.java
@Override public boolean propagateAddAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details, String accountUUID, String userUUID) { String command = "createAccount"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair(ApiConstants.USERNAME, userName)); params.add(new NameValuePair(ApiConstants.PASSWORD, password)); params.add(new NameValuePair(ApiConstants.FIRSTNAME, firstName)); params.add(new NameValuePair(ApiConstants.LASTNAME, lastName)); params.add(new NameValuePair(ApiConstants.EMAIL, email)); params.add(new NameValuePair(ApiConstants.TIMEZONE, timezone)); params.add(new NameValuePair(ApiConstants.ACCOUNT, accountName)); params.add(new NameValuePair(ApiConstants.ACCOUNT_TYPE, "" + accountType)); //ToDo: use domain UUID params.add(new NameValuePair(ApiConstants.DOMAIN_ID, ((domainId != null) ? domainId.toString() : ""))); params.add(new NameValuePair(ApiConstants.NETWORK_DOMAIN, networkDomain)); params.add(new NameValuePair(ApiConstants.ACCOUNT_DETAILS, (details != null) ? details.toString() : "")); params.add(new NameValuePair(ApiConstants.ACCOUNT_ID, accountUUID)); params.add(new NameValuePair(ApiConstants.USER_ID, userUUID)); params.add(new NameValuePair(ApiConstants.REGION_ID, "" + getId())); List<RegionVO> regions = _regionDao.listAll(); for (Region region : regions) { if (region.getId() == getId()) { continue; }/*from w ww. j a v a 2s . co m*/ s_logger.debug("Adding account :" + accountName + " to Region: " + region.getId()); if (RegionsApiUtil.makeAPICall(region, command, params)) { s_logger.debug("Successfully added account :" + accountName + " to Region: " + region.getId()); } else { // api call failed. Add entry in region_sync table addRegionSyncItem(region.getId(), command, params); s_logger.error("Error while Adding account :" + accountName + " to Region: " + region.getId()); } } return true; }
From source file:com.linkedin.databus.core.TestDbusEventBufferMult.java
private void batchReading(Set<Integer> srcIds, final int expectEvents, final int batchFetchSize) throws IOException, ScnNotFoundException, DatabusException, OffsetNotFoundException { // for debug generate this line String inputSrcIds = Arrays.toString(srcIds.toArray()); LOG.info("Reading events from " + inputSrcIds); // create checkpoints CheckpointMult cpMult = new CheckpointMult(); for (PhysicalSourceStaticConfig pConf : _pConfigs) { PhysicalPartition pPart = pConf.getPhysicalPartition(); Checkpoint cp;/*from w ww . j av a 2 s . c o m*/ if (cpMult.getCheckpoint(pPart) == null) { // needs a new checkpoint cp = new Checkpoint(); cp.setFlexible(); cpMult.addCheckpoint(pPart, cp); } } DbusEventBufferBatchReadable read = _eventBufferMult.getDbusEventBufferBatchReadable(srcIds, cpMult, null); int totalRead = 0; int numEventsRead = Integer.MAX_VALUE; int numNonControlEventsRead = 0; int maxIterNum = 100, iterCount = 0; String prevEvent = ""; while (numEventsRead > 0) { if (iterCount++ > maxIterNum) { fail("Checkpoint doesn't work - it is a never-ending loop"); } ByteArrayOutputStream jsonOut = new ByteArrayOutputStream(); WritableByteChannel jsonOutChannel = Channels.newChannel(jsonOut); numEventsRead = read.streamEvents(false, batchFetchSize, jsonOutChannel, Encoding.JSON_PLAIN_VALUE, new SourceDbusFilter(srcIds)).getNumEventsStreamed(); totalRead += numEventsRead; LOG.info("read for " + inputSrcIds + ": " + numEventsRead + " events"); byte[] jsonBytes = jsonOut.toByteArray(); if (jsonBytes.length == 0) break; // nothing more to read String jsonString = new String(jsonBytes); String[] jsonStrings = jsonString.split("\n"); assertEquals(jsonStrings.length, numEventsRead); ObjectMapper mapper = new ObjectMapper(); for (int i = 0; i < jsonStrings.length; i++) { // verify what was written String evtStr = jsonStrings[i]; if (evtStr.equals(prevEvent)) { // It may so happen that we receive the same event twice, especially when the // offered buffer is small. This check gets around the issue. continue; } prevEvent = evtStr; Map<String, Object> jsonMap = mapper.readValue(evtStr, new TypeReference<Map<String, Object>>() { }); //assertEquals(jsonMap.size(), 10); Integer srcId = (Integer) jsonMap.get("srcId"); if (!DbusEventUtils.isControlSrcId(srcId)) { // not a control message numNonControlEventsRead++; Integer physicalPartitionId = (Integer) jsonMap.get("physicalPartitionId"); Integer logicalPartitionId = (Integer) jsonMap.get("logicalPartitionId"); PhysicalPartition pPartition = _eventBufferMult.getPhysicalPartition(srcId, new LogicalPartition(logicalPartitionId.shortValue())); LOG.info("EVENT: " + jsonMap.toString()); assertTrue(srcIds.contains(srcId), "src id " + srcId + " doesn't match to " + inputSrcIds); assertEquals(physicalPartitionId, pPartition.getId(), "physical partition id didn't match"); } else { LOG.info("Control event: " + jsonMap.toString()); } } } assertTrue(totalRead > numNonControlEventsRead); assertEquals(numNonControlEventsRead, expectEvents); }
From source file:edu.unc.lib.dl.cdr.sword.server.deposit.AbstractDepositHandler.java
protected void registerDeposit(PID depositPid, PID destination, Deposit deposit, PackagingType type, String depositor, String owner, Map<String, String> extras) throws SwordError { Map<String, String> chkstatus = this.depositStatusFactory.get(depositPid.getUUID()); if (chkstatus != null && !chkstatus.isEmpty()) throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, 400, "Duplicate request, repository already has deposit " + depositPid); Map<String, String> status = new HashMap<String, String>(); status.putAll(extras);//from www .jav a2s. c o m // generic deposit fields status.put(DepositField.uuid.name(), depositPid.getUUID()); status.put(DepositField.submitTime.name(), String.valueOf(System.currentTimeMillis())); status.put(DepositField.fileName.name(), deposit.getFilename()); String email = SwordConfigurationImpl.getUserEmailAddress(); status.put(DepositField.depositorName.name(), email != null ? depositor : owner); status.put(DepositField.depositorEmail.name(), email != null ? email : owner + "@email.unc.edu"); status.put(DepositField.containerId.name(), destination.getPid()); status.put(DepositField.depositMethod.name(), DepositMethod.SWORD13.getLabel()); status.put(DepositField.packagingType.name(), type.getUri()); status.put(DepositField.depositMd5.name(), deposit.getMd5()); status.put(DepositField.depositSlug.name(), deposit.getSlug()); String permGroups = null; if (this.getOverridePermissionGroups() != null) { permGroups = StringUtils.join(this.getOverridePermissionGroups(), ';'); } else { permGroups = StringUtils.join(GroupsThreadStore.getGroups(), ';'); } status.put(DepositField.permissionGroups.name(), permGroups); status.put(DepositField.state.name(), DepositState.unregistered.name()); status.put(DepositField.actionRequest.name(), DepositAction.register.name()); Set<String> nulls = new HashSet<String>(); for (String key : status.keySet()) { if (status.get(key) == null) nulls.add(key); } for (String key : nulls) status.remove(key); this.depositStatusFactory.save(depositPid.getUUID(), status); log.info(status.toString()); }
From source file:es.upv.grycap.coreutils.fiber.net.UrlBuilder.java
/** * Creates a new URL relative to the base URL provided in the constructor of this class. The new relative URL * includes the path, query parameters and the internal reference of the {@link UrlBuilder#baseUrl base URL} * provided with this class. An additional fragment, as well as additional query parameters can be optionally * added to the new URL. In addition to the parameters passed to the method as an argument, the supplied * fragment can also include parameters that will be added to the created URL. The created URL is normalized * and unencoded before returning it to the caller. The current implementation has the following limitations: * <ul>/* ww w.ja va 2s.c o m*/ * <li>Arrays are not supported: <tt>q=foo&q=bar</tt> will produce an error.</li> * <li>Internal references are only supported in the base URL. Any additional reference provided with the * fragment will be silently ignored: the fragment <tt>/rd#ref</tt> will be appended to the base URL as * <tt>/rd</tt>, ignoring the internal reference.</li> * </ul> * @param fragment - optional URL fragment (may include parameters, but not references) that will be added * to the base URL * @param params - optional query parameters that will be added to the base URL * @return A relative URL created from the base URL provided in the constructor of this class and adding the * fragment and parameters passed as arguments to this method. */ public String buildRelativeUrl(final @Nullable String fragment, final @Nullable Map<String, String> params) { String url = null; final Optional<String> fragment2 = ofNullable(trimToNull(fragment)); try { final Optional<URL> fragmentUrl = ofNullable( fragment2.isPresent() ? new URL("http://example.com/" + fragment2.get()) : null); final URIBuilder uriBuilder = new URIBuilder(); // add path uriBuilder.setPath(new StringBuilder(ofNullable(trimToNull(baseUrl.getPath())).orElse("/")) .append(fragmentUrl.isPresent() ? "/" + stripEnd(fragmentUrl.get().getPath(), "/") : "") .toString().replaceAll("[/]{2,}", "/")); // add query parameters if (isNotBlank(baseUrl.getQuery())) { uriBuilder.setParameters(URLEncodedUtils.parse(baseUrl.getQuery(), defaultCharset())); } if (fragmentUrl.isPresent() && isNotBlank(fragmentUrl.get().getQuery())) { URLEncodedUtils.parse(fragmentUrl.get().getQuery(), defaultCharset()).stream().forEach(p -> { uriBuilder.addParameter(p.getName(), p.getValue()); }); } ofNullable(params).orElse(emptyMap()).entrySet().stream().forEach(p -> { uriBuilder.addParameter(p.getKey(), p.getValue()); }); // add internal reference uriBuilder.setFragment(baseUrl.getRef()); // build relative URL url = uriBuilder.build().normalize().toString(); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalStateException( new StringBuilder("Failed to create relative URL from provided parameters: fragment=") .append(fragment2.orElse("null")).append(", params=") .append(params != null ? params.toString() : "null").toString(), e); } return url; }
From source file:com.baasbox.service.push.providers.GCMServer.java
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws PushNotInitializedException, InvalidRequestException, UnknownHostException, IOException, PushTimeToLiveFormatException, PushCollapseKeyFormatException { PushLogger pushLogger = PushLogger.getInstance(); pushLogger.addMessage("............ GCM Push Message: -%s- to the device(s) %s", message, deviceid); try {/*from w w w.j av a 2 s .c o m*/ if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("GCM Push message: " + message + " to the device " + deviceid); if (!isInit) { pushLogger.addMessage("............ GCMS is not initialized!"); return true; } JsonNode customDataNodes = bodyJson.get("custom"); Map<String, JsonNode> customData = new HashMap<String, JsonNode>(); if (!(customDataNodes == null)) { customData.put("custom", customDataNodes); } JsonNode collapse_KeyNode = bodyJson.findValue("collapse_key"); String collapse_key = null; if (!(collapse_KeyNode == null)) { if (!(collapse_KeyNode.isTextual())) throw new PushCollapseKeyFormatException("Collapse_key MUST be a String"); collapse_key = collapse_KeyNode.asText(); } else collapse_key = ""; JsonNode timeToLiveNode = bodyJson.findValue("time_to_live"); int time_to_live = 0; if (!(timeToLiveNode == null)) { if (!(timeToLiveNode.isNumber())) throw new PushTimeToLiveFormatException("Time_to_live MUST be a positive number or equal zero"); else if (timeToLiveNode.asInt() < 0) throw new PushTimeToLiveFormatException("Time_to_live MUST be a positive number or equal zero"); else if (timeToLiveNode.asInt() > MAX_TIME_TO_LIVE) { time_to_live = MAX_TIME_TO_LIVE; } else time_to_live = timeToLiveNode.asInt(); } else time_to_live = MAX_TIME_TO_LIVE; //IF NULL WE SET DEFAULT VALUE (4 WEEKS) if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("collapse_key: " + collapse_key.toString()); if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("time_to_live: " + time_to_live); if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Custom Data: " + customData.toString()); pushLogger.addMessage("............ messgae: %s", message); pushLogger.addMessage("............ collapse_key: %s", collapse_key); pushLogger.addMessage("............ time_to_live: %s", time_to_live); pushLogger.addMessage("............ custom: %s", customData); pushLogger.addMessage("............ device(s): %s", deviceid); Sender sender = new Sender(apikey); Message msg = new Message.Builder().addData("message", message).addData("custom", customData.toString()) .collapseKey(collapse_key.toString()).timeToLive(time_to_live).build(); MulticastResult result = sender.send(msg, deviceid, 1); pushLogger.addMessage("............ %d message(s) sent", result.getTotal()); pushLogger.addMessage("................. success: %s", result.getSuccess()); pushLogger.addMessage("................. failure: %s", result.getFailure()); for (Result r : result.getResults()) { pushLogger.addMessage("............ MessageId (null == error): %s", r.getMessageId()); pushLogger.addMessage("............... Error Code Name: %s", r.getErrorCodeName()); pushLogger.addMessage("............... Canonincal Registration Id: %s", r.getCanonicalRegistrationId()); } // icallbackPush.onError(ExceptionUtils.getMessage(e)); // icallbackPush.onSuccess(); return false; } catch (Exception e) { pushLogger.addMessage("Error sending push notification (GCM)..."); pushLogger.addMessage(ExceptionUtils.getMessage(e)); throw e; } }
From source file:com.datafibers.kafka.connect.SchemaedFileSourceTask.java
private List<SourceRecord> pollFromFile() throws InterruptedException { log.trace("pollFromFile"); CsvSchema bootstrapCsv;/*w ww. j a v a 2 s. c o m*/ CsvMapper csvMapper = new CsvMapper(); ObjectMapper jsonMapper = new ObjectMapper(); MappingIterator<Map<?, ?>> mappingIterator; ArrayList<SourceRecord> records = null; long currentTime = System.currentTimeMillis(); long recordsPerPoll; // TODO: Improve ExceptionOnEof logic. // The code below only works when each pass through // poll() reads all available records (not a given). if (config.getExceptionOnEof() && streamOffset != null) { throw new ConnectException("No more deta available on FileInputStream"); } // Initialize the bootstrapCsv schema if necessary if (recordSchema == null || inputType.equalsIgnoreCase("json")) { log.trace("Constructing csvSchema from emptySchema"); bootstrapCsv = config.getCsvHeaders() ? CsvSchema.emptySchema().withHeader() : CsvSchema.emptySchema().withoutHeader(); } else { // We've seen a schema, so we'll assume headers from the recordSchema log.trace("Constructing csvSchema from recordSchema"); CsvSchema.Builder builder = new CsvSchema.Builder(); builder.setUseHeader(false); builder.setColumnSeparator(','); for (Field f : recordSchema.fields()) { log.trace("adding column {}", f.name()); builder.addColumn(f.name()); } bootstrapCsv = builder.build(); } try { if (stream == null) openFileStream(); if (reader == null) reader = new BufferedReader(new InputStreamReader(stream)); if (inputType.equalsIgnoreCase("json")) { mappingIterator = jsonMapper.readerFor(Map.class).readValues(reader); } else if (inputType.equalsIgnoreCase("csv")) { mappingIterator = csvMapper.readerWithSchemaFor(Map.class).with(bootstrapCsv).readValues(reader); } else { log.error("Unsupported file input type specified ({})", inputType); return null; } } catch (FileNotFoundException fnf) { log.warn("Couldn't find file {} for SchemaedFileSourceTask, sleeping to wait for it to be created", logFilename()); synchronized (this) { this.wait(1000); } return null; } catch (IOException e) { // IOException thrown when no more records in stream log.warn("Processed all available data from {}; sleeping to wait additional records", logFilename()); // Close reader and stream; swallowing exceptions ... we're about to throw a Retry try { reader.close(); } catch (Exception nested) { } finally { reader = null; } if (stream != System.in) { try { stream.close(); } catch (Exception nested) { } finally { stream = null; } } synchronized (this) { this.wait(1000); } return null; } log.debug("mappingIterator of type {} created; begin reading data file", mappingIterator.getClass().toString()); // The csvMapper class is really screwy; can't figure out why it // won't return a rational Schema ... so we'll extract it from the // the first object later. if (recordSchema == null && inputType.equalsIgnoreCase("csv") && csvMapper.schema().size() > 0) { recordSchema = ConvertMappingSchema(csvMapper.schemaWithHeader()); log.trace("recordSchema created from csvMapper; type {}", recordSchema.type().toString()); } try { FileInputStream fstream = (FileInputStream) stream; Long lastElementOffset = streamOffset; recordsPerPoll = 3; while (mappingIterator.hasNext()) { Map<?, ?> element = mappingIterator.next(); Long elementOffset, iteratorOffset; recordCount++; recordsPerPoll--; iteratorOffset = mappingIterator.getCurrentLocation().getByteOffset(); // never works !!! if (iteratorOffset < 0) { // The stream channel will CLOSE on the last clean record // seen by mapping Iterator, so we have be careful here // Additionally, when parsing CSV files, there seems to be a // lot of Bad File Descriptor errors; ignore them. try { elementOffset = fstream.getChannel().position(); } catch (java.nio.channels.ClosedChannelException e) { log.trace("getChannel.position threw {}", e.toString()); elementOffset = lastElementOffset; } catch (IOException e) { log.trace("getChannel.position threw {}", e.toString()); elementOffset = lastElementOffset; } } else { log.trace("mappingIterator.getCurrentLocation() returns {}", iteratorOffset.toString()); elementOffset = iteratorOffset; } log.trace("Next input record: {} (class {}) from file position {}", element.toString(), element.getClass().toString(), elementOffset.toString()); if (recordSchema == null) { recordSchema = ConvertMappingSchema(element.keySet()); log.trace("recordSchema created from element; type {}", recordSchema.type().toString()); } if (records == null) records = new ArrayList<>(); records.add(new SourceRecord(offsetKey(filename), offsetValue(elementOffset), topic, recordSchema, ConvertMappingElement(recordSchema, (HashMap<?, ?>) element))); streamOffset = lastElementOffset = elementOffset; } } catch (Exception e) { throw new ConnectException(e); } lastPollTime = currentTime; return records; }
From source file:org.gbif.portal.webservices.rest.Dispatcher.java
/** * Generate a cleaned parameters map from a get request, including any attributes (from URL rewriting) * //from w w w .ja va2 s .co m * @param request * @return parameters map * @throws GbifWebServiceException */ protected Map<String, Object> processGet(HttpServletRequest request) throws GbifWebServiceException { Map<String, Object> kvps = new HashMap<String, Object>(); Enumeration enumeration = request.getParameterNames(); // Place the first value in the map under its own name (since in general // most parameters are processed as singletons, but if there are more // than one values, also insert the array under the name "<name>_array". if (enumeration != null) { Map parameterMap = request.getParameterMap(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String[] values = (String[]) parameterMap.get(name); kvps.put(name.toLowerCase(), values[0]); if (values.length > 1) { kvps.put(name + ARRAY_SUFFIX, values); } } } enumeration = request.getAttributeNames(); if (enumeration != null) { while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); Object value = request.getAttribute(name); if (value instanceof String) { kvps.put(name.toLowerCase(), (String) value); } } } String url = request.getRequestURL().toString(); String servletPath = request.getServletPath(); String urlBase = url.substring(0, url.indexOf(servletPath)); kvps.put("portalroot", urlBase); kvps.put("wsroot", urlBase + servletPath); log.debug("Parameter map: " + kvps.toString()); return kvps; }
From source file:mom.trd.opentheso.bdd.helper.ThesaurusHelper.java
/** * Retourne la liste des traductions d'un thesaurus sous forme de MAP (lang * + title)// w w w . j a v a 2s . c om * * @param ds * @param idThesaurus * @return */ public Map getMapTraduction(HikariDataSource ds, String idThesaurus) { Connection conn; Statement stmt; ResultSet resultSet; Map map = new HashMap(); try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "select lang, title from thesaurus_label" + " where id_thesaurus = '" + idThesaurus + "'"; stmt.executeQuery(query); resultSet = stmt.getResultSet(); if (resultSet != null) { while (resultSet.next()) { map.put(resultSet.getString("lang"), resultSet.getString("title")); } } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while getting Map of thesaurus : " + map.toString(), sqle); } return map; }
From source file:org.apache.hadoop.hbase.master.HMaster.java
public boolean balance() throws IOException { // if master not initialized, don't run balancer. if (!this.initialized) { LOG.debug("Master has not been initialized, don't run balancer."); return false; }/*from w ww . ja va2 s.co m*/ // Do this call outside of synchronized block. int maximumBalanceTime = getBalancerCutoffTime(); boolean balancerRan; synchronized (this.balancer) { // If balance not true, don't run balancer. if (!this.loadBalancerTracker.isBalancerOn()) return false; // Only allow one balance run at at time. if (this.assignmentManager.getRegionStates().isRegionsInTransition()) { Map<String, RegionState> regionsInTransition = this.assignmentManager.getRegionStates() .getRegionsInTransition(); LOG.debug("Not running balancer because " + regionsInTransition.size() + " region(s) in transition: " + org.apache.commons.lang.StringUtils.abbreviate(regionsInTransition.toString(), 256)); return false; } if (this.serverManager.areDeadServersInProgress()) { LOG.debug("Not running balancer because processing dead regionserver(s): " + this.serverManager.getDeadServers()); return false; } if (this.cpHost != null) { try { if (this.cpHost.preBalance()) { LOG.debug("Coprocessor bypassing balancer request"); return false; } } catch (IOException ioe) { LOG.error("Error invoking master coprocessor preBalance()", ioe); return false; } } Map<TableName, Map<ServerName, List<HRegionInfo>>> assignmentsByTable = this.assignmentManager .getRegionStates().getAssignmentsByTable(); List<RegionPlan> plans = new ArrayList<RegionPlan>(); //Give the balancer the current cluster state. this.balancer.setClusterStatus(getClusterStatus()); for (Map<ServerName, List<HRegionInfo>> assignments : assignmentsByTable.values()) { List<RegionPlan> partialPlans = this.balancer.balanceCluster(assignments); if (partialPlans != null) plans.addAll(partialPlans); } long cutoffTime = System.currentTimeMillis() + maximumBalanceTime; int rpCount = 0; // number of RegionPlans balanced so far long totalRegPlanExecTime = 0; balancerRan = plans != null; if (plans != null && !plans.isEmpty()) { for (RegionPlan plan : plans) { LOG.info("balance " + plan); long balStartTime = System.currentTimeMillis(); //TODO: bulk assign this.assignmentManager.balance(plan); totalRegPlanExecTime += System.currentTimeMillis() - balStartTime; rpCount++; if (rpCount < plans.size() && // if performing next balance exceeds cutoff time, exit the loop (System.currentTimeMillis() + (totalRegPlanExecTime / rpCount)) > cutoffTime) { //TODO: After balance, there should not be a cutoff time (keeping it as a security net for now) LOG.debug("No more balancing till next balance run; maximumBalanceTime=" + maximumBalanceTime); break; } } } if (this.cpHost != null) { try { this.cpHost.postBalance(rpCount < plans.size() ? plans.subList(0, rpCount) : plans); } catch (IOException ioe) { // balancing already succeeded so don't change the result LOG.error("Error invoking master coprocessor postBalance()", ioe); } } } return balancerRan; }