Example usage for java.util List sort

List of usage examples for java.util List sort

Introduction

In this page you can find the example usage for java.util List sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
default void sort(Comparator<? super E> c) 

Source Link

Document

Sorts this list according to the order induced by the specified Comparator .

Usage

From source file:org.wso2.carbon.apimgt.rest.api.store.v1.impl.SubscriptionsApiServiceImpl.java

/**
 * Get all subscriptions that are of user or shared subscriptions of the user's group.
 * <p/>/*from   w w w .ja va2  s  . co  m*/
 * If apiId is specified this will return the subscribed applications of that api
 * If application id is specified this will return the api subscriptions of that application
 *
 * @param apiId         api identifier
 * @param applicationId application identifier
 * @param offset        starting index of the subscription list
 * @param limit         max num of subscriptions returned
 * @param ifNoneMatch   If-None-Match header value
 * @return matched subscriptions as a list of SubscriptionDTOs
 */
@Override
public Response subscriptionsGet(String apiId, String applicationId, String apiType, Integer offset,
        Integer limit, String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    Subscriber subscriber = new Subscriber(username);
    Set<SubscribedAPI> subscriptions;
    List<SubscribedAPI> subscribedAPIList = new ArrayList<>();

    //pre-processing
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;

    // currently groupId is taken from the user so that groupId coming as a query parameter is not honored.
    // As a improvement, we can check admin privileges of the user and honor groupId.
    String groupId = RestApiUtil.getLoggedInUserGroupId();

    try {
        APIConsumer apiConsumer = RestApiUtil.getConsumer(username);
        SubscriptionListDTO subscriptionListDTO;
        if (!StringUtils.isEmpty(apiId)) {
            // todo : FIX properly, need to done properly with backend side pagination. 
            // todo : getSubscribedIdentifiers() method should NOT be used. Appears to be too slow. 

            // This will fail with an authorization failed exception if user does not have permission to access the API
            API api = apiConsumer.getLightweightAPIByUUID(apiId, tenantDomain);
            subscriptions = apiConsumer.getSubscribedIdentifiers(subscriber, api.getId(), groupId);
            //sort by application name
            subscribedAPIList.addAll(subscriptions);
            subscribedAPIList.sort(Comparator.comparing(o -> o.getApplication().getName()));

            subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit,
                    offset);

            return Response.ok().entity(subscriptionListDTO).build();
        } else if (!StringUtils.isEmpty(applicationId)) {
            Application application = apiConsumer.getApplicationByUUID(applicationId);

            if (application == null) {
                RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId,
                        log);
                return null;
            }

            if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId,
                        log);
            }

            subscriptions = apiConsumer.getPaginatedSubscribedAPIs(subscriber, application.getName(), offset,
                    limit, groupId);
            subscribedAPIList.addAll(subscriptions);

            subscriptionListDTO = SubscriptionMappingUtil.fromSubscriptionListToDTO(subscribedAPIList, limit,
                    offset);
            return Response.ok().entity(subscriptionListDTO).build();

        } else {
            //neither apiId nor applicationId is given
            RestApiUtil.handleBadRequest("Either applicationId or apiId should be available", log);
            return null;
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Error while getting subscriptions of the user " + username,
                    e, log);
        }
    }
    return null;
}

From source file:com.haulmont.cuba.gui.components.filter.addcondition.ConditionDescriptorsTreeBuilder.java

