Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:com.fabernovel.alertevoirie.NewsActivity.java

@Override
public void onRequestcompleted(int requestCode, Object result) {
    Log.d(Constants.PROJECT_TAG, "resp : " + result);

    //@formatter:off
    /**/*from  w  ww .  j a  v a  2  s  .  c  o m*/
                    
    */
    //@formatter:on 

    try {
        JSONArray responses;
        responses = new JSONArray((String) result);
        response = responses.getJSONObject(0);
        SparseArray<JSONObject> events = new SparseArray<JSONObject>();

        if (requestCode == AVService.REQUEST_JSON) {

            if (JsonData.VALUE_REQUEST_GET_USERS_ACTVITIES.equals(response.getString(JsonData.PARAM_REQUEST))) {
                lock = new Vector<Integer>();
                logs = new SparseArray<JSONObject>();
                logList = new TreeMap<String, JSONObject>(Collections.reverseOrder());
                JSONArray incidentLog = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONArray(JsonData.PARAM_INCIDENT_LOG);
                for (int i = 0; i < incidentLog.length(); i++) {
                    JSONObject job = incidentLog.getJSONObject(i);
                    logs.put(job.getInt(JsonData.ANSWER_INCIDENT_ID), job);
                    logList.put(job.getString(JsonData.PARAM_INCIDENT_DATE)
                            + job.getLong(JsonData.ANSWER_INCIDENT_ID), job);
                }

                JSONArray items = new JSONArray();

                JSONArray ongoingIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_ONGOING_INCIDENTS);
                for (int i = 0; i < ongoingIncidents.length(); i++) {
                    JSONObject job = ongoingIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add ongoing incident " + key);
                        events.put(key, job);// items.put(job);
                    }
                }

                JSONArray updatedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS).getJSONArray(JsonData.PARAM_UPDATED_INCIDENTS);
                for (int i = 0; i < updatedIncidents.length(); i++) {
                    JSONObject job = updatedIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add updated incident " + key);
                        events.put(key, job);
                    }
                }

                JSONArray resolvedIncidents = response.getJSONObject(JsonData.PARAM_ANSWER)
                        .getJSONObject(JsonData.PARAM_INCIDENTS)
                        .getJSONArray(JsonData.PARAM_RESOLVED_INCIDENTS);
                for (int i = 0; i < resolvedIncidents.length(); i++) {
                    JSONObject job = resolvedIncidents.getJSONObject(i);
                    int key = job.getInt(JsonData.PARAM_INCIDENT_ID);
                    if (logs.get(key) != null) {
                        Log.d("AlerteVoirie_PM", "add resolved incident " + key);
                        events.put(key, job);
                    }
                }

                for (JSONObject log : logList.values()) {
                    int id = log.getInt(JsonData.ANSWER_INCIDENT_ID);
                    Log.d("AlerteVoirie_PM", "key bug " + id);
                    JSONObject jsonObject = events.get(id);
                    if (jsonObject != null) {
                        String json = jsonObject.toString();
                        JSONObject job = new JSONObject(json);
                        job.put(JsonData.PARAM_INCIDENT_DATE, log.getString(JsonData.PARAM_INCIDENT_DATE));
                        items.put(job);

                        if (JsonData.PARAM_UPDATE_INCIDENT_INVALID.equals(log.getString(JsonData.PARAM_STATUS))
                                || JsonData.PARAM_UPDATE_INCIDENT_RESOLVED
                                        .equals(log.getString(JsonData.PARAM_STATUS))) {
                            lock.add(id);
                        }
                    }
                }

                setListAdapter(new MagicAdapter(this, items, R.layout.cell_report,
                        new String[] { JsonData.PARAM_INCIDENT_DESCRIPTION, JsonData.PARAM_INCIDENT_ADDRESS },
                        new int[] { R.id.TextView_title, R.id.TextView_text }, null));
            }

        }

    } catch (JSONException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : ", e);
    } catch (ClassCastException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : CLasscastException", e);
    } catch (NullPointerException e) {
        Log.e(Constants.PROJECT_TAG, "error in onRequestcompleted : NullPointerException", e);
    } finally {

        if (requestCode == AVService.REQUEST_JSON)
            dismissDialog(DIALOG_PROGRESS);
    }

}

From source file:semanticsco.servicecomposition.ServiceDiscoverer.java

