List of usage examples for java.lang Long compare
public static int compare(long x, long y)
From source file:org.apache.carbondata.core.statusmanager.SegmentUpdateStatusManager.java
/** * Returns all update delta files of specified Segment. * * @param segmentId//from w w w .jav a2 s. c om * @param validUpdateFiles * @param fileExtension * @param excludeOriginalFact * @param allFilesOfSegment * @return */ public CarbonFile[] getUpdateDeltaFilesForSegment(String segmentId, final boolean validUpdateFiles, final String fileExtension, final boolean excludeOriginalFact, CarbonFile[] allFilesOfSegment) { String endTimeStamp = ""; String startTimeStamp = ""; long factTimeStamp = 0; for (LoadMetadataDetails eachSeg : segmentDetails) { if (eachSeg.getLoadName().equalsIgnoreCase(segmentId)) { // if the segment is found then take the start and end time stamp. startTimeStamp = eachSeg.getUpdateDeltaStartTimestamp(); endTimeStamp = eachSeg.getUpdateDeltaEndTimestamp(); factTimeStamp = eachSeg.getLoadStartTime(); } } // if start timestamp is empty then no update delta is found. so return empty list. if (startTimeStamp.isEmpty()) { return new CarbonFile[0]; } final Long endTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(endTimeStamp); final Long startTimeStampFinal = CarbonUpdateUtil.getTimeStampAsLong(startTimeStamp); final long factTimeStampFinal = factTimeStamp; List<CarbonFile> listOfCarbonFiles = new ArrayList<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); // else scan the segment for the delta files with the respective timestamp. for (CarbonFile eachFile : allFilesOfSegment) { String fileName = eachFile.getName(); if (fileName.endsWith(fileExtension)) { String firstPart = fileName.substring(0, fileName.indexOf('.')); long timestamp = Long.parseLong(firstPart .substring(firstPart.lastIndexOf(CarbonCommonConstants.HYPHEN) + 1, firstPart.length())); if (excludeOriginalFact) { if (Long.compare(factTimeStampFinal, timestamp) == 0) { continue; } } if (validUpdateFiles) { if (Long.compare(timestamp, endTimeStampFinal) <= 0 && Long.compare(timestamp, startTimeStampFinal) >= 0) { boolean validBlock = true; for (SegmentUpdateDetails blockDetails : getUpdateStatusDetails()) { if (blockDetails.getActualBlockName().equalsIgnoreCase(eachFile.getName()) && CarbonUpdateUtil.isBlockInvalid(blockDetails.getSegmentStatus())) { validBlock = false; } } if (validBlock) { listOfCarbonFiles.add(eachFile); } } } else { // invalid cases. if (Long.compare(timestamp, startTimeStampFinal) < 0) { listOfCarbonFiles.add(eachFile); } } } } return listOfCarbonFiles.toArray(new CarbonFile[listOfCarbonFiles.size()]); }
From source file:com.oneops.controller.cms.CmsWoProvider.java
void addComponentConfig(CmsWorkOrder wo) { CmsRfcCI rfc = wo.getRfcCi();//from w ww. j av a 2 s. c om if (rfc.getCiClassName().matches(BOM_FQDN) && isTorbitService(rfc)) { String logKey = "Fqdn workorder " + wo.getDeploymentId() + ":" + rfc.getCiId() + ":: "; //send weights only when enabled if (isWeightsEnabled(wo.getRfcCi().getNsPath())) { logger.info(logKey + "finding weights for clouds"); List<CmsCIRelation> deployedToRelations = cmProcessor .getCIRelationsWithToCIAndNoAttrs(rfc.getNsPath(), DEPLOYED_TO, null, "Compute", null); Set<String> clouds = getPrimaryClouds(wo); logger.info(logKey + "primary clouds " + clouds); Map<String, Long> cloudInstancesMap = deployedToRelations.stream() .filter(r -> (r.getToCi() != null) && clouds.contains(r.getToCi().getCiName())) .collect(groupingBy(r -> r.getToCi().getCiName(), counting())); if (cloudInstancesMap.isEmpty()) { logger.info(logKey + "no active cloud compute instance found"); return; } Long totalComputes = 0L; List<CloudWeight> cloudWeights = new ArrayList<>(); for (Entry<String, Long> entry : cloudInstancesMap.entrySet()) { totalComputes = totalComputes + entry.getValue(); cloudWeights.add(new CloudWeight(entry.getKey(), entry.getValue())); } logger.info(logKey + "total active computes " + totalComputes); cloudWeights.sort((c1, c2) -> Long.compare(c2.computes, c1.computes)); if (totalComputes > 0) { int totalPercent = 0; for (CloudWeight cloudWeight : cloudWeights) { cloudWeight.weight = (int) ((cloudWeight.computes * 100.0) / totalComputes); totalPercent += cloudWeight.weight; } //bring the total percent to 100 int remainingPercent = 100 - totalPercent; for (int i = 0; i < remainingPercent; i++) { cloudWeights.get(i).weight++; } Map<String, String> config = configMap(wo); Map<String, Integer> weights = cloudWeights.stream() .collect(Collectors.toMap(c -> c.name, c -> c.weight)); logger.info(logKey + "weight map " + weights); config.put("weights", gson.toJson(weights)); } } else { logger.info(logKey + "not using weights for gslb. gslb weights not enabled."); } } }
From source file:org.elasticsearch.client.RestClient.java
/** * Returns an {@link Iterable} of hosts to be used for a request call. * Ideally, the first host is retrieved from the iterable and used successfully for the request. * Otherwise, after each failure the next host has to be retrieved from the iterator so that the request can be retried until * there are no more hosts available to retry against. The maximum total of attempts is equal to the number of hosts in the iterable. * The iterator returned will never be empty. In case there are no healthy hosts available, or dead ones to be be retried, * one dead host gets returned so that it can be retried. *//*from w ww . j av a 2s. c o m*/ private HostTuple<Iterator<HttpHost>> nextHost() { final HostTuple<Set<HttpHost>> hostTuple = this.hostTuple; Collection<HttpHost> nextHosts = Collections.emptySet(); do { Set<HttpHost> filteredHosts = new HashSet<>(hostTuple.hosts); for (Map.Entry<HttpHost, DeadHostState> entry : blacklist.entrySet()) { if (System.nanoTime() - entry.getValue().getDeadUntilNanos() < 0) { filteredHosts.remove(entry.getKey()); } } if (filteredHosts.isEmpty()) { //last resort: if there are no good host to use, return a single dead one, the one that's closest to being retried List<Map.Entry<HttpHost, DeadHostState>> sortedHosts = new ArrayList<>(blacklist.entrySet()); if (sortedHosts.size() > 0) { Collections.sort(sortedHosts, new Comparator<Map.Entry<HttpHost, DeadHostState>>() { @Override public int compare(Map.Entry<HttpHost, DeadHostState> o1, Map.Entry<HttpHost, DeadHostState> o2) { return Long.compare(o1.getValue().getDeadUntilNanos(), o2.getValue().getDeadUntilNanos()); } }); HttpHost deadHost = sortedHosts.get(0).getKey(); logger.trace("resurrecting host [" + deadHost + "]"); nextHosts = Collections.singleton(deadHost); } } else { List<HttpHost> rotatedHosts = new ArrayList<>(filteredHosts); Collections.rotate(rotatedHosts, rotatedHosts.size() - lastHostIndex.getAndIncrement()); nextHosts = rotatedHosts; } } while (nextHosts.isEmpty()); return new HostTuple<>(nextHosts.iterator(), hostTuple.authCache); }
From source file:com.unboundid.scim2.common.utils.JsonUtils.java
/** * Compares two JsonNodes for order. Nodes containing datetime and numerical * values are ordered accordingly. Otherwise, the values' string * representation will be compared lexicographically. * * @param n1 the first node to be compared. * @param n2 the second node to be compared. * @param attributeDefinition The attribute definition of the attribute * whose values to compare or {@code null} to * compare string values using case insensitive * matching./*w w w. ja v a2 s. c o m*/ * @return a negative integer, zero, or a positive integer as the * first argument is less than, equal to, or greater than the second. */ public static int compareTo(final JsonNode n1, final JsonNode n2, final AttributeDefinition attributeDefinition) { if (n1.isTextual() && n2.isTextual()) { Date d1 = dateValue(n1); Date d2 = dateValue(n2); if (d1 != null && d2 != null) { return d1.compareTo(d2); } else { if (attributeDefinition != null && attributeDefinition.getType() == AttributeDefinition.Type.STRING && attributeDefinition.isCaseExact()) { return n1.textValue().compareTo(n2.textValue()); } return StaticUtils.toLowerCase(n1.textValue()).compareTo(StaticUtils.toLowerCase(n2.textValue())); } } if (n1.isNumber() && n2.isNumber()) { if (n1.isBigDecimal() || n2.isBigDecimal()) { return n1.decimalValue().compareTo(n2.decimalValue()); } if (n1.isFloatingPointNumber() || n2.isFloatingPointNumber()) { return Double.compare(n1.doubleValue(), n2.doubleValue()); } if (n1.isBigInteger() || n2.isBigInteger()) { return n1.bigIntegerValue().compareTo(n2.bigIntegerValue()); } return Long.compare(n1.longValue(), n2.longValue()); } // Compare everything else lexicographically return n1.asText().compareTo(n2.asText()); }
From source file:org.apache.solr.handler.component.QueryComponent.java
protected void doFieldSortValues(ResponseBuilder rb, SolrIndexSearcher searcher) throws IOException { SolrQueryRequest req = rb.req;/*from w w w .j a v a 2 s . c om*/ SolrQueryResponse rsp = rb.rsp; // The query cache doesn't currently store sort field values, and SolrIndexSearcher doesn't // currently have an option to return sort field values. Because of this, we // take the documents given and re-derive the sort values. // // TODO: See SOLR-5595 boolean fsv = req.getParams().getBool(ResponseBuilder.FIELD_SORT_VALUES, false); if (fsv) { NamedList<Object[]> sortVals = new NamedList<>(); // order is important for the sort fields IndexReaderContext topReaderContext = searcher.getTopReaderContext(); List<AtomicReaderContext> leaves = topReaderContext.leaves(); AtomicReaderContext currentLeaf = null; if (leaves.size() == 1) { // if there is a single segment, use that subReader and avoid looking up each time currentLeaf = leaves.get(0); leaves = null; } DocList docList = rb.getResults().docList; // sort ids from lowest to highest so we can access them in order int nDocs = docList.size(); final long[] sortedIds = new long[nDocs]; final float[] scores = new float[nDocs]; // doc scores, parallel to sortedIds DocList docs = rb.getResults().docList; DocIterator it = docs.iterator(); for (int i = 0; i < nDocs; i++) { sortedIds[i] = (((long) it.nextDoc()) << 32) | i; scores[i] = docs.hasScores() ? it.score() : Float.NaN; } // sort ids and scores together new InPlaceMergeSorter() { @Override protected void swap(int i, int j) { long tmpId = sortedIds[i]; float tmpScore = scores[i]; sortedIds[i] = sortedIds[j]; scores[i] = scores[j]; sortedIds[j] = tmpId; scores[j] = tmpScore; } @Override protected int compare(int i, int j) { return Long.compare(sortedIds[i], sortedIds[j]); } }.sort(0, sortedIds.length); SortSpec sortSpec = rb.getSortSpec(); Sort sort = searcher.weightSort(sortSpec.getSort()); SortField[] sortFields = sort == null ? new SortField[] { SortField.FIELD_SCORE } : sort.getSort(); List<SchemaField> schemaFields = sortSpec.getSchemaFields(); for (int fld = 0; fld < schemaFields.size(); fld++) { SchemaField schemaField = schemaFields.get(fld); FieldType ft = null == schemaField ? null : schemaField.getType(); SortField sortField = sortFields[fld]; SortField.Type type = sortField.getType(); // :TODO: would be simpler to always serialize every position of SortField[] if (type == SortField.Type.SCORE || type == SortField.Type.DOC) continue; FieldComparator comparator = null; Object[] vals = new Object[nDocs]; int lastIdx = -1; int idx = 0; for (int i = 0; i < sortedIds.length; ++i) { long idAndPos = sortedIds[i]; float score = scores[i]; int doc = (int) (idAndPos >>> 32); int position = (int) idAndPos; if (leaves != null) { idx = ReaderUtil.subIndex(doc, leaves); currentLeaf = leaves.get(idx); if (idx != lastIdx) { // we switched segments. invalidate comparator. comparator = null; } } if (comparator == null) { comparator = sortField.getComparator(1, 0); comparator = comparator.setNextReader(currentLeaf); } doc -= currentLeaf.docBase; // adjust for what segment this is in comparator.setScorer(new FakeScorer(doc, score)); comparator.copy(0, doc); Object val = comparator.value(0); if (null != ft) val = ft.marshalSortValue(val); vals[position] = val; } sortVals.add(sortField.getField(), vals); } rsp.add("sort_values", sortVals); } }
From source file:com.farmerbb.taskbar.service.TaskbarService.java
@SuppressWarnings("Convert2streamapi") @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1) private void updateRecentApps(final boolean firstRefresh) { SharedPreferences pref = U.getSharedPreferences(this); final PackageManager pm = getPackageManager(); final List<AppEntry> entries = new ArrayList<>(); List<LauncherActivityInfo> launcherAppCache = new ArrayList<>(); int maxNumOfEntries = U.getMaxNumOfEntries(this); int realNumOfPinnedApps = 0; boolean fullLength = pref.getBoolean("full_length", false); PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this); List<AppEntry> pinnedApps = pba.getPinnedApps(); List<AppEntry> blockedApps = pba.getBlockedApps(); List<String> applicationIdsToRemove = new ArrayList<>(); // Filter out anything on the pinned/blocked apps lists if (pinnedApps.size() > 0) { UserManager userManager = (UserManager) getSystemService(USER_SERVICE); LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE); for (AppEntry entry : pinnedApps) { boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(), userManager.getUserForSerialNumber(entry.getUserId(this))); if (packageEnabled) entries.add(entry);//from w w w . j av a 2 s.co m else realNumOfPinnedApps--; applicationIdsToRemove.add(entry.getPackageName()); } realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size(); } if (blockedApps.size() > 0) { for (AppEntry entry : blockedApps) { applicationIdsToRemove.add(entry.getPackageName()); } } // Get list of all recently used apps List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>(); if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) { if (realNumOfPinnedApps < maxNumOfEntries) { List<AppEntry> usageStatsList2 = new ArrayList<>(); List<AppEntry> usageStatsList3 = new ArrayList<>(); List<AppEntry> usageStatsList4 = new ArrayList<>(); List<AppEntry> usageStatsList5 = new ArrayList<>(); List<AppEntry> usageStatsList6; Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory(Intent.CATEGORY_HOME); ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY); // Filter out apps without a launcher intent // Also filter out the current launcher, and Taskbar itself for (AppEntry packageInfo : usageStatsList) { if (hasLauncherIntent(packageInfo.getPackageName()) && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID) && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName)) usageStatsList2.add(packageInfo); } // Filter out apps that don't fall within our current search interval for (AppEntry stats : usageStatsList2) { if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly) usageStatsList3.add(stats); } // Sort apps by either most recently used, or most time used if (!runningAppsOnly) { if (sortOrder.contains("most_used")) { Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(), us1.getTotalTimeInForeground())); } else { Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed())); } } // Filter out any duplicate entries List<String> applicationIds = new ArrayList<>(); for (AppEntry stats : usageStatsList3) { if (!applicationIds.contains(stats.getPackageName())) { usageStatsList4.add(stats); applicationIds.add(stats.getPackageName()); } } // Filter out the currently running foreground app, if requested by the user if (pref.getBoolean("hide_foreground", false)) { UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService( USAGE_STATS_SERVICE); UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis()); UsageEvents.Event eventCache = new UsageEvents.Event(); String currentForegroundApp = null; while (events.hasNextEvent()) { events.getNextEvent(eventCache); if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) { if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID) && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName()) && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName()) && !eventCache.getClassName() .equals(InvisibleActivityFreeform.class.getCanonicalName()))) currentForegroundApp = eventCache.getPackageName(); } } if (!applicationIdsToRemove.contains(currentForegroundApp)) applicationIdsToRemove.add(currentForegroundApp); } for (AppEntry stats : usageStatsList4) { if (!applicationIdsToRemove.contains(stats.getPackageName())) { usageStatsList5.add(stats); } } // Truncate list to a maximum length if (usageStatsList5.size() > maxNumOfEntries) usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries); else usageStatsList6 = usageStatsList5; // Determine if we need to reverse the order boolean needToReverseOrder; switch (U.getTaskbarPosition(this)) { case "bottom_right": case "top_right": needToReverseOrder = sortOrder.contains("false"); break; default: needToReverseOrder = sortOrder.contains("true"); break; } if (needToReverseOrder) { Collections.reverse(usageStatsList6); } // Generate the AppEntries for TaskbarAdapter int number = usageStatsList6.size() == maxNumOfEntries ? usageStatsList6.size() - realNumOfPinnedApps : usageStatsList6.size(); UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE); LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE); final List<UserHandle> userHandles = userManager.getUserProfiles(); for (int i = 0; i < number; i++) { for (UserHandle handle : userHandles) { String packageName = usageStatsList6.get(i).getPackageName(); List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle); if (!list.isEmpty()) { // Google App workaround if (!packageName.equals("com.google.android.googlequicksearchbox")) launcherAppCache.add(list.get(0)); else { boolean added = false; for (LauncherActivityInfo info : list) { if (info.getName() .equals("com.google.android.googlequicksearchbox.SearchActivity")) { launcherAppCache.add(info); added = true; } } if (!added) launcherAppCache.add(list.get(0)); } AppEntry newEntry = new AppEntry(packageName, null, null, null, false); newEntry.setUserId(userManager.getSerialNumberForUser(handle)); entries.add(newEntry); break; } } } } while (entries.size() > maxNumOfEntries) { try { entries.remove(entries.size() - 1); launcherAppCache.remove(launcherAppCache.size() - 1); } catch (ArrayIndexOutOfBoundsException e) { /* Gracefully fail */ } } // Determine if we need to reverse the order again if (U.getTaskbarPosition(this).contains("vertical")) { Collections.reverse(entries); Collections.reverse(launcherAppCache); } // Now that we've generated the list of apps, // we need to determine if we need to redraw the Taskbar or not boolean shouldRedrawTaskbar = firstRefresh; List<String> finalApplicationIds = new ArrayList<>(); for (AppEntry entry : entries) { finalApplicationIds.add(entry.getPackageName()); } if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps) shouldRedrawTaskbar = true; else { for (int i = 0; i < finalApplicationIds.size(); i++) { if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) { shouldRedrawTaskbar = true; break; } } } if (shouldRedrawTaskbar) { currentTaskbarIds = finalApplicationIds; numOfPinnedApps = realNumOfPinnedApps; UserManager userManager = (UserManager) getSystemService(USER_SERVICE); int launcherAppCachePos = -1; for (int i = 0; i < entries.size(); i++) { if (entries.get(i).getComponentName() == null) { launcherAppCachePos++; LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos); String packageName = entries.get(i).getPackageName(); entries.remove(i); AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(), appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this) .getIcon(TaskbarService.this, pm, appInfo), false); newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser())); entries.add(i, newEntry); } } final int numOfEntries = Math.min(entries.size(), maxNumOfEntries); handler.post(() -> { if (numOfEntries > 0 || fullLength) { ViewGroup.LayoutParams params = scrollView.getLayoutParams(); DisplayMetrics metrics = getResources().getDisplayMetrics(); int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries; float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize; if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) { int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this) - U.getBaseTaskbarSize(TaskbarService.this); params.height = (int) Math.min(maxRecentsSize, maxScreenSize) + getResources().getDimensionPixelSize(R.dimen.divider_size); if (fullLength && U.getTaskbarPosition(this).contains("bottom")) { try { Space whitespace = (Space) layout.findViewById(R.id.whitespace); ViewGroup.LayoutParams params2 = whitespace.getLayoutParams(); params2.height = maxScreenSize - recentsSize; whitespace.setLayoutParams(params2); } catch (NullPointerException e) { /* Gracefully fail */ } } } else { int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this); params.width = (int) Math.min(maxRecentsSize, maxScreenSize) + getResources().getDimensionPixelSize(R.dimen.divider_size); if (fullLength && U.getTaskbarPosition(this).contains("right")) { try { Space whitespace = (Space) layout.findViewById(R.id.whitespace); ViewGroup.LayoutParams params2 = whitespace.getLayoutParams(); params2.width = maxScreenSize - recentsSize; whitespace.setLayoutParams(params2); } catch (NullPointerException e) { /* Gracefully fail */ } } } scrollView.setLayoutParams(params); taskbar.removeAllViews(); for (int i = 0; i < entries.size(); i++) { taskbar.addView(getView(entries, i)); } isShowingRecents = true; if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) { if (firstRefresh) scrollView.setVisibility(View.INVISIBLE); else scrollView.setVisibility(View.VISIBLE); } if (firstRefresh && scrollView.getVisibility() != View.VISIBLE) new Handler().post(() -> { switch (U.getTaskbarPosition(TaskbarService.this)) { case "bottom_left": case "bottom_right": case "top_left": case "top_right": if (sortOrder.contains("false")) scrollView.scrollTo(0, 0); else if (sortOrder.contains("true")) scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight()); break; case "bottom_vertical_left": case "bottom_vertical_right": case "top_vertical_left": case "top_vertical_right": if (sortOrder.contains("false")) scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight()); else if (sortOrder.contains("true")) scrollView.scrollTo(0, 0); break; } if (shouldRefreshRecents) { scrollView.setVisibility(View.VISIBLE); } }); } else { isShowingRecents = false; scrollView.setVisibility(View.GONE); } }); } } else if (firstRefresh || currentTaskbarIds.size() > 0) { currentTaskbarIds.clear(); handler.post(() -> { isShowingRecents = false; scrollView.setVisibility(View.GONE); }); } }
From source file:org.apache.storm.cluster.StormClusterStateImpl.java
@Override public void reportError(String stormId, String componentId, String node, Long port, Throwable error) { String path = ClusterUtils.errorPath(stormId, componentId); String lastErrorPath = ClusterUtils.lastErrorPath(stormId, componentId); ErrorInfo errorInfo = new ErrorInfo(ClusterUtils.stringifyError(error), Time.currentTimeSecs()); errorInfo.set_host(node);//ww w . j ava 2 s. c o m errorInfo.set_port(port.intValue()); byte[] serData = Utils.serialize(errorInfo); stateStorage.mkdirs(path, acls); stateStorage.create_sequential(path + ClusterUtils.ZK_SEPERATOR + "e", serData, acls); stateStorage.set_data(lastErrorPath, serData, acls); List<String> childrens = stateStorage.get_children(path, false); Collections.sort(childrens, new Comparator<String>() { public int compare(String arg0, String arg1) { return Long.compare(Long.parseLong(arg0.substring(1)), Long.parseLong(arg1.substring(1))); } }); while (childrens.size() > 10) { String znodePath = path + ClusterUtils.ZK_SEPERATOR + childrens.remove(0); try { stateStorage.delete_node(znodePath); } catch (Exception e) { if (Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) { // if the node is already deleted, do nothing LOG.warn("Could not find the znode: {}", znodePath); } else { throw e; } } } }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Creates the pairs that have a channel ID as a key, and list of descriptors as value. All the * descriptors in the list are associated with the channel, thus all the data described in the * descriptors can be retrieved with a single HTTP/local request. * /*from ww w . j av a2s . c o m*/ * @param descriptors * Un-grouped descriptors. * * @return Map of channel IDs with its descriptors. */ private Map<Integer, List<IStorageDescriptor>> createFilesGroup(List<IStorageDescriptor> descriptors) { Map<Integer, List<IStorageDescriptor>> filesMap = new HashMap<Integer, List<IStorageDescriptor>>(); for (IStorageDescriptor storageDescriptor : descriptors) { Integer channelId = Integer.valueOf(storageDescriptor.getChannelId()); List<IStorageDescriptor> oneFileList = filesMap.get(channelId); if (null == oneFileList) { oneFileList = new ArrayList<IStorageDescriptor>(); filesMap.put(channelId, oneFileList); } oneFileList.add(storageDescriptor); } // sort lists for (Map.Entry<Integer, List<IStorageDescriptor>> entry : filesMap.entrySet()) { List<IStorageDescriptor> list = entry.getValue(); Collections.sort(list, new Comparator<IStorageDescriptor>() { @Override public int compare(IStorageDescriptor o1, IStorageDescriptor o2) { return Long.compare(o1.getPosition(), o2.getPosition()); } }); } return filesMap; }
From source file:rocks.inspectit.ui.rcp.storage.util.DataRetriever.java
/** * Creates the pairs that have a channel ID as a key, and list of descriptors as value. All the * descriptors in the list are associated with the channel, thus all the data described in the * descriptors can be retrieved with a single HTTP/local request. * * @param descriptors// w ww . j a va 2 s .c o m * Un-grouped descriptors. * * @return Map of channel IDs with its descriptors. */ private Map<Integer, List<IStorageDescriptor>> createFilesGroup(List<IStorageDescriptor> descriptors) { Map<Integer, List<IStorageDescriptor>> filesMap = new HashMap<>(); for (IStorageDescriptor storageDescriptor : descriptors) { Integer channelId = Integer.valueOf(storageDescriptor.getChannelId()); List<IStorageDescriptor> oneFileList = filesMap.get(channelId); if (null == oneFileList) { oneFileList = new ArrayList<>(); filesMap.put(channelId, oneFileList); } oneFileList.add(storageDescriptor); } // sort lists for (Map.Entry<Integer, List<IStorageDescriptor>> entry : filesMap.entrySet()) { List<IStorageDescriptor> list = entry.getValue(); Collections.sort(list, new Comparator<IStorageDescriptor>() { @Override public int compare(IStorageDescriptor o1, IStorageDescriptor o2) { return Long.compare(o1.getPosition(), o2.getPosition()); } }); } return filesMap; }
From source file:org.apache.hadoop.hbase.procedure2.Procedure.java
@Override public int compareTo(final Procedure<TEnvironment> other) { return Long.compare(getProcId(), other.getProcId()); }