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:ch.ksfx.util.calc.MovingAverageCalculator.java

public static Double calculateMovingAverageObservation(List<Observation> prices, Integer ticksBackFromNow,
        boolean askPrice) {
    if (prices.size() < ticksBackFromNow) {
        return null;
    }// ww w . j  av  a2s .  c o m

    List<Observation> aps = new ArrayList<Observation>(prices);

    Collections.sort(aps, new ObservationDateComparator());
    Collections.reverse(aps);

    //for (AssetPrice test : aps) {
    //    logger.info("SORTTEST = " + test.getPricingTime());
    //}

    if (askPrice) {
        Double cal = 0.0;

        for (Integer i = 0; i < ticksBackFromNow && prices.size() >= ticksBackFromNow; i++) {
            cal = cal + Double.parseDouble(aps.get(i).getScalarValue());
        }

        return cal / ticksBackFromNow;
    } else {
        Double cal = 0.0;

        for (Integer i = 0; i < ticksBackFromNow && prices.size() >= ticksBackFromNow; i++) {

            //logger.info("MA based on " + aps.get(i).getBid() + " TIME: " + aps.get(i).getPricingTime());

            cal = cal + Double.parseDouble(aps.get(i).getScalarValue());
        }

        //logger.info("====================");

        return cal / ticksBackFromNow;
    }
}

From source file:com.sheepdog.mashmesh.Itinerary.java

public static Itinerary fetch(String fromLocation, String toLocation, String viaLocation, DateTime arrivalTime)
        throws URISyntaxException, IOException {
    URIBuilder uriBuilder = new URIBuilder(DIRECTIONS_ENDPOINT_URL);
    uriBuilder.addParameter("origin", fromLocation);
    uriBuilder.addParameter("destination", toLocation);
    uriBuilder.addParameter("mode", "driving");
    uriBuilder.addParameter("language", "en_US"); // TODO: Configurable?
    uriBuilder.addParameter("region", "us");
    uriBuilder.addParameter("waypoints", viaLocation);
    uriBuilder.addParameter("sensor", "false");

    URL url = uriBuilder.build().toURL();
    BufferedReader responseReader = new BufferedReader(new InputStreamReader(url.openStream()));

    JsonParser parser = new JsonParser();
    JsonObject responseObject = parser.parse(responseReader).getAsJsonObject();
    JsonObject route = responseObject.getAsJsonArray("routes").get(0).getAsJsonObject();
    JsonArray legs = route.getAsJsonArray("legs");

    JsonObject startLeg = legs.get(0).getAsJsonObject();
    JsonObject endLeg = legs.get(legs.size() - 1).getAsJsonObject();

    DateTime departureTime = arrivalTime;
    List<Leg> directionLegs = new ArrayList<Leg>();

    Preconditions.checkState(legs.size() == 2, "Expected two direction legs in response");

    // Process the legs in reverse order so that we can compute departure and arrival
    //  times by working backwards from the desired arrival time.
    for (int i = legs.size() - 1; i >= 0; i--) {
        JsonObject leg = legs.get(i).getAsJsonObject();
        List<Step> directionSteps = new ArrayList<Step>();
        DateTime legArrivalTime = departureTime;

        for (JsonElement stepElement : leg.getAsJsonArray("steps")) {
            JsonObject stepObject = stepElement.getAsJsonObject();
            int duration = stepObject.getAsJsonObject("duration").get("value").getAsInt();
            String htmlInstructions = stepObject.get("html_instructions").getAsString();
            String distance = stepObject.getAsJsonObject("distance").get("text").getAsString();

            departureTime = departureTime.minusSeconds(duration);
            directionSteps.add(new Step(htmlInstructions, distance));
        }/*from   w w w .j  a  v a 2  s .c om*/

        Leg directionLeg = new Leg();
        directionLeg.departureTime = departureTime;
        directionLeg.startLatLng = getLatLng(leg.getAsJsonObject("start_location"));
        directionLeg.arrivalTime = legArrivalTime;
        directionLeg.endLatLng = getLatLng(leg.getAsJsonObject("end_location"));
        directionLeg.distanceMeters = leg.getAsJsonObject("distance").get("value").getAsInt();
        directionLeg.steps = Collections.unmodifiableList(directionSteps);
        directionLegs.add(directionLeg);
    }

    Collections.reverse(directionLegs);

    Itinerary itinerary = new Itinerary();
    itinerary.startAddress = startLeg.get("start_address").getAsString();
    itinerary.endAddress = endLeg.get("end_address").getAsString();
    itinerary.legs = Collections.unmodifiableList(directionLegs);
    itinerary.overviewPolyline = route.getAsJsonObject("overview_polyline").get("points").getAsString();

    return itinerary;
}

