Example usage for java.util Collections reverse

List of usage examples for java.util Collections reverse

Introduction

In this page you can find the example usage for java.util Collections reverse.

Prototype

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void reverse(List<?> list) 

Source Link

Document

Reverses the order of the elements in the specified list.

This method runs in linear time.

Usage

From source file:com.taobao.itest.core.TestContextManager.java

private List<TestListener> getReversedTestListeners() {
    List<TestListener> listenersReversed = new ArrayList<TestListener>(getTestListeners());
    Collections.reverse(listenersReversed);
    return listenersReversed;
}

From source file:de.codesourcery.jasm16.ast.ASTUtils.java

public static Iterator<ASTNode> createInOrderIterator(ASTNode node) {
    if (node == null) {
        throw new IllegalArgumentException("node must not be NULL");
    }/*from  w w w.  j  av  a2s .co  m*/
    final Stack<ASTNode> stack = new Stack<ASTNode>();
    stack.push(node);
    return new Iterator<ASTNode>() {

        @Override
        public boolean hasNext() {
            return !stack.isEmpty();
        }

        /*    A (1)
         *    |\
         *(5) E B (2)
         *    |\ 
         *(4) D C (3)
         */
        @Override
        public ASTNode next() {
            if (stack.isEmpty()) {
                throw new NoSuchElementException();
            }
            ASTNode result = stack.pop();

            final List<ASTNode> children = result.getChildren();
            Collections.reverse(children);

            for (ASTNode child : children) {
                stack.push(child);
            }
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.ichi2.libanki.Finder.java

private List<Long> _findCards(String query, Object _order) {
    String[] tokens = _tokenize(query);
    Pair<String, String[]> res1 = _where(tokens);
    String preds = res1.first;/*  w  w w  .j  a v a2  s.com*/
    String[] args = res1.second;
    List<Long> res = new ArrayList<Long>();
    if (preds == null) {
        return res;
    }
    Pair<String, Boolean> res2 = _order instanceof Boolean ? _order((Boolean) _order) : _order((String) _order);
    String order = res2.first;
    boolean rev = res2.second;
    String sql = _query(preds, order);
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase().rawQuery(sql, args);
        while (cur.moveToNext()) {
            res.add(cur.getLong(0));
        }
    } catch (SQLException e) {
        // invalid grouping
        return new ArrayList<Long>();
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (rev) {
        Collections.reverse(res);
    }
    return res;
}

From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG
    Date,Open,High,Low,Close,Volume,Adj Close
    2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30
    2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00
    *//* w  w  w  .j a v a  2 s  . c o  m*/
    int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January
    int fromDD = Integer.valueOf(request.getParameter("b"));
    int fromYYYY = Integer.valueOf(request.getParameter("c"));
    int toMM = Integer.valueOf(request.getParameter("d"));
    int toDD = Integer.valueOf(request.getParameter("e"));
    int toYYYY = Integer.valueOf(request.getParameter("f"));
    String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear
    ValidationUtils.validateResolution(resolution);
    String symbol = request.getParameter("s");
    ValidationUtils.validateSymbol(symbol);
    String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM,
            fromDD, fromYYYY, toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING));
    String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY,
            toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache

    FileCache fileCache = JsquantContextListener.getFileCache(request);
    String responseBody = fileCache.get(cacheKey);
    if (responseBody == null) {
        HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        log.debug("requesting uri=" + httpget.getURI());
        responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler);
        //httpget.setReleaseTrigger(releaseTrigger); // no need to close?
        fileCache.put(cacheKey, responseBody);
    }

    String[] lines = responseBody.split("\n");
    List<Stock> dayPrices = new ArrayList<Stock>();
    int index = 0;
    for (String line : lines)
        if (index++ > 0 && line.length() > 0)
            dayPrices.add(new Stock(line));
    Collections.reverse(dayPrices);

    index = 0;
    BigDecimal allTimeHighClose = new BigDecimal(0);
    BigDecimal stopAt = null;
    BigDecimal boughtPrice = null;
    Stock sPrev = null;
    for (Stock s : dayPrices) {
        allTimeHighClose = allTimeHighClose.max(s.adjClose);
        s.allTimeHighClose = allTimeHighClose;
        if (index > 0) {
            sPrev = dayPrices.get(index - 1);
            //true range = max(high,closeprev) - min(low,closeprev)
            s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose));
        }
        int rng = 10;
        if (index > rng) {
            BigDecimal sum = new BigDecimal(0);
            for (Stock s2 : dayPrices.subList(index - rng, index))
                sum = sum.add(s2.trueRange);
            s.ATR10 = sum.divide(new BigDecimal(rng));

            if (allTimeHighClose.equals(s.adjClose)) {
                stopAt = s.adjClose.subtract(s.ATR10);
            }
        }

        s.stopAt = stopAt;

        if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null
                && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) {
            s.order = OrderAction.SELL;
            s.soldPrice = s.adjClose;
            s.soldDifference = s.soldPrice.subtract(boughtPrice);
        } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null
                && sPrev.order == OrderAction.IGNORE) {
            s.order = OrderAction.BUY;
            boughtPrice = s.adjClose;
            s.boughtPrice = boughtPrice;
        } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) {
            s.order = OrderAction.HOLD;
        } else {
            s.order = OrderAction.IGNORE;
        }
        index++;
    }

    ServletOutputStream out = response.getOutputStream();
    out.println(lines[0]
            + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference");
    for (Stock s : dayPrices)
        out.println(s.getCSV());

}