protected void recursivelyFillPropertyDescriptors(Node<AbstractConditionDescriptor> parentNode,
        int currentDepth) {
    currentDepth++;//from   w w w .j  a  v  a  2s .c  o m
    List<AbstractConditionDescriptor> descriptors = new ArrayList<>();
    MetaClass filterMetaClass = filter.getDatasource().getMetaClass();
    String propertyId = parentNode.getData().getName();
    MetaPropertyPath mpp = filterMetaClass.getPropertyPath(propertyId);
    if (mpp == null) {
        throw new RuntimeException("Unable to find property " + propertyId);
    }

    MetaProperty metaProperty = mpp.getMetaProperty();
    if (metaProperty.getRange().isClass()
            && (metadataTools.getCrossDataStoreReferenceIdProperty(storeName, metaProperty) == null)) {
        MetaClass childMetaClass = metaProperty.getRange().asClass();
        for (MetaProperty property : childMetaClass.getProperties()) {
            if (isPropertyAllowed(childMetaClass, property)) {
                String propertyPath = mpp.toString() + "." + property.getName();
                if (excludedProperties.contains(propertyPath))
                    continue;

                PropertyConditionDescriptor childPropertyConditionDescriptor = new PropertyConditionDescriptor(
                        propertyPath, null, filter.getFrame().getMessagesPack(), filterComponentName,
                        filter.getDatasource());
                descriptors.add(childPropertyConditionDescriptor);
            }
        }
    }

    descriptors.sort(new ConditionDescriptorComparator());

    for (AbstractConditionDescriptor descriptor : descriptors) {
        Node<AbstractConditionDescriptor> newNode = new Node<>(descriptor);
        parentNode.addChild(newNode);
        if (currentDepth < hierarchyDepth) {
            recursivelyFillPropertyDescriptors(newNode, currentDepth);
        }
    }

    if (metaProperty.getRange().isClass()) {
        MetaClass childMetaClass = metaProperty.getRange().asClass();
        if (!dynamicAttributes.getAttributesForMetaClass(childMetaClass).isEmpty()) {
            DynamicAttributesConditionCreator descriptor = new DynamicAttributesConditionCreator(
                    filterComponentName, filter.getDatasource(), propertyId);
            Node<AbstractConditionDescriptor> newNode = new Node<>(descriptor);
            parentNode.addChild(newNode);
        }
    }
}

From source file:com.netflix.genie.web.services.impl.JobDirectoryServerServiceImpl.java

private void handleRequest(final URI baseUri, final String relativePath, final HttpServletRequest request,
        final HttpServletResponse response, final JobDirectoryManifest manifest, final URI jobDirectoryRoot)
        throws IOException, ServletException {
    log.debug("Handle request, baseUri: '{}', relpath: '{}', jobRootUri: '{}'", baseUri, relativePath,
            jobDirectoryRoot);//from  w  w w.  j  a  v  a2 s  .c o m
    final JobDirectoryManifest.ManifestEntry entry;
    final Optional<JobDirectoryManifest.ManifestEntry> entryOptional = manifest.getEntry(relativePath);
    if (entryOptional.isPresent()) {
        entry = entryOptional.get();
    } else {
        log.error("No such entry in job manifest: {}", relativePath);
        response.sendError(HttpStatus.NOT_FOUND.value(), "Not found: " + relativePath);
        return;
    }

    if (entry.isDirectory()) {
        // For now maintain the V3 structure
        // TODO: Once we determine what we want for V4 use v3/v4 flags or some way to differentiate
        // TODO: there's no unit test covering this section
        final DefaultDirectoryWriter.Directory directory = new DefaultDirectoryWriter.Directory();
        final List<DefaultDirectoryWriter.Entry> files = Lists.newArrayList();
        final List<DefaultDirectoryWriter.Entry> directories = Lists.newArrayList();
        try {
            entry.getParent().ifPresent(parentPath -> {
                final JobDirectoryManifest.ManifestEntry parentEntry = manifest.getEntry(parentPath)
                        .orElseThrow(IllegalArgumentException::new);
                directory.setParent(createEntry(parentEntry, baseUri));
            });

            for (final String childPath : entry.getChildren()) {
                final JobDirectoryManifest.ManifestEntry childEntry = manifest.getEntry(childPath)
                        .orElseThrow(IllegalArgumentException::new);

                if (childEntry.isDirectory()) {
                    directories.add(this.createEntry(childEntry, baseUri));
                } else {
                    files.add(this.createEntry(childEntry, baseUri));
                }
            }
        } catch (final IllegalArgumentException iae) {
            log.error("Encountered unexpected problem traversing the manifest for directory entry {}", entry,
                    iae);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return;
        }

        directories.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
        files.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));

        directory.setDirectories(directories);
        directory.setFiles(files);

        final String accept = request.getHeader(HttpHeaders.ACCEPT);
        if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response.getOutputStream().write(DefaultDirectoryWriter.directoryToHTML(entry.getName(), directory)
                    .getBytes(StandardCharsets.UTF_8));
        } else {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            GenieObjectMapper.getMapper().writeValue(response.getOutputStream(), directory);
        }
    } else {
        final URI location = jobDirectoryRoot.resolve(entry.getPath());
        log.debug("Get resource: {}", location);
        final Resource jobResource = this.resourceLoader.getResource(location.toString());
        // Every file really should have a media type but if not use text/plain
        final String mediaType = entry.getMimeType().orElse(MediaType.TEXT_PLAIN_VALUE);
        final ResourceHttpRequestHandler handler = this.genieResourceHandlerFactory.get(mediaType, jobResource);
        handler.handleRequest(request, response);
    }
}