From source file:eu.europa.esig.dss.validation.process.ltv.ControlTimeSliding.java

/**
 * @param params// www  .jav  a2 s .  c  om
 * @param certificateChain
 * @return
 */
private ControlTimeSlidingConclusion process(final ProcessParameters params, final XmlDom certificateChain) {

    final ControlTimeSlidingConclusion conclusion = new ControlTimeSlidingConclusion();

    final String signingCertificateId = certificateChain.getValue("./ChainCertificate[1]/@Id");

    final List<XmlDom> chainCertificates = certificateChain.getElements("./ChainCertificate");

    Collections.reverse(chainCertificates);

    /**
     * 2) For each certificate in the chain starting from the first certificate (the certificate issued by the trust
     * anchor), do the following:<br>
     */
    for (final XmlDom chainCertificate : chainCertificates) {

        final String certificateId = getCertificateId(chainCertificate);
        final XmlNode certificateNode = controlTimeSlidingData.addChild(AttributeValue.CERTIFICATE,
                StringUtils.EMPTY);
        certificateNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId));

        final XmlDom certificate = params.getCertificate(certificateId);

        final boolean isTrusted = certificate.getBoolValue("./Trusted/text()");
        if (isTrusted) {

            continue;
        }

        if (StringUtils.equals(signingCertificateId, certificateId)) {

            /**
             * (See NOTE 1) Concerning the trust anchor, it must be checked if it is still trusted at the current
             * date/time. Other checks are not necessary.<br>
             */
            final XmlNode constraintNode = addConstraint(MessageTag.CTS_WITSS);

            final String status = InvolvedServiceInfo.getStatus(certificate);
            constraintNode.addChild(NodeName.STATUS, NodeValue.OK);
            constraintNode.addChild(NodeName.INFO).setAttribute(AttributeValue.TRUSTED_SERVICE_STATUS, status);

            final boolean underSupervision = InvolvedServiceInfo.isSERVICE_STATUS_UNDERSUPERVISION(status);
            final boolean supervisionInCessation = InvolvedServiceInfo
                    .isSERVICE_STATUS_SUPERVISIONINCESSATION(status);
            final boolean accredited = InvolvedServiceInfo.isSERVICE_STATUS_ACCREDITED(status);

            if (!underSupervision && !supervisionInCessation && !accredited) {

                /**
                 * ...where the trust anchor is broken at a known date by initialising control-time to this date/time.<br>
                 */
                if (status.isEmpty()) {

                    // Trusted service is unknown
                    final String serviceName = InvolvedServiceInfo.getServiceName(certificate);
                    LOG.warn("The status of the service is unknown: (serviceName: " + serviceName + ")");
                } else {

                    final Date statusEndDate = InvolvedServiceInfo.getEndDate(certificate);
                    controlTime = statusEndDate;
                    addControlTime(constraintNode);
                }
            }
        }
        /**
         * - a) Find revocation status information satisfying the following:<br>
         * - -  The revocation status information is consistent with the rules conditioning its use to check the
         * revocation status of the considered certificate. For instance, in the case of a CRL, it shall satisfy the
         * checks described in (see clause 6.3).<br>
         *
         * TODO: 20130704 by bielecro: To notify ETSI --> (see clause 6.3) is not the right clause.<br>
         */

        XmlNode constraintNode = addConstraint(MessageTag.CTS_DRIE);

        final boolean revocationExists = certificate.exists("./Revocation");
        if (!revocationExists) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }

        final Date revocationIssuingTime = certificate.getTimeValue("./Revocation/IssuingTime/text()");
        final String formatedRevocationIssuingTime = DSSUtils.formatDate(revocationIssuingTime);

        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);
        constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_ISSUING_TIME,
                formatedRevocationIssuingTime);

        final Date notAfterTime = certificate.getTimeValue("./NotAfter/text()");
        final Date notBeforeTime = certificate.getTimeValue("./NotBefore/text()");

        /**
         * (See NOTE 2)<br>
         * TODO: ...(for instance, using the CRL extension expiredCertOnCRL (OID: 2.5.29.60)) This check need to be
         * added to the revocation information retrieval.
         */
        constraintNode = addConstraint(MessageTag.CTS_ICNEAIDORSI);

        if (revocationIssuingTime.before(notBeforeTime) || revocationIssuingTime.after(notAfterTime)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);

            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - -  The issuance date of the revocation status information is before control-time. If more than one
         * revocation status is found, consider the most recent one and go to the next step. If there is no such
         * information, terminate with INDETERMINATE/NO_POE:<br>
         */

        constraintNode = addConstraint(MessageTag.CTS_IIDORSIBCT);

        if (!revocationIssuingTime.before(controlTime)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            addControlTime(constraintNode);

            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - b) If the set of POEs contains a proof of existence of the certificate and the revocation status
         * information at (or before) control-time, go to step c). Otherwise, terminate with INDETERMINATE/NO_POE.
         */

        constraintNode = addConstraint(MessageTag.CTS_DSOPCPOEOC);

        final boolean poeExists = poe.getCertificatePOE(certificateId, controlTime);
        if (!poeExists || (revocationIssuingTime.compareTo(controlTime) > 0)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            conclusion.setIndication(Indication.INDETERMINATE);
            conclusion.setSubIndication(SubIndication.NO_POE);
            return conclusion;
        }
        constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

        /**
         * - c) Update the value of control-time as follows:<br>
         */

        constraintNode = addConstraint(MessageTag.CTS_SCT);
        addControlTime(constraintNode);

        final boolean revoked = !certificate.getBoolValue("./Revocation/Status/text()");
        /**
         * - -  If the certificate is marked as revoked in the revocation status information, set control-time to the
         * revocation date.<br>
         */
        if (revoked) {

            final Date revocationDate = certificate.getTimeValue("./Revocation/DateTime/text()");
            controlTime = revocationDate;

            final String formatedRevocationDate = DSSUtils.formatDate(revocationDate);
            constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRT_LABEL);
            constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_TIME,
                    formatedRevocationDate);
        } else {

            /**
             * - -  If the certificate is not marked as revoked.<br>
             * - - - - If the revocation status information is not considered "fresh", set control-time to the issuance
             * date of the revocation status information.<br>
             */
            final long revocationDeltaTime = controlTime.getTime() - revocationIssuingTime.getTime();
            if (revocationDeltaTime > constraintData.getMaxRevocationFreshness()) {

                controlTime = revocationIssuingTime;
                constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRIT_LABEL);
                final XmlNode xmlNode = constraintNode.addChild(NodeName.INFO, MessageTag.BBB_XCV_IRIF_ANS);
                xmlNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId))
                        .setAttribute(AttributeName.REVOCATION_ISSUING_TIME, formatedRevocationIssuingTime);
            }

            /**
             * - - - - Otherwise, the value of control-time is not changed.<br>
             */
        }
        /**
         * - d) Apply the cryptographic constraints to the certificate and the revocation status information. If the
         * certificate (or the revocation status information) does not match these constraints, set control-time to the
         * lowest time up to which the listed algorithms were considered reliable.<br>
         */

        checkDigestAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL);
        checkEncryptionAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL);

        final XmlDom revocation = certificate.getElement("./Revocation");
        checkDigestAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL);
        checkEncryptionAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL);

        /**
         * 3) Continue with the next certificate in the chain or, if no further certificate exists, terminate with
         * VALID and the calculated control-time.<br>
         */
    }
    /**
     * NOTE 1: In step 1, initialising control-time with current date/time assumes that the trust anchor is still
     * trusted at the current date/time. The algorithm can capture the very exotic case where the trust anchor is
     * broken (or becomes untrusted for any other reason) at a known date by initialising control-time to this
     * date/time.<br>
     *
     * NOTE 2: The rational of step 2-a) is to check that the revocation status information is "in-scope" for the
     * given certificate. In other words, the rationale is to check that the revocation status information is reliable
     * to be used to ascertain the revocation status of the given certificate. For instance, this includes the fact
     * the certificate is not expired at the issuance date of the revocation status information, unless the issuing CA
     * states that its issues revocation information status for expired certificates (for instance, using the CRL
     * extension expiredCertOnCRL).<br>
     *
     * NOTE 3: If the certificate (or the revocation status information) was authentic, but the signature has been
     * faked exploiting weaknesses of the algorithms used, this is assumed only to be possible after the date the
     * algorithms are declared to be no longer acceptable. Therefore, the owner of the original key pair is assumed to
     * having been under control of his key up to that date. This is the rational of sliding control-time in step
     * 2-d).<br>
     *
     * NOTE 4: For more readability, the algorithm above implicitly assumes that the revocation information status is
     * signed by the certificate's issuer which is the most traditional revocation setting but not the only one. The
     * same algorithm can be adapted to the cases where the revocation information status has its own certificate
     * chain by applying the control-time sliding process to this chain which would output a control-time that has to
     * be compared to the control-time associated to the certificate.
     */

    conclusion.setIndication(Indication.VALID);
    conclusion.addInfo().setAttribute(AttributeValue.CONTROL_TIME, DSSUtils.formatDate(controlTime));

    return conclusion;
}