From source file:gov.medicaid.screening.dao.impl.BaseDAO.java

/**
 * Trim the results./*from w w  w  .j  av  a2 s. c  om*/
 * 
 * @param allResults
 *            All the search results.
 * @param pageSize
 *            The page size requested
 * @param pageNumber
 *            The page number requested
 * @param sortColumn
 *            the sort column
 * @param sortOrder
 *            the sort order
 * @param <T>
 *            the type of the results
 * @return trimmed results
 * @throws ServiceException
 *             for any errors encountered
 */
@SuppressWarnings("unchecked")
protected <T extends Object> SearchResult<T> trimResults(SearchResult<T> allResults, int pageSize,
        int pageNumber, String sortColumn, SortOrder sortOrder) throws ServiceException {
    if (pageNumber > 0 && pageSize < 1) {
        throw new ServiceException(ErrorCode.MITA10002.getDesc());
    }

    if (sortColumn != null) {
        Collections.sort(allResults.getItems(), new BeanComparator(sortColumn));
        if (sortOrder == SortOrder.DESC) {
            Collections.reverse(allResults.getItems());
        }
    }

    // trim result
    List<T> trimmedResults = new ArrayList<T>();
    List<T> allResultsList = allResults.getItems();
    if (pageNumber > 0) {
        if (allResultsList != null && !allResultsList.isEmpty()) {
            int fromIndex = pageSize * (pageNumber - 1);
            int toIndex = Math.min(fromIndex + pageSize, allResultsList.size());
            trimmedResults.addAll(allResultsList.subList(fromIndex, toIndex));
        }
    } else {
        trimmedResults.addAll(allResultsList);
    }

    SearchResult<T> result = new SearchResult<T>();
    result.setPageNumber(pageNumber);
    result.setPageSize(pageSize);
    result.setItems(trimmedResults);
    result.setTotal(allResultsList.size());
    if (pageSize > 0) {
        result.setTotalPages((int) Math.ceil((double) allResultsList.size() / pageSize));
    } else {
        result.setTotalPages(allResultsList.isEmpty() ? 0 : 1);
    }
    return result;
}

From source file:no.ntnu.okse.web.controller.LogController.java

/**
 * This method returns the log given the request parameters
 *
 * @param logID    The log file to return (represented as a integer)
 * @param logLevel The log level to show
 * @param length   How many lines to return
 * @return A Log model containing the correct log. Will be serialized as JSON
 *//*from w w  w .j a  va  2  s.  co m*/