From source file:com.grayfox.server.service.PoiService.java

@Transactional(readOnly = true)
public List<Recommendation> recommend(String accessToken, Location location, int radius, Locale locale) {
    Set<String> categories = new HashSet<>();
    List<Recommendation> recommendations = new ArrayList<>();
    if (accessToken != null) {
        LOGGER.debug("Adding personalized recommendations...");
        if (!credentialDao.exists(accessToken)) {
            LOGGER.warn("Not existing user attempting to retrive information");
            throw new ServiceException.Builder().messageKey("user.invalid.error").build();
        }//from www .  j  a  v a2  s.co m
        List<Recommendation> recommendationsByCategoriesLiked = recommendationDao
                .findNearestByCategoriesLiked(accessToken, location, radius, locale);
        List<Recommendation> recommendationsByCategoriesLikedByFriends = recommendationDao
                .findNearestByCategoriesLikedByFriends(accessToken, location, radius, locale);
        recommendations.addAll(recommendationsByCategoriesLiked);
        recommendations.addAll(recommendationsByCategoriesLikedByFriends);
    } else
        LOGGER.debug("Only global recommendations...");
    List<Recommendation> recommendationsByRating = recommendationDao.findNearestWithHighRating(location, radius,
            locale);
    recommendations.addAll(recommendationsByRating);
    for (Iterator<Recommendation> iterator = recommendations.iterator(); iterator.hasNext();) {
        Recommendation recommendation = iterator.next();
        for (Category category : recommendation.getPoi().getCategories()) {
            if (!categories.add(category.getFoursquareId())) {
                iterator.remove();
                break;
            }
        }
    }
    recommendations.sort((r1, r2) -> {
        double distance1 = distanceBetween(location, r1.getPoi().getLocation());
        double distance2 = distanceBetween(location, r2.getPoi().getLocation());
        return distance1 > distance2 ? 1 : distance1 < distance2 ? -1 : 0;
    });
    return recommendations;
}

From source file:net.sf.jabref.gui.openoffice.OOBibBase.java

/**
 * This method inserts a cite marker in the text for the given BibEntry,
 * and may refresh the bibliography.//from   w  ww.j  a v  a2  s  .  c  om
 * @param entries The entries to cite.
 * @param database The database the entry belongs to.
 * @param style The bibliography style we are using.
 * @param inParenthesis Indicates whether it is an in-text citation or a citation in parenthesis.
 *   This is not relevant if numbered citations are used.
 * @param withText Indicates whether this should be a normal citation (true) or an empty
 *   (invisible) citation (false).
 * @param sync Indicates whether the reference list should be refreshed.
 * @throws Exception
 */