From source file:dk.statsbiblioteket.alto.AnagramHashing.java

public static void dumpAnagramTerms(AnagramDictionary anagramDictionary, int minVariants, int maxVariants,
        int maxLev, boolean onlyStrongPrimaries) {
    System.out.println("minTerms=" + minVariants + ", maxTerms=" + maxVariants + ", maxLev="
            + (maxLev < 0 ? "N/A" : maxLev));

    List<Pair<Integer, String>> values = new ArrayList<Pair<Integer, String>>();
    primaryLoop: for (Map.Entry<String, AnagramDictionary.Word> entry : anagramDictionary.getPrimaryDict()
            .entrySet()) {//from   w  w w  .j  a  va 2  s .  c om
        AnagramDictionary.Word word = entry.getValue();
        Set<String> secondaries = maxLev < 0 ? word.getSecondaries() : word.getSecondaries(maxLev);

        if (secondaries.size() + 1 < minVariants || secondaries.size() + 1 > maxVariants) {
            continue;
        }
        String output = word.getPrimary() + "(" + word.getPrimaryOccurrences() + "):";
        for (String secondary : secondaries) {
            int secondaryOccurrences = anagramDictionary.get(secondary).getPrimaryOccurrences();
            if (onlyStrongPrimaries) {
                if (secondaryOccurrences > word.getPrimaryOccurrences()) {
                    continue primaryLoop;
                }
            }
            output += " " + secondary + "(" + secondaryOccurrences + ")";
        }
        values.add(new Pair<Integer, String>(word.getPrimaryOccurrences(), output));
    }
    Collections.sort(values);
    Collections.reverse(values);
    for (Pair<Integer, String> value : values) {
        System.out.println(value.getPayload());
    }
}