@RequestMapping(method = RequestMethod.GET)
public Log log(@RequestParam(value = "logID", defaultValue = "0") Integer logID,
        @RequestParam(value = "logLevel", defaultValue = "DEBUG") String logLevel,
        @RequestParam(value = "length", defaultValue = "250") int length) {

    try {
        Stream<String> l = Files.lines(Paths.get("logs/", fileNames.get(logID)));

        List<String> lines = l.filter(x -> isWithinLogLevel(logLevel, x)).collect(Collectors.toList());
        Collections.reverse(lines);

        Log log;

        if (lines.size() > length) {
            log = new Log(fileNames.get(logID), lines.subList(0, length));
        } else {
            log = new Log(fileNames.get(logID), lines);
        }

        return log;

    } catch (IOException e) {
        Log log = new Log("Does not exists", new ArrayList<String>() {
            {
                add("The logfile you requested do not exist.");
            }
        });
        return log;
    }
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

@Override
public List<T> fetchAll() {
    File target = new File(Settings.instance().getTargetFolder());
    if (!target.isDirectory()) {
        if (getItemController().isWritable()) {
            target.mkdirs();/*from   w  ww.  ja v  a2 s . c  om*/
        } else {
            throw new ConfigException(String.format(
                    "The JSON bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.",
                    getItemController().getBucket(), getBucketFolderPath()));
        }
    }
    TreeVisitor visitor = new TreeVisitor();
    Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath());
    try {
        Files.walkFileTree(folderPath, visitor);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    List<T> objects = new ArrayList<>();
    for (Path path : visitor.getPaths()) {
        if (!matchesExtension(path.toString())) {
            continue;
        }

        if (path.toString().contains(".#")) {
            continue;
        }
        if (path.getFileName().startsWith(".")) {
            continue;
        }
        T o = fetchOne(path.toString());
        if (o != null) {
            objects.add(o);
        }

    }
    objects.sort(new PropertyComparator<T>(sortField));
    if (sortDirection.toLowerCase().equals("desc")) {
        Collections.reverse(objects);
    }

    return objects;
}

From source file:com.netflix.curator.x.discovery.TestServiceCache.java

@Test
public void testViaProvider() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//w  ww. j ava 2 s  .  co  m
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class)
                .basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> serviceProvider = discovery.serviceProviderBuilder().serviceName("test")
                .build();
        closeables.add(serviceProvider);
        serviceProvider.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10064).build();
        discovery.registerService(instance);

        int count = 0;
        ServiceInstance<String> foundInstance = null;
        while (foundInstance == null) {
            Assert.assertTrue(count++ < 5);
            foundInstance = serviceProvider.getInstance();
            Thread.sleep(1000);
        }
        Assert.assertEquals(foundInstance, instance);
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.adito.server.jetty.CustomWebApplicationContext.java

/**
 * <p>/*from w w  w .  j  a v  a  2s.  co  m*/
 * Add a new Resource Cache. Whenever a resource is requested, this handler
 * will search all registered resource caches until one can locate it.
 * 
 * <p>
 * This shouldn't be called directly, but through
 * {@link com.adito.boot.Context#addResourceBase(URL)}
 * 
 * @param cache cache to add
 */
public void addResourceCache(ResourceCache cache) {
    resourceCaches.add(cache);
    reverseCaches.clear();
    cacheState.clear();
    reverseCaches.addAll(resourceCaches);
    Collections.reverse(reverseCaches);
}

From source file:com.breadwallet.tools.manager.CurrencyManager.java

private Set<CurrencyEntity> getCurrencies(Activity context) {
    Set<CurrencyEntity> set = new LinkedHashSet<>();
    if (((BreadWalletApp) ctx.getApplication()).hasInternetAccess()) {
        try {/*from ww  w. ja  v a 2 s . c om*/
            JSONArray arr = JsonParser.getJSonArray(context);
            JsonParser.updateFeePerKb(context);
            //                Log.e(TAG, "JSONArray arr.length(): " + arr.length());
            if (arr != null) {
                int length = arr.length();
                for (int i = 1; i < length; i++) {
                    CurrencyEntity tmp = new CurrencyEntity();
                    try {
                        JSONObject tmpObj = (JSONObject) arr.get(i);
                        tmp.name = tmpObj.getString("name");
                        tmp.code = tmpObj.getString("code");
                        tmp.codeAndName = tmp.code + " - " + tmp.name;
                        tmp.rate = (float) tmpObj.getDouble("rate");
                        String selectedISO = SharedPreferencesManager.getIso(context);
                        //                        Log.e(TAG,"selectedISO: " + selectedISO);
                        if (tmp.code.equalsIgnoreCase(selectedISO)) {
                            //                            Log.e(TAG, "theIso : " + theIso);
                            //                                Log.e(TAG, "Putting the shit in the shared preffs");
                            SharedPreferencesManager.putIso(context, tmp.code);
                            SharedPreferencesManager.putCurrencyListPosition(context, i - 1);
                            //                            Log.e(TAG,"position set: " + (i - 1));
                            SharedPreferencesManager.putRate(context, tmp.rate);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    set.add(tmp);
                }
            } else {
                Log.e(TAG, "getCurrencies: failed to get currencies, response string: " + arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    List tempList = new ArrayList<>(set);
    Collections.reverse(tempList);
    return new LinkedHashSet<>(set);
}