public void insertEntry(List<BibEntry> entries, BibDatabase database, List<BibDatabase> allBases,
        OOBibStyle style, boolean inParenthesis, boolean withText, String pageInfo, boolean sync)
        throws Exception {

    try {

        XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();

        if (entries.size() > 1) {
            if (style.getBooleanCitProperty(OOBibStyle.MULTI_CITE_CHRONOLOGICAL)) {
                entries.sort(yearAuthorTitleComparator);
            } else {
                entries.sort(entryComparator);
            }
        }

        String keyString = String.join(",",
                entries.stream().map(BibEntry::getCiteKey).collect(Collectors.toList()));
        // Insert bookmark:
        String bName = getUniqueReferenceMarkName(keyString,
                withText ? inParenthesis ? OOBibBase.AUTHORYEAR_PAR : OOBibBase.AUTHORYEAR_INTEXT
                        : OOBibBase.INVISIBLE_CIT);

        // If we should store metadata for page info, do that now:
        if (pageInfo != null) {
            LOGGER.info("Storing page info: " + pageInfo);
            setCustomProperty(bName, pageInfo);
        }

        xViewCursor.getText().insertString(xViewCursor, " ", false);
        if (style.isFormatCitations()) {
            XPropertySet xCursorProps = UnoRuntime.queryInterface(XPropertySet.class, xViewCursor);
            String charStyle = style.getCitationCharacterFormat();
            try {
                xCursorProps.setPropertyValue(CHAR_STYLE_NAME, charStyle);
            } catch (UnknownPropertyException | PropertyVetoException | IllegalArgumentException
                    | WrappedTargetException ex) {
                // Setting the character format failed, so we throw an exception that
                // will result in an error message for the user. Before that,
                // delete the space we inserted:
                xViewCursor.goLeft((short) 1, true);
                xViewCursor.setString("");
                throw new UndefinedCharacterFormatException(charStyle);
            }
        }
        xViewCursor.goLeft((short) 1, false);
        Map<BibEntry, BibDatabase> databaseMap = new HashMap<>();
        for (BibEntry entry : entries) {
            databaseMap.put(entry, database);
        }
        String citeText = style.isNumberEntries() ? "-"
                : style.getCitationMarker(entries, databaseMap, inParenthesis, null, null);
        insertReferenceMark(bName, citeText, xViewCursor, withText, style);

        xViewCursor.collapseToEnd();
        xViewCursor.goRight((short) 1, false);

        XTextRange position = xViewCursor.getEnd();

        if (sync) {
            // To account for numbering and for uniqiefiers, we must refresh the cite markers:
            updateSortedReferenceMarks();
            refreshCiteMarkers(allBases, style);

            // Insert it at the current position:
            rebuildBibTextSection(allBases, style);
        }

        // Go back to the relevant position:
        xViewCursor.gotoRange(position, false);
    } catch (DisposedException ex) {
        // We need to catch this one here because the OpenOfficePanel class is
        // loaded before connection, and therefore cannot directly reference
        // or catch a DisposedException (which is in a OO jar file).
        throw new ConnectionLostException(ex.getMessage());
    }
}

From source file:org.phoenicis.repository.types.LocalRepository.java

private List<TypeDTO> fetchTypes(File[] typeDirectories) {
    final List<TypeDTO> results = new ArrayList<>();

    for (File typeDirectory : typeDirectories) {
        if (typeDirectory.isDirectory() && !typeDirectory.getName().startsWith(".")) {
            final File typeJson = new File(typeDirectory, "type.json");

            if (typeJson.exists()) {
                final TypeDTO jsonTypeDTO = unSerializeType(typeJson);
                final TypeDTO.Builder typeDTOBuilder = new TypeDTO.Builder(jsonTypeDTO);

                if (StringUtils.isBlank(jsonTypeDTO.getId())) {
                    if (!StringUtils.isBlank(jsonTypeDTO.getName())) {
                        typeDTOBuilder.withId(jsonTypeDTO.getName().replaceAll(ID_REGEX, ""));
                    } else {
                        typeDTOBuilder.withId(typeDirectory.getName().replaceAll(ID_REGEX, ""));
                    }// w  w  w.j a  v a 2 s  . c o  m
                }

                final File typeIconFile = new File(typeDirectory, ICON_NAME);
                if (typeIconFile.exists()) {
                    typeDTOBuilder.withIcon(typeIconFile.toURI());
                }

                typeDTOBuilder.withCategories(fetchCategories(typeDTOBuilder.getId(), typeDirectory));

                final TypeDTO type = typeDTOBuilder.build();
                results.add(type);
            }
        }
    }

    results.sort(Comparator.comparing(TypeDTO::getName));
    return results;
}

From source file:pcgen.gui2.facade.EquipmentSetFacadeImpl.java

