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:de.codesourcery.eve.skills.db.datamodel.MarketGroup.java

/**
 * Returns the path from a given <code>MarketGroup</code> to it's root
 * <code>MarketGroup</code>.
 * /*from w  w  w.j  ava2 s .  c o  m*/
 * @param group market group to find path for
 * @return path with the first element being the top-level market group
 * and the last element being the input <code>MarketGroup</code> 
 */
public List<MarketGroup> getPathToRoot() {
    final List<MarketGroup> result = new ArrayList<>();
    MarketGroup current = this;
    while (current != null) {
        result.add(current);
        current = current.getParent();
    }
    Collections.reverse(result);
    return result;
}

From source file:de.taimos.pipeline.aws.cloudformation.EventPrinter.java

public void waitAndPrintStackEvents(String stack, Waiter<DescribeStacksRequest> waiter) {
    Date startDate = new Date();

    final AtomicBoolean done = new AtomicBoolean(false);

    waiter.runAsync(new WaiterParameters<>(new DescribeStacksRequest().withStackName(stack)),
            new WaiterHandler() {
                @Override// w  w w  .j  a  v a  2 s. c om
                public void onWaitSuccess(AmazonWebServiceRequest request) {
                    done.set(true);
                }

                @Override
                public void onWaitFailure(Exception e) {
                    done.set(true);
                }
            });

    String lastEventId = null;
    this.printLine();
    this.printStackName(stack);
    this.printLine();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    while (!done.get()) {
        try {
            DescribeStackEventsResult result = this.client
                    .describeStackEvents(new DescribeStackEventsRequest().withStackName(stack));
            List<StackEvent> stackEvents = new ArrayList<>();
            for (StackEvent event : result.getStackEvents()) {
                if (event.getEventId().equals(lastEventId) || event.getTimestamp().before(startDate)) {
                    break;
                }
                stackEvents.add(event);
            }
            if (!stackEvents.isEmpty()) {
                Collections.reverse(stackEvents);
                for (StackEvent event : stackEvents) {
                    this.printEvent(sdf, event);
                    this.printLine();
                }
                lastEventId = stackEvents.get(stackEvents.size() - 1).getEventId();
            }
        } catch (AmazonCloudFormationException e) {
            // suppress and continue
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:cz.jirutka.spring.exhandler.handlers.ConstraintViolationExceptionHandler.java

private Node findLastNonEmptyPathNode(Path path) {

    List<Node> list = new ArrayList<>();
    for (Iterator<Node> it = path.iterator(); it.hasNext();) {
        list.add(it.next());/*from w w w .  java2 s. c  o  m*/
    }
    Collections.reverse(list);
    for (Node node : list) {
        if (!isEmpty(node.getName())) {
            return node;
        }
    }
    return null;
}

From source file:com.github.luuuis.myzone.preference.TimeZoneInfo.java

private String getDisplayId() {
    // return city name before country/continent
    List<String> tokens = Lists.newArrayList(split(timeZone.getID(), ID_SEPARATOR));
    Collections.reverse(tokens);

    return join(tokens, DISPLAY_SEPARATOR).replace(DISPLAY_STRIP, " ");
}

From source file:com.predic8.membrane.core.transport.http.InterceptorInvocationTest.java

private List<String> getReverseList(List<String> list) {
    List<String> res = new ArrayList<String>(list);
    Collections.reverse(res);
    return res;//  w w w.  j  a  va2 s. c  o m
}

From source file:com.predic8.membrane.core.transport.http.AbstractHttpRunnable.java

protected List<Interceptor> getInterceptorsReverse(List<Interceptor> list) {
    Collections.reverse(list);
    return list;
}

From source file:com.googlecode.flyway.core.validation.DbValidator.java

/**
 * Validate the checksum of all existing sql migration in the metadata table with the checksum of the sql migrations
 * in the classpath//from  ww  w. j a v  a2  s  . c o  m
 *
 * @param resolvedMigrations All migrations available on the classpath, sorted by version, newest first.
 * @return description of validation error or NULL if no validation error was found
 */
public String validate(List<Migration> resolvedMigrations) {
    if (ValidationMode.NONE.equals(validationMode)) {
        return null;
    }

    LOG.debug(String.format("Validating (mode %s) migrations ...", validationMode));
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final List<MetaDataTableRow> appliedMigrations = new ArrayList<MetaDataTableRow>(
            metaDataTable.allAppliedMigrations());
    if (appliedMigrations.isEmpty()) {
        LOG.info("No migrations applied yet. No validation necessary.");
        return null;
    }

    List<Migration> migrations = new ArrayList<Migration>(resolvedMigrations);
    // migrations now with newest last
    Collections.reverse(migrations);
    final MetaDataTableRow firstAppliedMigration = appliedMigrations.get(0);
    if (MigrationType.INIT.equals(firstAppliedMigration.getMigrationType())) {
        // if first migration is INIT, just check checksum of following migrations
        final SchemaVersion initVersion = firstAppliedMigration.getVersion();
        appliedMigrations.remove(firstAppliedMigration);

        Iterator<Migration> iterator = migrations.iterator();
        while (iterator.hasNext()) {
            Migration migration = iterator.next();
            if (migration.getVersion().compareTo(initVersion) <= 0) {
                iterator.remove();
            }
        }
    }

    if (appliedMigrations.size() > migrations.size()) {
        List<SchemaVersion> schemaVersions = new ArrayList<SchemaVersion>();
        for (MetaDataTableRow metaDataTableRow : appliedMigrations) {
            schemaVersions.add(metaDataTableRow.getVersion());
        }
        for (Migration migration : migrations) {
            schemaVersions.remove(migration.getVersion());
        }

        String diff = StringUtils.collectionToCommaDelimitedString(schemaVersions);

        return String.format(
                "More applied migrations than classpath migrations: DB=%s, Classpath=%s, Missing migrations=(%s)",
                appliedMigrations.size(), migrations.size(), diff);
    }

    for (int i = 0; i < appliedMigrations.size(); i++) {
        MetaDataTableRow appliedMigration = appliedMigrations.get(i);
        //Migrations are sorted in the opposite order: newest first.
        Migration classpathMigration = migrations.get(i);

        if (!appliedMigration.getVersion().equals(classpathMigration.getVersion())) {
            return String.format("Version mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getVersion(),
                    classpathMigration.getVersion());

        }
        if (!appliedMigration.getMigrationType().equals(classpathMigration.getMigrationType())) {
            return String.format("Migration Type mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getMigrationType(),
                    classpathMigration.getMigrationType());
        }

        final Integer appliedChecksum = appliedMigration.getChecksum();
        final Integer classpathChecksum = classpathMigration.getChecksum();
        if (!ObjectUtils.nullSafeEquals(appliedChecksum, classpathChecksum)) {
            return String.format("Checksum mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedChecksum, classpathMigration.getChecksum());
        }
    }

    stopWatch.stop();
    if (appliedMigrations.size() == 1) {
        LOG.info(String.format("Validated 1 migration (mode: %s) (execution time %s)", validationMode,
                TimeFormat.format(stopWatch.getTotalTimeMillis())));
    } else {
        LOG.info(String.format("Validated %d migrations (mode: %s) (execution time %s)",
                appliedMigrations.size(), validationMode, TimeFormat.format(stopWatch.getTotalTimeMillis())));
    }

    return null;
}

From source file:com.jgeppert.struts2.jquery.showcase.grid.GridDataProvider.java

@SuppressWarnings("unchecked")
public String execute() {
    log.debug("Page " + getPage() + " Rows " + getRows() + " Sorting Order " + getSord() + " Index Row :"
            + getSidx());/*  w  w  w . ja v  a  2  s .c o  m*/
    log.debug("Search :" + searchField + " " + searchOper + " " + searchString);

    Object list = session.get("mylist");
    if (list != null) {
        myCustomers = (List<Customer>) list;
    } else {
        log.debug("Build new List");
        myCustomers = CustomerDAO.buildList();
    }

    if (sord != null && sord.equalsIgnoreCase("asc")) {
        Collections.sort(myCustomers);
    }
    if (sord != null && sord.equalsIgnoreCase("desc")) {
        Collections.sort(myCustomers);
        Collections.reverse(myCustomers);
    }

    // Count all record (select count(*) from your_custumers)
    records = CustomerDAO.getCustomersCount(myCustomers);

    if (totalrows != null) {
        records = totalrows;
    }

    // Calucalate until rows ware selected
    int to = (rows * page);

    // Calculate the first row to read
    int from = to - rows;

    // Set to = max rows
    if (to > records)
        to = records;

    if (loadonce) {
        if (totalrows != null && totalrows > 0) {
            Collections.sort(myCustomers, new Comparator<Customer>() {
                public int compare(Customer o1, Customer o2) {
                    return o1.getCountry().compareToIgnoreCase(o2.getCountry());
                }
            });
            setGridModel(myCustomers.subList(0, totalrows));
        } else {
            // All Custumer
            setGridModel(myCustomers);
        }
    } else {
        // Search Custumers
        if (searchString != null && searchOper != null) {
            int id = Integer.parseInt(searchString);
            if (searchOper.equalsIgnoreCase("eq")) {
                log.debug("search id equals " + id);
                List<Customer> cList = new ArrayList<Customer>();
                Customer customer = CustomerDAO.findById(myCustomers, id);

                if (customer != null)
                    cList.add(customer);

                setGridModel(cList);
            } else if (searchOper.equalsIgnoreCase("ne")) {
                log.debug("search id not " + id);
                setGridModel(CustomerDAO.findNotById(myCustomers, id, from, to));
            } else if (searchOper.equalsIgnoreCase("lt")) {
                log.debug("search id lesser then " + id);
                setGridModel(CustomerDAO.findLesserAsId(myCustomers, id, from, to));
            } else if (searchOper.equalsIgnoreCase("gt")) {
                log.debug("search id greater then " + id);
                setGridModel(CustomerDAO.findGreaterAsId(myCustomers, id, from, to));
            }
        } else {
            setGridModel(CustomerDAO.getCustomers(myCustomers, from, to));
        }
    }

    // Calculate total Pages
    total = (int) Math.ceil((double) records / (double) rows);

    // only for showcase functionality, don't do this in production
    session.put("mylist", myCustomers);

    return SUCCESS;
}

From source file:jease.cmf.domain.Node.java

/**
 * Returns all parents of node ordered from root to parent of node.
 *//*from   w ww .ja  va 2s  . c  om*/
public Node[] getParents() {
    List<Node> parents = new ArrayList<>();
    Node parentNode = getParent();
    while (parentNode != null) {
        parents.add(parentNode);
        parentNode = parentNode.getParent();
    }
    Collections.reverse(parents);
    return parents.toArray(new Node[parents.size()]);
}

From source file:com.epam.cme.storefront.breadcrumb.impl.SearchBreadcrumbBuilder.java

public List<Breadcrumb> getBreadcrumbs(final String categoryCode,
        final ProductSearchPageData<SearchStateData, ProductData> searchPageData)
        throws IllegalArgumentException {
    final List<Breadcrumb> breadcrumbs = new ArrayList<Breadcrumb>();

    final boolean emptyBreadcrumbs = CollectionUtils.isEmpty(searchPageData.getBreadcrumbs());
    Breadcrumb breadcrumb;// w  w w. ja  v  a  2s  . com
    if (categoryCode == null) {
        breadcrumb = new Breadcrumb("/search?text=" + getEncodedUrl(searchPageData.getFreeTextSearch()),
                StringEscapeUtils.escapeHtml(searchPageData.getFreeTextSearch()),
                (emptyBreadcrumbs ? LAST_LINK_CLASS : ""));
        breadcrumbs.add(breadcrumb);
    } else {
        // Create category hierarchy path for breadcrumb
        final List<Breadcrumb> categoryBreadcrumbs = new ArrayList<Breadcrumb>();
        final Collection<CategoryModel> categoryModels = new ArrayList<CategoryModel>();
        final CategoryModel lastCategoryModel = getCommerceCategoryService().getCategoryForCode(categoryCode);
        categoryModels.addAll(lastCategoryModel.getSupercategories());
        categoryBreadcrumbs
                .add(getCategoryBreadcrumb(lastCategoryModel, (!emptyBreadcrumbs ? LAST_LINK_CLASS : "")));

        while (!categoryModels.isEmpty()) {
            final CategoryModel categoryModel = categoryModels.iterator().next();
            if (!(categoryModel instanceof ClassificationClassModel)) {
                if (categoryModel != null) {
                    categoryBreadcrumbs.add(getCategoryBreadcrumb(categoryModel));
                    categoryModels.clear();
                    categoryModels.addAll(categoryModel.getSupercategories());
                }
            }
        }
        Collections.reverse(categoryBreadcrumbs);
        breadcrumbs.addAll(categoryBreadcrumbs);
    }
    return breadcrumbs;
}