From source file:lisong_mechlab.view.graphs.DpsGraph.java

private TableXYDataset getSeries() {
    final Collection<Modifier> modifiers = loadout.getModifiers();
    SortedMap<Weapon, Integer> multiplicity = new TreeMap<Weapon, Integer>(new Comparator<Weapon>() {
        @Override/*  w w w  .  j  a va 2  s  .  com*/
        public int compare(Weapon aO1, Weapon aO2) {
            int comp = Double.compare(aO2.getRangeMax(modifiers), aO1.getRangeMax(modifiers));
            if (comp == 0)
                return aO1.compareTo(aO2);
            return comp;
        }
    });

    for (Weapon weapon : loadout.items(Weapon.class)) {
        if (!weapon.isOffensive())
            continue;
        if (!multiplicity.containsKey(weapon)) {
            multiplicity.put(weapon, 0);
        }
        int v = multiplicity.get(weapon);
        multiplicity.put(weapon, v + 1);
    }

    List<Weapon> orderedWeapons = new ArrayList<>();
    Double[] ranges = WeaponRanges.getRanges(multiplicity.keySet(), modifiers);
    DefaultTableXYDataset dataset = new DefaultTableXYDataset();
    for (Map.Entry<Weapon, Integer> e : multiplicity.entrySet()) {
        Weapon weapon = e.getKey();
        int mult = e.getValue();

        XYSeries series = new XYSeries(weapon.getName(), true, false);
        for (double range : ranges) {
            final double dps = weapon.getStat("d/s", modifiers);
            final double rangeEff = weapon.getRangeEffectivity(range, modifiers);
            series.add(range, dps * rangeEff * mult);
        }
        dataset.addSeries(series);
        orderedWeapons.add(e.getKey());
    }
    Collections.reverse(orderedWeapons);
    colours.updateColoursToMatch(orderedWeapons);
    return dataset;
}