@Override
public void quantityChanged(EquipmentListEvent e) {
    EquipmentFacade equipmentFacade = e.getEquipment();
    if (equippedItemsList.containsElement(equipmentFacade)) {
        int quantity = purchasedList.getQuantity(equipmentFacade)
                - equippedItemsList.getQuantity(equipmentFacade);
        if (quantity < 0) {
            if (Logging.isDebugMode()) {
                Logging.debugPrint("Currently equipped item " + equipmentFacade + " is being partially removed "
                        + quantity + " from " + equippedItemsList.getQuantity(equipmentFacade));
            }//from  www. j a v a  2 s. c  om

            int numStillToRemove = -1 * quantity;
            List<EquipNodeImpl> affectedList = findEquipmentNodes(equipmentFacade);
            affectedList.sort(new EquipLocImportantComparator()); // TODO: Custom sort order
            for (EquipNodeImpl equipNode : affectedList) {
                EquipSet eSet = charDisplay.getEquipSetByIdPath(equipNode.getIdPath());
                if (eSet != null) {
                    int numToRemove = Math.min(eSet.getQty().intValue(), numStillToRemove);
                    removeEquipment(equipNode, numToRemove);
                    numStillToRemove -= numToRemove;
                }

                if (numStillToRemove <= 0) {
                    return;
                }
            }

        }
    }
}

From source file:com.haulmont.cuba.gui.components.filter.addcondition.ConditionDescriptorsTreeBuilder.java

@Override
public Tree<AbstractConditionDescriptor> build() {
    Messages messages = AppBeans.get(Messages.class);
    String messagesPack = filter.getFrame().getMessagesPack();
    CollectionDatasource datasource = filter.getDatasource();

    Tree<AbstractConditionDescriptor> tree = new Tree<>();
    List<AbstractConditionDescriptor> propertyDescriptors = new ArrayList<>();
    List<AbstractConditionDescriptor> customDescriptors = new ArrayList<>();

    boolean propertiesExplicitlyDefined = false;
    if (filter.getXmlDescriptor() != null) {
        for (Element element : Dom4j.elements(filter.getXmlDescriptor())) {
            AbstractConditionDescriptor conditionDescriptor;
            if ("properties".equals(element.getName())) {
                addMultiplePropertyDescriptors(element, propertyDescriptors, filter);
                propertiesExplicitlyDefined = true;
            } else if ("property".equals(element.getName())) {
                conditionDescriptor = new PropertyConditionDescriptor(element, messagesPack,
                        filterComponentName, datasource);
                propertyDescriptors.add(conditionDescriptor);
                propertiesExplicitlyDefined = true;
            } else if ("custom".equals(element.getName())) {
                conditionDescriptor = new CustomConditionDescriptor(element, messagesPack, filterComponentName,
                        datasource);/*  w  w w .  java2  s .  co  m*/
                customDescriptors.add(conditionDescriptor);
                propertiesExplicitlyDefined = true;
            } else {
                throw new UnsupportedOperationException("Element not supported: " + element.getName());
            }
        }
    }

    if (!propertiesExplicitlyDefined) {
        addMultiplePropertyDescriptors(".*", "", propertyDescriptors, filter);
    }

    propertyDescriptors.sort(new ConditionDescriptorComparator());
    customDescriptors.sort(new ConditionDescriptorComparator());

    HeaderConditionDescriptor propertyHeaderDescriptor = new HeaderConditionDescriptor("propertyConditions",
            messages.getMainMessage("filter.addCondition.propertyConditions"), filterComponentName, datasource);
    HeaderConditionDescriptor customHeaderDescriptor = new HeaderConditionDescriptor("customConditions",
            messages.getMainMessage("filter.addCondition.customConditions"), filterComponentName, datasource);

    Node<AbstractConditionDescriptor> propertyHeaderNode = new Node<>(propertyHeaderDescriptor);
    Node<AbstractConditionDescriptor> customHeaderNode = new Node<>(customHeaderDescriptor);
    int currentDepth = 0;

    for (AbstractConditionDescriptor propertyDescriptor : propertyDescriptors) {
        MetaClass propertyDsMetaClass = propertyDescriptor.getDatasourceMetaClass();
        MetaPropertyPath propertyPath = propertyDsMetaClass.getPropertyPath(propertyDescriptor.getName());
        if (propertyPath == null) {
            log.error("Property path for {} of metaClass {} not found", propertyDescriptor.getName(),
                    propertyDsMetaClass.getName());
            continue;
        }

        MetaProperty metaProperty = propertyPath.getMetaProperty();
        MetaClass propertyEnclosingMetaClass = metadataTools.getPropertyEnclosingMetaClass(propertyPath);

        if (isPropertyAllowed(propertyEnclosingMetaClass, metaProperty)
                && !excludedProperties.contains(metaProperty.getName())) {
            Node<AbstractConditionDescriptor> node = new Node<>(propertyDescriptor);
            propertyHeaderNode.addChild(node);

            if (currentDepth < hierarchyDepth) {
                recursivelyFillPropertyDescriptors(node, currentDepth);
            }
        }
    }

    for (AbstractConditionDescriptor customDescriptor : customDescriptors) {
        Node<AbstractConditionDescriptor> node = new Node<>(customDescriptor);
        customHeaderNode.addChild(node);
    }

    List<Node<AbstractConditionDescriptor>> rootNodes = new ArrayList<>();
    rootNodes.add(propertyHeaderNode);
    if (!customDescriptors.isEmpty())
        rootNodes.add(customHeaderNode);

    if (!hideCustomConditions && security.isSpecificPermitted(CUSTOM_CONDITIONS_PERMISSION)) {
        rootNodes.add(new Node<>(new CustomConditionCreator(filterComponentName, datasource)));
    }

    if (!hideDynamicAttributes
            && !dynamicAttributes.getAttributesForMetaClass(datasource.getMetaClass()).isEmpty()) {
        rootNodes.add(new Node<>(new DynamicAttributesConditionCreator(filterComponentName, datasource, "")));
    }

    if (FtsConfigHelper.getEnabled()) {
        rootNodes.add(new Node<>(new FtsConditionDescriptor(filterComponentName, datasource)));
    }

    tree.setRootNodes(rootNodes);

    return tree;
}

