List of usage examples for java.util Collections reverse
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void reverse(List<?> list)
This method runs in linear time.
From source file:com.citytechinc.cq.component.dialog.util.DialogUtil.java
public static DialogFieldConfig getDialogFieldFromSuperClasses(CtMethod method) throws NotFoundException, ClassNotFoundException, InvalidComponentClassException { DialogFieldConfig dialogFieldConfig = null; List<CtClass> classes = new ArrayList<CtClass>(); CtClass clazz = method.getDeclaringClass(); classes.add(clazz);//from w w w.j av a 2 s .co m while (clazz.getSuperclass() != null) { classes.add(clazz.getSuperclass()); clazz = clazz.getSuperclass(); } Collections.reverse(classes); CtMember interfaceMember = getMemberForAnnotatedInterfaceMethod(method); if (interfaceMember != null) { dialogFieldConfig = new DialogFieldConfig( (DialogField) interfaceMember.getAnnotation(DialogField.class), interfaceMember); } for (CtClass ctclass : classes) { try { CtMethod superClassMethod = ctclass.getDeclaredMethod(method.getName(), method.getParameterTypes()); if (superClassMethod.hasAnnotation(DialogField.class)) { dialogFieldConfig = new DialogFieldConfig( (DialogField) superClassMethod.getAnnotation(DialogField.class), superClassMethod); } else if (superClassMethod.hasAnnotation(DialogFieldOverride.class)) { mergeDialogFields(dialogFieldConfig, superClassMethod); } } catch (NotFoundException e) { } } return dialogFieldConfig; }
From source file:com.streamsets.datacollector.execution.store.FilePipelineStateStore.java
@Override public List<PipelineState> getHistory(String pipelineName, String rev, boolean fromBeginning) throws PipelineStoreException { if (!pipelineDirExists(pipelineName, rev) || !pipelineStateHistoryFileExists(pipelineName, rev)) { return Collections.emptyList(); }//from w ww .j a v a2 s . c o m try (Reader reader = new FileReader(getPipelineStateHistoryFile(pipelineName, rev))) { ObjectMapper objectMapper = ObjectMapperFactory.get(); JsonParser jsonParser = objectMapper.getFactory().createParser(reader); MappingIterator<PipelineStateJson> pipelineStateMappingIterator = objectMapper.readValues(jsonParser, PipelineStateJson.class); List<PipelineStateJson> pipelineStateJsons = pipelineStateMappingIterator.readAll(); Collections.reverse(pipelineStateJsons); if (fromBeginning) { return BeanHelper.unwrapPipelineStatesNewAPI(pipelineStateJsons); } else { int toIndex = pipelineStateJsons.size() > 100 ? 100 : pipelineStateJsons.size(); return BeanHelper.unwrapPipelineStatesNewAPI(pipelineStateJsons.subList(0, toIndex)); } } catch (IOException e) { throw new PipelineStoreException(ContainerError.CONTAINER_0115, pipelineName, rev, e.toString(), e); } }
From source file:burstcoin.observer.service.NetworkService.java
private void processMiningInfoLookup(Map<String, MiningInfo> miningInfoLookup) { List<NetworkBean> networkBeans = new ArrayList<>(); for (Map.Entry<String, MiningInfo> entry : miningInfoLookup.entrySet()) { MiningInfo miningInfo = entry.getValue(); String https = entry.getKey().contains("https://") ? "Yes" : "No"; String domain = entry.getKey().replace("http://", "").replace("https://", ""); if (miningInfo != null && miningInfo.getGenerationSignature() != null) { networkBeans.add(new NetworkBean(String.valueOf(miningInfo.getHeight()), domain, entry.getKey(), miningInfo.getBaseTarget(), miningInfo.getGenerationSignature().substring(0, 25) + "...", String.valueOf(miningInfo.getTargetDeadline()), https)); } else {//from w w w.j a v a 2s .c o m networkBeans.add(new NetworkBean(domain)); } } Collections.sort(networkBeans, new Comparator<NetworkBean>() { @Override public int compare(NetworkBean o1, NetworkBean o2) { return o1.getBaseTarget().compareTo(o2.getBaseTarget()); } }); Collections.sort(networkBeans, new Comparator<NetworkBean>() { @Override public int compare(NetworkBean o1, NetworkBean o2) { return o1.getType().compareTo(o2.getType()); } }); Collections.sort(networkBeans, new Comparator<NetworkBean>() { @Override public int compare(NetworkBean o1, NetworkBean o2) { return o2.getHeight().compareTo(o1.getHeight()); } }); // update genSig Lookup int numberOfNotAvailableDomains = 0; for (NetworkBean networkBean : networkBeans) { if (networkBean.getAvailable()) { Long height = Long.valueOf(networkBean.getHeight()); if (!genSigLookup.containsKey(height)) { genSigLookup.put(height, new HashMap<>()); } Map<String, Set<String>> subMap = genSigLookup.get(height); if (!subMap.containsKey(networkBean.getGenerationSignature())) { subMap.put(networkBean.getGenerationSignature(), new HashSet<>()); } Set<String> domains = subMap.get(networkBean.getGenerationSignature()); domains.add(networkBean.getDomain()); } else { // N/A numberOfNotAvailableDomains++; } } List<Long> order = new ArrayList<>(genSigLookup.keySet()); Collections.sort(order); Collections.reverse(order); Iterator<Long> iterator = order.iterator(); Long lastBlockWithSameGenSig = null; while (iterator.hasNext() && lastBlockWithSameGenSig == null) { Long nextHeight = iterator.next(); if (genSigLookup.get(nextHeight).size() == 1) // only one known genSig for height { // number of domains with same genSig = all domains without N/A if (networkBeans.size() - numberOfNotAvailableDomains == genSigLookup.get(nextHeight).values() .iterator().next().size()) { lastBlockWithSameGenSig = nextHeight; } } } long maxHeight = 0; for (NetworkBean networkBean : networkBeans) { if (networkBean.getAvailable()) { maxHeight = Math.max(Long.valueOf(networkBean.getHeight()), maxHeight); } } boolean appStartedAfterForkHappened = lastBlockWithSameGenSig == null; boolean sendMail = false; for (NetworkBean networkBean : networkBeans) { if (networkBean.getAvailable()) { Long height = Long.valueOf(networkBean.getHeight()); Set<String> domainsWithSameGenSigForBlock = genSigLookup.get(height) .get(networkBean.getGenerationSignature()); if (genSigLookup.get(height).size() > 1 && domainsWithSameGenSigForBlock .size() < (networkBeans.size() - numberOfNotAvailableDomains) / 2) { networkBean.setState(NetworkState.FORKED); sendMail = true; } if (height + 4 < maxHeight) // when the wallet is 4 blocks behind -> stuck { if (!networkBean.getState().equals(NetworkState.FORKED)) // if it's forked, then ignore the stuck-check, because forks may also be behind { networkBean.setState(NetworkState.STUCK); if (ObserverProperties.isEnableStuckNotify() && (!previousStateLookup .containsKey(networkBean.getDomain()) || !previousStateLookup.get(networkBean.getDomain()).equals(NetworkState.STUCK))) //send only once { sendMessage("Burstcoin-Observer - Stuck at block: " + networkBean.getHeight(), networkBean.getDomain() + "\r\n" + "Please check: " + ObserverProperties.getObserverUrl()); } } } } } if (sendMail && !forkMailSend) { if (ObserverProperties.isEnableForkNotify() && (appStartedAfterForkHappened || (lastBlockWithSameGenSigMailSend != null && !lastBlockWithSameGenSig.equals(lastBlockWithSameGenSigMailSend)))) { forkMailSend = true; // ensure only one mail send per lastBlockWithSameGenSig e.g. if forked wallet pops off blocks over and over again lastBlockWithSameGenSigMailSend = lastBlockWithSameGenSig; sendMessage("Burstcoin-Observer - Fork after block: " + lastBlockWithSameGenSig, "Please check: " + ObserverProperties.getObserverUrl()); } } else if (!sendMail && !appStartedAfterForkHappened) { forkMailSend = false; } // store the network state for next check-loop for (NetworkBean networkBean : networkBeans) { if (networkBean.getAvailable() && networkBean.getDomain() != null) { previousStateLookup.put(networkBean.getDomain(), networkBean.getState()); } } publisher.publishEvent( new NetworkUpdateEvent(networkBeans, lastBlockWithSameGenSig, createSenkeyChartData())); }
From source file:com.smartitengineering.events.async.api.impl.hub.EventSubscriberImpl.java
private boolean processFeed(ChannelEventsResource resource, boolean traverseOlder) { if (logger.isDebugEnabled()) { logger.debug("RESOURCE being processed is " + resource.getUri().toASCIIString()); }//from w w w . j a v a 2 s . com final Feed lastReadStateOfEntity = resource.getLastReadStateOfEntity(); final List<Entry> entries = lastReadStateOfEntity == null ? Collections.<Entry>emptyList() : lastReadStateOfEntity.getEntries(); if (traverseOlder) { if (entries != null && !entries.isEmpty()) { final ChannelEventsResource next = resource.next(); if (next != null) { boolean processOldEvents = processFeed(next, traverseOlder); if (!processOldEvents) { logger.warn("Error processing older events thus returning"); return processOldEvents; } } } } if (entries == null || entries.isEmpty()) { storer.storeNextUri(resource.getUri().toASCIIString()); return true; } List<HubEvent> events = new ArrayList<HubEvent>(); for (Entry entry : entries) { Link altLink = entry.getAlternateLink(); final HubEvent event = new EventResource(resource, AtomClientUtil.convertFromAtomLinkToResourceLink(altLink), factory).getLastReadStateOfEntity(); events.add(event); } //Reverse it to get the older event first Collections.reverse(events); if (events.size() > 0 && integer.get() == 0) { for (final EventConsumer consumer : consumers) { consumer.startConsumption(); } } integer.addAndGet(events.size()); for (HubEvent event : events) { for (final EventConsumer consumer : consumers) { try { consumer.consume(event.getContentType(), event.getContentAsString()); } catch (Exception ex) { logger.warn("Consumer threw exception to halt subscription", ex); final String resourceUri = resource.getUri().toASCIIString(); if (logger.isInfoEnabled()) { logger.info(new StringBuilder("Will retry this resource again ").append(resourceUri) .toString()); } storer.storeNextUri(resourceUri); return false; } } } final ChannelEventsResource previous = resource.previous(); if (previous != null) { return processFeed(previous, false); } else { return true; } }
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
public ArrayList<ShortFeedItem> getShortItems(int feedTypes, String query) { String[] terms = query.split("\\s"); ArrayList<ShortFeedItem> result = new ArrayList<ShortFeedItem>(); ArrayList<Feed> feeds = mDB.getFeeds(feedTypes); for (Feed feed : feeds) { ArrayList<ShortFeedItem> items = mDB.getShortFeedItems(feed.mId, terms, false); result.addAll(items);// w w w .j a va 2s . c om } Collections.sort(result); Collections.reverse(result); return result; }
From source file:com.axelor.studio.service.data.exporter.ExporterService.java
private void updateMenuPath(MetaMenu metaMenu) { List<String> menus = new ArrayList<String>(); menus.add(metaMenu.getTitle());/*from ww w . j av a 2 s .co m*/ addParentMenus(menus, metaMenu); Collections.reverse(menus); boolean first = true; for (String mn : menus) { String mnFR = translationService.getTranslation(mn, "fr"); if (Strings.isNullOrEmpty(mnFR)) { mnFR = mn; } if (first) { menuPath = mn; menuPathFR = mnFR; } else { menuPath += "/" + mn; menuPathFR += "/" + mnFR; } first = false; } }
From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.CartPageController.java
protected void reverseCartProductsOrder(final List<OrderEntryData> entries) { if (entries != null) { Collections.reverse(entries); }/*from w w w . ja v a 2 s. co m*/ }
From source file:burstcoin.observer.service.AssetService.java
private void startCheckAssetsTask() { timer.schedule(new TimerTask() { @Override/* w w w. ja v a 2s .c o m*/ public void run() { try { LOG.info("START import asset data from " + ObserverProperties.getWalletUrl()); Map<String, Asset> assetLookup = createAssetLookup(); Map<OrderType, Map<Asset, List<Order>>> orderLookup = createOrderLookup(assetLookup); Map<Asset, List<Trade>> tradeLookup = getTradeLookup(assetLookup); State state = getState(); LOG.info("FINISH import asset data!"); List<AssetBean> assetBeans = new ArrayList<>(); List<AssetCandleStickBean> assetCandleStickBeans = new ArrayList<>(); for (Asset asset : assetLookup.values()) { List<List> candleStickData = new ArrayList<List>(); long volume7Days = 0L; long volume30Days = 0L; String lastPrice = ""; List<Trade> trades = tradeLookup.get(asset); if (trades != null && !trades.isEmpty()) { Iterator<Trade> iterator = trades.iterator(); boolean withinLast30Days = true; while (withinLast30Days && iterator.hasNext()) { Trade trade = iterator.next(); if (StringUtils.isEmpty(lastPrice)) { lastPrice = convertPrice(trade.getPriceNQT(), trade.getDecimals()); } Integer bidOrderBlock = Integer.valueOf(trade.getBidOrderHeight()); Integer askOrderBlock = Integer.valueOf(trade.getAskOrderHeight()); int block = bidOrderBlock >= askOrderBlock ? bidOrderBlock : askOrderBlock; withinLast30Days = state.getNumberOfBlocks() - 360 * 30 < block; if (withinLast30Days) { long volume = Long.valueOf(trade.getPriceNQT()) * Long.valueOf(trade.getQuantityQNT()); volume30Days += volume; if (state.getNumberOfBlocks() - 360 * 7 < block) { volume7Days += volume; } } } Long currentBlockHeight = Long.valueOf(state.getNumberOfBlocks()); for (int i = 1; i <= 60 /*days*/; i++) { List<Trade> tradesOfDay = new ArrayList<Trade>(); for (Trade trade : trades) { if (trade.getHeight() > currentBlockHeight - (360 * (i + 1)) && trade.getHeight() < currentBlockHeight - (360 * i)) { tradesOfDay.add(trade); } } Double min = null; Double max = null; Double first = null; Double last = null; for (Trade trade : tradesOfDay) { double price = Double .valueOf(convertPrice(trade.getPriceNQT(), trade.getDecimals())); if (first == null) { first = price; } if (min == null || price < min) { min = price; } if (max == null || price > max) { max = price; } if (tradesOfDay.indexOf(trade) == tradesOfDay.size() - 1) { last = price; } } if (min != null && max != null && first != null && last != null) { List x = Arrays.asList("" + i, min, first, last, max); candleStickData.add(x); } else { candleStickData.add(Arrays.asList("" + i, null, null, null, null)); } } } Collections.reverse(candleStickData); List<Order> sellOrders = orderLookup.get(OrderType.ASK).get(asset) != null ? orderLookup.get(OrderType.ASK).get(asset) : new ArrayList<>(); List<Order> buyOrders = orderLookup.get(OrderType.BID).get(asset) != null ? orderLookup.get(OrderType.BID).get(asset) : new ArrayList<>(); if (!(buyOrders.isEmpty() && sellOrders.isEmpty() && asset.getNumberOfTrades() < 2)) { assetBeans.add(new AssetBean(asset.getAsset(), asset.getName(), asset.getDescription(), asset.getAccountRS(), asset.getAccount(), asset.getQuantityQNT(), asset.getDecimals(), asset.getNumberOfAccounts(), asset.getNumberOfTransfers(), asset.getNumberOfTrades(), buyOrders.size(), sellOrders.size(), formatAmountNQT(volume7Days, 8), formatAmountNQT(volume30Days, 8), lastPrice)); assetCandleStickBeans.add(new AssetCandleStickBean(asset.getAsset(), candleStickData)); } } Collections.sort(assetBeans, new Comparator<AssetBean>() { @Override public int compare(AssetBean o1, AssetBean o2) { return Long.valueOf(o2.getVolume30Days()).compareTo(Long.valueOf(o1.getVolume30Days())); } }); Collections.sort(assetBeans, new Comparator<AssetBean>() { @Override public int compare(AssetBean o1, AssetBean o2) { return Long.valueOf(o2.getVolume7Days()).compareTo(Long.valueOf(o1.getVolume7Days())); } }); // delete data of candleStick for all after index 24 todo remove as soon ui has show/hide charts per asset List<String> assetOrder = new ArrayList<String>(); for (AssetBean assetBean : assetBeans) { assetOrder.add(assetBean.getAsset()); } assetCandleStickBeans.sort(new Comparator<AssetCandleStickBean>() { @Override public int compare(AssetCandleStickBean o1, AssetCandleStickBean o2) { return ((Integer) assetOrder.indexOf(o1.getAsset())) .compareTo(assetOrder.indexOf(o2.getAsset())); } }); publisher.publishEvent(new AssetUpdateEvent(assetBeans, assetCandleStickBeans)); } catch (Exception e) { LOG.error("Failed update assets!", e); } } }, 200, ObserverProperties.getAssetRefreshInterval()); }
From source file:es.pode.catalogadorWeb.presentacion.taxonomias.TaxonomiasControllerImpl.java
/** * @see es.pode.catalogadorBasico.presentacion.taxonomias.TaxonomiasController#consultaTaxId(org.apache.struts.action.ActionMapping, * es.pode.catalogadorBasico.presentacion.taxonomias.ConsultaTaxIdForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *///from www . ja va 2s. c o m public final void consultaTaxId(ActionMapping mapping, es.pode.catalogadorWeb.presentacion.taxonomias.ConsultaTaxIdForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { //Recogemos el idioma del navegador String idioma = ((Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)) .getLanguage(); InputStream iss = null; boolean bandera = false; String ficheroProperties = "/catalogadorBasico.properties"; iss = this.getClass().getResourceAsStream(ficheroProperties); Properties fprop = new Properties(); fprop.load(iss); String nomTaxonomia = request.getParameter("nomTaxonomia"); String id = request.getParameter("id"); String vocabName = request.getParameter("vocabName"); if (form.getIdioma() != null && !form.getIdioma().equals("")) idioma = form.getIdioma(); form.setIdioma(idioma); form.setNomTaxonomia(nomTaxonomia); form.setId(id); form.setVocabName(vocabName); TaxonVO[] taxVO = this.getSrvTaxonomiaService().obtenerNodos(id, nomTaxonomia, idioma); form.setTaxonesvoAsArray(taxVO); List rutaPadrevo = Arrays .asList(this.getSrvTaxonomiaService().obtenerTaxonPath(id, nomTaxonomia, idioma)); Collections.reverse(rutaPadrevo); form.setRutaPadrevo(rutaPadrevo); } catch (org.acegisecurity.AccessDeniedException ad) { logger.error("Error de Acceso " + ad); throw new java.lang.Exception("taxonomias", ad); } catch (Exception e) { logger.error("Error en catalogadorWeb, Taxonomias, metodo consultaTaxId " + e); throw new java.lang.Exception("taxonomias", e); } }
From source file:com.vmware.appfactory.application.controller.AppController.java
/** * Display application related data in detail. * Fetch application details, associated recipe info if recipeId is passed. * It also fetches the entities required for capturing a build. * * @param request - a HttpServlet request. * @param appId - an valid application id. * @param recipeId - a valid recipe id/*from w ww .j ava 2s. c o m*/ * @param locale * @return * @throws Exception */ @RequestMapping(value = "/apps/detail/{appId}", method = RequestMethod.GET) public ModelAndView detail(HttpServletRequest request, @PathVariable Long appId, @RequestParam(required = false) Long recipeId, @RequestParam(required = false) String selectionData, Locale locale) throws Exception { Application app = _daoFactory.getApplicationDao().find(appId); if (app == null) { throw new AfNotFoundException("No such application " + appId); } Recipe recipe = null; long otherRecipeCount = _daoFactory.getRecipeDao().countAll(); if (recipeId != null) { recipe = _daoFactory.getRecipeDao().find(recipeId); } // Subtract 1 from otherRecipeCount coz we have a valid recipe. if (recipe != null) { otherRecipeCount--; } // Find other versions of apps with the same name. List<Application> otherVersions = _daoFactory.getApplicationDao().findOtherVersionsIncluded(app); Application newerApp = null; if (CollectionUtils.isNotEmpty(otherVersions)) { // Sort by name, version, ... and get the most recent version to the top. Collections.sort(otherVersions); Collections.reverse(otherVersions); newerApp = findNewerVersionApp(app, otherVersions); } ModelMap mm = getBaseModel(request, locale, "T.APPS"); mm.put("app", app); mm.put("icons", AfJson.ObjectMapper().writeValueAsString(app.getIcons())); mm.put("recipe", recipe); mm.put("otherRecipeCount", otherRecipeCount); mm.put("newerApp", newerApp); mm.put("appVersions", otherVersions); // Additionally load the build components and set any defaults if they were set. loadBuildComponentsAndSetDefault(mm, selectionData); return new ModelAndView("apps/app-detail", mm); }