public List<Service> findServices() {

    //Initialize List "foundServices"
    this.foundServices = new LinkedList<>();

    try {//from   w  ww  . ja v a2 s .co  m

        RegistryInquiry jr = new RegistryInquiry();

        //Try to authenticate user in service registry
        String authentication = jr.authenticate(juddiUser);

        //If user is authenticated
        if (authentication != null) {

            //Find services semantically annotated with corresponding functionality and add them to List "foundServices"
            foundServices.addAll(jr.findBusinessServicesByFunction((LinkedList<String>) this.fSearchValues));

            //Find services semantically annotated with corresponding input and add them to List "foundServices" (without duplicates)
            for (Iterator it = this.iSearchValues.iterator(); it.hasNext();) {

                String input = (String) it.next();
                LinkedList<String> inputs = new LinkedList<>();
                inputs.add(input);

                List<Service> auxList;
                auxList = jr.findBusinessServicesByData("input", (LinkedList<String>) inputs);
                for (Iterator i = auxList.iterator(); i.hasNext();) {

                    Service serv1 = (Service) i.next();

                    boolean alreadyContains = false;
                    for (Iterator j = foundServices.iterator(); j.hasNext();)
                        if (((Service) j.next()).getIdentifier().equals(serv1.getIdentifier()))
                            alreadyContains = true;

                    if (!alreadyContains)
                        foundServices.add(serv1);
                }
            }

            //Calculate semantic similarity
            this.setSemanticSimilarity("functionInput");

            //Sort List "foundServices" in descending order
            Collections.sort(foundServices, Collections.reverseOrder());

            //Logout from service registry
            jr.logout();

        }

    } catch (ConfigurationException | TransportException ex) {
    }

    return foundServices;
}

From source file:com.linkedin.pinot.core.query.aggregation.groupby.AggregationGroupByTrimmingService.java

@SuppressWarnings("unchecked")
private static Sorter getSorter(int trimSize, AggregationFunction aggregationFunction, boolean isComparable) {
    // This will cover both MIN and MINMV
    boolean minOrder = aggregationFunction instanceof MinAggregationFunction;

    if (isComparable) {
        if (minOrder) {
            return new ComparableSorter(trimSize, Collections.reverseOrder());
        } else {/*from ww  w. j a  v a 2 s .c  o m*/
            return new ComparableSorter(trimSize, new ComparableComparator());
        }
    } else {
        // Reverse the comparator so that keys are ordered in descending order
        if (minOrder) {
            return new NonComparableSorter(trimSize, new ComparableComparator(), aggregationFunction);
        } else {
            return new NonComparableSorter(trimSize, Collections.reverseOrder(), aggregationFunction);
        }
    }
}

From source file:models.data.providers.LogProvider.java

public static List<LogFile> getLogFilesInFolder(String folderPath) {

    List<String> fileNames = FileIoUtils.getFileNamesInFolder(folderPath);

    List<LogFile> logFiles = new ArrayList<LogFile>();

    for (String fileName : fileNames) {
        LogFile logFile = new LogFile(fileName);
        logFiles.add(logFile);//  w  w w  . j a  v  a  2 s  . co  m

        if (VarUtils.IN_DETAIL_DEBUG) {
            models.utils.LogUtils.printLogNormal(logFile.toString());
        }
    }
    Collections.sort(logFiles, Collections.reverseOrder());

    return logFiles;

}

From source file:org.mycontroller.standalone.api.BackupApi.java

/**
 * Call this method to get list of available backup files.
 * <p><b>Filter(s):</b>
 * <p>name - {@link List} of backup file names
 * <p><b>Page filter(s):</b>
 * <p>pageLimit - Set number of items per page
 * <p>page - Request page number/*from ww  w .j  a v a  2s.  co  m*/
 * <p>order - Set order. <b>Option:</b> asc, desc
 * <p>orderBy - column name for order. <b>Option:</b> name
 * @param filters Supports various filter options.
 * @return QueryResponse Contains input filter and response
 * @throws IOException throws when problem with backup location
 */