From source file:org.openbase.bco.ontology.lib.manager.aggregation.DataAggregation.java

/**
 * Method is used to check and prepare the input information, which should be aggregated.
 *
 * @param unitConnectionTime is the time, which describes the connection time in milliseconds between unit and bco. Inconspicuous connection states should
 *                           have connection times equal the time frame of aggregation.
 * @param stateChanges are the state changes, which should be sorted ascending by including timestamp.
 * @return the sorted list of state changes.
 * @throws MultiException is thrown in case the verification of input information, which should be aggregated, is invalid.
 *///  w  ww. ja  v a 2 s .  co  m
private List<OntStateChangeBuf> preparingStateChanges(final long unitConnectionTime,
        final List<OntStateChangeBuf> stateChanges) throws MultiException {
    MultiException.ExceptionStack exceptionStack = null;

    try {
        if (unitConnectionTime > timeFrameMilliS) {
            throw new VerificationFailedException(
                    "The unitConnectionTime is bigger than the time frame of aggregation!");
        }
    } catch (VerificationFailedException e) {
        exceptionStack = MultiException.push(this, e, null);
    }
    try {
        if (stateChanges.isEmpty()) {
            throw new VerificationFailedException("The list of state changes is empty!");
        }
    } catch (VerificationFailedException e) {
        exceptionStack = MultiException.push(this, e, exceptionStack);
    }
    try {
        if (OffsetDateTime.parse(stateChanges.get(0).getTimestamp()).isAfter(dateTimeFrom)) {
            throw new VerificationFailedException(
                    "First state change is after the beginning aggregation time frame! No information about the state in "
                            + "the beginning time frame! First state change entry should be, chronological, before/equal the beginning time frame.");
        }
    } catch (VerificationFailedException e) {
        exceptionStack = MultiException.push(this, e, exceptionStack);
    }

    MultiException.checkAndThrow("Could not perform aggregation!", exceptionStack);

    // sort ascending (old to young)
    stateChanges.sort(Comparator.comparing(OntStateChangeBuf::getTimestamp));

    return stateChanges;
}

From source file:org.cbioportal.service.impl.GenesetHierarchyServiceImpl.java