From source file:org.codeqinvest.web.project.InvestmentOpportunitiesJsonGenerator.java

private List<String> getAllPackageNamesReversed(Artefact artefact) {
    List<String> packages = new ArrayList<String>();
    StringBuilder packagePath = new StringBuilder();
    for (String packageName : PACKAGE_SPLITTER.split(artefact.getName())) {
        if (packageName.equals(artefact.getShortClassName())) {
            break;
        }//from w ww  .j  ava2  s . c om
        if (packagePath.length() > 0) {
            packagePath.append('.');
        }
        packagePath.append(packageName);
        packages.add(packagePath.toString());
    }
    Collections.reverse(packages);
    return packages;
}

From source file:me.st28.flexseries.flexcore.command.FlexCommand.java

/**
 * @return a list containing the hierarchy of parents for this command.
 *//*from w ww .  j a v  a 2  s  .c o  m*/
public final List<FlexCommand<T>> getParents() {
    List<FlexCommand<T>> returnList = new ArrayList<>();

    FlexCommand<T> tempParent = parent;
    while (tempParent != null) {
        returnList.add(tempParent);
        tempParent = tempParent.parent;
    }

    Collections.reverse(returnList);
    return returnList;
}

From source file:org.openmrs.module.kenyaemr.api.impl.KenyaEmrServiceImpl.java

/**
 * @see KenyaEmrService#getVisitsByPatientAndDay(org.openmrs.Patient, java.util.Date)
 *///from w w  w .  j  av  a 2  s  .c o m
@Override
public List<Visit> getVisitsByPatientAndDay(Patient patient, Date date) {
    Date startOfDay = OpenmrsUtil.firstSecondOfDay(date);
    Date endOfDay = OpenmrsUtil.getLastMomentOfDay(date);

    // look for visits that started before endOfDay and ended after startOfDay
    List<Visit> visits = Context.getVisitService().getVisits(null, Collections.singleton(patient), null, null,
            null, endOfDay, startOfDay, null, null, true, false);
    Collections.reverse(visits); // We want by date asc
    return visits;
}

From source file:ca.cmput301w14t09.elasticSearch.ElasticSearchOperations.java

/**
 * pullThreads returns the list of top comments.  
 * Tested and verified.//from  w w w.j ava 2s .co  m
 * @return list of names of Threads.
 * @throws InterruptedException
 */
public static ArrayList<Comment> pullThreads() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final ArrayList<Comment> commentList = new ArrayList<Comment>();

    if (GSON == null)
        constructGson();

    Thread thread = new Thread() {

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();

            try {
                HttpPost searchRequest = new HttpPost(searchAddress);
                String query = "{\"query\" : {\"query_string\" : {\"default_field\" : \"topComment\",\"query\" : \"true\"}}}";

                StringEntity stringentity = new StringEntity(query);
                searchRequest.setEntity(stringentity);

                HttpResponse response = client.execute(searchRequest);
                String json = getEntityContent(response);

                Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Comment>>() {
                }.getType();
                ElasticSearchSearchResponse<Comment> esResponse = GSON.fromJson(json,
                        elasticSearchSearchResponseType);

                for (ElasticSearchResponse<Comment> r : esResponse.getHits()) {
                    Comment topComment = r.getSource();
                    commentList.add(topComment);
                }

                // Sort by latest dated element.
                Collections.sort(commentList);
                Collections.reverse(commentList);
                latch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
    latch.await();
    return commentList;
}