public QueryResponse getBackupFiles(HashMap<String, Object> filters) throws IOException {
    Query query = Query.get(filters);

    String locationCanonicalPath = McUtils.getDirectoryLocation(FileUtils
            .getFile(AppProperties.getInstance().getBackupSettings().getBackupLocation()).getCanonicalPath());

    if (FileUtils.getFile(locationCanonicalPath).exists()) {
        List<BackupFile> files = new ArrayList<BackupFile>();

        //Filters
        //Extension filter
        SuffixFileFilter extensionFilter = new SuffixFileFilter(BACKUP_FILE_SUFFIX_FILTER, IOCase.INSENSITIVE);

        //name filter
        IOFileFilter nameFileFilter = null;
        @SuppressWarnings("unchecked")
        List<String> fileNames = (List<String>) query.getFilters().get(KEY_NAME);
        if (fileNames == null) {
            fileNames = new ArrayList<String>();
        }
        fileNames.add(BRCommons.FILE_NAME_IDENTITY);

        if (fileNames != null && !fileNames.isEmpty()) {
            for (String fileName : fileNames) {
                if (nameFileFilter == null) {
                    nameFileFilter = FileFilterUtils
                            .and(new WildcardFileFilter("*" + fileName + "*", IOCase.INSENSITIVE));
                } else {
                    nameFileFilter = FileFilterUtils.and(nameFileFilter,
                            new WildcardFileFilter("*" + fileName + "*", IOCase.INSENSITIVE));
                }
            }
        }
        //Combine all filters
        IOFileFilter finalFileFilter = null;
        if (nameFileFilter != null) {
            finalFileFilter = FileFilterUtils.and(extensionFilter, nameFileFilter);
        } else {
            finalFileFilter = extensionFilter;
        }
        List<File> backupFiles = new ArrayList<File>(FileUtils
                .listFiles(FileUtils.getFile(locationCanonicalPath), finalFileFilter, TrueFileFilter.INSTANCE));
        query.setFilteredCount((long) backupFiles.size());
        //Get total items without filter
        query.setTotalItems((long) FileUtils
                .listFiles(FileUtils.getFile(locationCanonicalPath), extensionFilter, TrueFileFilter.INSTANCE)
                .size());
        int fileFrom;
        int fileTo;
        if (query.getPageLimit() == -1) {
            fileTo = backupFiles.size();
            fileFrom = 0;
        } else {
            fileFrom = query.getStartingRow().intValue();
            fileTo = (int) (query.getPage() * query.getPageLimit());
        }
        for (File backupFile : backupFiles) {
            String name = backupFile.getCanonicalPath().replace(locationCanonicalPath, "");
            files.add(BackupFile.builder().name(name).size(backupFile.length())
                    .timestamp(backupFile.lastModified()).canonicalPath(backupFile.getCanonicalPath()).build());
        }

        if (!files.isEmpty()) {
            //Do order reverse
            Collections.sort(files, Collections.reverseOrder());
            if (fileFrom < files.size()) {
                files = files.subList(Math.max(0, fileFrom), Math.min(fileTo, files.size()));
            }
        }
        return QueryResponse.builder().data(files).query(query).build();

    } else {
        throw new FileNotFoundException("File location not found: " + locationCanonicalPath);
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public Long[] getSnapshotIDs(String resourcePath) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();

    ResultSet results = null;//www. j  a va2 s  .  c  o  m
    PreparedStatement ps = null;
    try {
        ResourceIDImpl resourceIdImpl = resourceDAO.getResourceID(resourcePath);
        if (resourceIdImpl == null) {
            return new Long[0];
        }
        if (resourceIdImpl.isCollection()) {
            String sql = "SELECT REG_SNAPSHOT_ID FROM REG_SNAPSHOT WHERE "
                    + "REG_PATH_ID=? AND REG_RESOURCE_NAME IS NULL AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, resourceIdImpl.getPathID());
            ps.setInt(2, CurrentSession.getTenantId());
        } else {
            String sql = "SELECT REG_SNAPSHOT_ID FROM REG_SNAPSHOT WHERE "
                    + "REG_PATH_ID=? AND REG_RESOURCE_NAME=? AND REG_TENANT_ID=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, resourceIdImpl.getPathID());
            ps.setString(2, resourceIdImpl.getName());
            ps.setInt(3, CurrentSession.getTenantId());
        }

        results = ps.executeQuery();
        List<Long> snapshotIDs = new ArrayList<Long>();
        while (results.next()) {
            long snapshotNumber = results.getLong(DatabaseConstants.SNAPSHOT_ID_FIELD);
            snapshotIDs.add(snapshotNumber);
        }
        Collections.sort(snapshotIDs, Collections.reverseOrder());

        return snapshotIDs.toArray(new Long[snapshotIDs.size()]);

    } catch (SQLException e) {

        String msg = "Failed to get snapshot numbers of resource " + resourcePath + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (results != null) {
                    results.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:net.tsquery.LastEndpoint.java

@SuppressWarnings("unchecked")
private JSONObject PlotToStandardJSON(Plot plot, long tsFrom, long tsTo, int topN) {
    final JSONObject plotObject = new JSONObject();
    JSONArray seriesArray = new JSONArray();

    final TreeMap<Double, JSONObject> weightMap = new TreeMap<>(Collections.reverseOrder());

    for (DataPoints dataPoints : plot.getDataPoints()) {
        double weight = 0;
        JSONArray dataArray = new JSONArray();
        StringBuilder nameBuilder = new StringBuilder();

        nameBuilder.append(dataPoints.metricName()).append(": ");

        Map<String, String> tags = dataPoints.getTags();
        for (String s : tags.keySet()) {
            nameBuilder.append(String.format("%s=%s, ", s, tags.get(s)));
        }//w  w w  .  ja v  a  2  s. co  m
        nameBuilder.setLength(nameBuilder.length() - 2);

        JSONArray values = null;
        long latestTimestamp = 0;

        for (DataPoint point : dataPoints) {
            long timestamp = point.timestamp();
            if (!(timestamp < tsFrom || timestamp > tsTo) && timestamp > latestTimestamp) {
                latestTimestamp = timestamp;
                double dpValue = getValue(point);
                values = new JSONArray();
                values.add(timestamp * 1000);
                values.add(dpValue);
            }
        }
        dataArray.add(values);

        JSONObject series = new JSONObject();
        series.put("name", nameBuilder.toString());
        series.put("data", dataArray);

        while (weightMap.containsKey(weight))
            weight -= 0.00000001;

        weightMap.put(weight, series);
    }

    int counter = 0;
    for (Map.Entry<Double, JSONObject> entry : weightMap.entrySet()) {
        seriesArray.add(entry.getValue());

        ++counter;
        if ((topN > 0) && (counter >= topN))
            break;
    }

    plotObject.put("plot", seriesArray);

    return plotObject;
}

From source file:org.apache.hive.hcatalog.templeton.ListDelegator.java

public List<JobItemBean> getJobStatus(ArrayList<String> jobIds, String user, boolean showall, String jobId,
        int numRecords, boolean showDetails) throws IOException, InterruptedException {

    List<JobItemBean> detailList = new ArrayList<JobItemBean>();
    int currRecord = 0;

    // Sort the list as requested
    boolean isAscendingOrder = true;
    switch (appConf.getListJobsOrder()) {
    case lexicographicaldesc:
        Collections.sort(jobIds, Collections.reverseOrder());
        isAscendingOrder = false;// w  ww. j a  v  a2 s  .c o  m
        break;
    case lexicographicalasc:
    default:
        Collections.sort(jobIds);
        break;
    }

    for (String job : jobIds) {
        // If numRecords = -1, fetch all records.
        // Hence skip all the below checks when numRecords = -1.
        if (numRecords != -1) {
            // If currRecord >= numRecords, we have already fetched the top #numRecords
            if (currRecord >= numRecords) {
                break;
            } else if (jobId == null || jobId.trim().length() == 0) {
                currRecord++;
            }
            // If the current record needs to be returned based on the
            // filter conditions specified by the user, increment the counter
            else if (isAscendingOrder && job.compareTo(jobId) > 0
                    || !isAscendingOrder && job.compareTo(jobId) < 0) {
                currRecord++;
            }
            // The current record should not be included in the output detailList.
            else {
                continue;
            }
        }
        JobItemBean jobItem = new JobItemBean();
        jobItem.id = job;
        if (showDetails) {
            StatusDelegator sd = new StatusDelegator(appConf);
            try {
                jobItem.detail = sd.run(user, job, false);
            } catch (Exception ex) {
                /*
                 * if we could not get status for some reason, log it, and send empty status back with
                 * just the ID so that caller knows to even look in the log file
                 */
                LOG.info("Failed to get status detail for jobId='" + job + "'", ex);
                jobItem.detail = new QueueStatusBean(job, "Failed to retrieve status; see WebHCat logs");
            }
        }
        detailList.add(jobItem);
    }

    return detailList;
}

From source file:com.joeyturczak.jtscanner.utils.Utility.java

public static void deleteFilesOnDate(Context context, long dateInMillis) {
    long date = normalizeDate(dateInMillis);

    File externalDir = Environment.getExternalStorageDirectory();
    String externalDirPath = externalDir.getPath();

    File scannerDir = new File(externalDirPath + context.getString(R.string.file_directory));

    File[] files = scannerDir.listFiles();
    if (files != null) {
        Arrays.sort(files, Collections.reverseOrder());

        for (File file : files) {
            String fileName = file.getName();
            fileName = fileName.replace("JTS_", "");
            fileName = fileName.replace(".xls", "");

            long fileDate = Utility.dateToMilliseconds(fileName, "MM-dd-yyyy");

            if (fileDate == date) {
                file.delete();/*from  w w w .jav  a2 s.  c o  m*/
            }
        }
    }
}

From source file:org.kuali.kra.common.committee.lookup.CommitteeLookupableHelperServiceImplBase.java

@SuppressWarnings("unchecked")
protected List<? extends BusinessObject> getUniqueList(List<? extends BusinessObject> searchResults,
        Map<String, String> fieldValues) {

    List<CMT> uniqueResults = new ArrayList<CMT>();
    List<String> committeeIds = new ArrayList<String>();
    ((List<CMT>) searchResults).addAll(getUnapprovedCommittees(fieldValues));
    if (CollectionUtils.isNotEmpty(searchResults)) {
        Collections.sort((List<CMT>) searchResults, Collections.reverseOrder());
        for (CMT committee : (List<CMT>) searchResults) {
            if (!committeeIds.contains(committee.getCommitteeId())) {
                committee.getCommitteeChair();
                uniqueResults.add(committee);
                committeeIds.add(committee.getCommitteeId());
            }/*from w  w  w.  j ava2  s  .c o m*/
        }
    }
    return uniqueResults;
}