private void calculateAndSetRepresentativeScoreAndPvalue(Geneset geneset,
        Map<String, List<GenesetMolecularData>> genesetScoresMap,
        Map<String, List<GenesetMolecularData>> genesetPvaluesMap, Integer percentile) {

    List<GenesetMolecularData> genesetScoreData = genesetScoresMap.get(geneset.getGenesetId());
    List<GenesetMolecularData> genesetPvalueData = genesetPvaluesMap.get(geneset.getGenesetId());

    //lists to hold the score and p-value pairs:
    List<ImmutablePair<Double, Double>> positiveScoresAndPvalues = new ArrayList<ImmutablePair<Double, Double>>();
    List<ImmutablePair<Double, Double>> negativeScoresAndPvalues = new ArrayList<ImmutablePair<Double, Double>>();

    //return the maximum absolute value found:
    double max = 0;
    double pvalueOfMax = 1;
    for (int i = 0; i < genesetScoreData.size(); i++) {
        String scoreString = genesetScoreData.get(i).getValue();
        String pvalueString = genesetPvalueData.get(i).getValue();

        if (!NumberUtils.isNumber(scoreString))
            continue;

        double score = Double.parseDouble(scoreString);
        double pvalue = 1.0;
        if (NumberUtils.isNumber(pvalueString))
            pvalue = Double.parseDouble(pvalueString);
        if (score >= 0) {
            positiveScoresAndPvalues.add(new ImmutablePair<Double, Double>(score, pvalue));
        } else {//from  w w  w  .  jav  a  2s  .co m
            negativeScoresAndPvalues.add(new ImmutablePair<Double, Double>(score, pvalue));
        }

        //keep track of max, in case percentile is null
        if (Math.abs(score) > Math.abs(max)) {
            max = score; //here no abs, since we want to get the raw score (could be negative)
            pvalueOfMax = pvalue;
        }
    }

    if (percentile == null) {
        geneset.setRepresentativeScore(max);
        geneset.setRepresentativePvalue(pvalueOfMax);
    } else {
        //sort scores (NB: .getLeft() returns the score, .getRight() returns the pvalue of each pair):
        positiveScoresAndPvalues.sort((ImmutablePair<Double, Double> o1,
                ImmutablePair<Double, Double> o2) -> Double.compare(o1.getLeft(), o2.getLeft()));
        //negative scores descending:
        negativeScoresAndPvalues.sort((ImmutablePair<Double, Double> o1,
                ImmutablePair<Double, Double> o2) -> Double.compare(o2.getLeft(), o1.getLeft()));

        //use percentile:
        ImmutablePair<Double, Double> representativePositiveScoreAndPvalue = new ImmutablePair<Double, Double>(
                0.0, 1.0);
        ImmutablePair<Double, Double> representativeNegativeScoreAndPvalue = new ImmutablePair<Double, Double>(
                0.0, 1.0);
        if (positiveScoresAndPvalues.size() > 0) {
            int idxPositiveScores = (int) Math.round(percentile * positiveScoresAndPvalues.size() / 100.0);
            if (idxPositiveScores == 0) { //(can happen when positiveScoresAndPvalues.size() is small)
                idxPositiveScores = 1;
            }
            representativePositiveScoreAndPvalue = positiveScoresAndPvalues.get(idxPositiveScores - 1);
        }
        if (negativeScoresAndPvalues.size() > 0) {
            int idxNegativeScores = (int) Math.round(percentile * negativeScoresAndPvalues.size() / 100.0);
            if (idxNegativeScores == 0) { //(can happen when positiveScoresAndPvalues.size() is small)
                idxNegativeScores = 1;
            }
            representativeNegativeScoreAndPvalue = negativeScoresAndPvalues.get(idxNegativeScores - 1);
        }

        //set best one:
        if (Math.abs(representativePositiveScoreAndPvalue.getLeft()) > Math
                .abs(representativeNegativeScoreAndPvalue.getLeft())) {
            geneset.setRepresentativeScore(representativePositiveScoreAndPvalue.getLeft());
            geneset.setRepresentativePvalue(representativePositiveScoreAndPvalue.getRight());
        } else {
            geneset.setRepresentativeScore(representativeNegativeScoreAndPvalue.getLeft());
            geneset.setRepresentativePvalue(representativeNegativeScoreAndPvalue.getRight());
        }
    }
}