Example usage for java.util SortedSet add

List of usage examples for java.util SortedSet add

Introduction

In this page you can find the example usage for java.util SortedSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public Map<TableInfo, Set<BaseReportInfo>> getViewableDataStores(HttpServletRequest request)
        throws CodingErrorException, ObjectNotFoundException {
    // Get the list of viewable tables and reports, for possible use in
    // replacing user input fields etc. with internal names
    // TODO: Shares common code with ViewMethods.getViewableReports/Tables,
    // refactor/*from  w w  w  .j a  v  a2 s.  com*/
    // Actually, if/when we add report privileges this will be obsolete
    // anyway
    Map<TableInfo, Set<BaseReportInfo>> availableDataStores = new HashMap<TableInfo, Set<BaseReportInfo>>();
    Set<TableInfo> companyTables = this.getAuthManager().getCompanyForLoggedInUser(request).getTables();
    AuthenticatorInfo authenticator = this.getAuthManager().getAuthenticator();
    for (TableInfo testTable : companyTables) {
        if (authenticator.loggedInUserAllowedTo(request, PrivilegeType.VIEW_TABLE_DATA, testTable)) {
            SortedSet<BaseReportInfo> allTableReports = testTable.getReports();
            // Strip down to the set of reports the user has privileges to
            // view
            SortedSet<BaseReportInfo> viewableReports = new TreeSet<BaseReportInfo>();
            for (BaseReportInfo report : allTableReports) {
                if (authenticator.loggedInUserAllowedToViewReport(request, report)) {
                    viewableReports.add(report);
                }
            }
            availableDataStores.put(testTable, Collections.unmodifiableSortedSet(viewableReports));
        }
    }
    return Collections.unmodifiableMap(availableDataStores);
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public SortedSet<TableInfo> getDirectlyDependentTables(TableInfo baseTable, HttpServletRequest request)
        throws ObjectNotFoundException {
    CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
    Set<TableInfo> tables = company.getTables();
    SortedSet<TableInfo> dependentTables = new TreeSet<TableInfo>();
    for (TableInfo table : tables) {
        if (table.equals(baseTable)) {
            continue;
        }//from w  w w.  j  av a 2  s . c o  m
        if (table.isDependentOn(baseTable)) {
            if (!dependentTables.contains(table)) {
                dependentTables.add(table);
            }
        }
    }
    return dependentTables;
}

From source file:org.jahia.modules.sociallib.SocialService.java

public SortedSet<JCRNodeWrapper> getActivities(JCRSessionWrapper jcrSessionWrapper, Set<String> usersPaths,
        long limit, long offset, String targetTreeRootPath, List<String> activityTypes, long startDate)
        throws RepositoryException {
    long timer = System.currentTimeMillis();
    SortedSet<JCRNodeWrapper> activitiesSet = new TreeSet<JCRNodeWrapper>(ACTIVITIES_COMPARATOR);
    StringBuilder statementBuilder = new StringBuilder().append("select * from [")
            .append(JNT_BASE_SOCIAL_ACTIVITY).append("] as uA where ");
    boolean addAnd = false;
    if (usersPaths != null && !usersPaths.isEmpty()) {
        int size = usersPaths.size();
        if (size > 1) {
            statementBuilder.append("(");
        }//from  ww  w .  ja  va  2s . c o  m
        Iterator<String> iterator = usersPaths.iterator();
        while (iterator.hasNext()) {
            statementBuilder.append("isdescendantnode(['").append(JCRContentUtils.sqlEncode(iterator.next()))
                    .append("'])");
            if (iterator.hasNext()) {
                statementBuilder.append(" or ");
            }
        }
        if (size > 1) {
            statementBuilder.append(")");
        }
        addAnd = true;
    }
    if (targetTreeRootPath != null) {
        String escapedPath = JCRContentUtils.sqlEncode(targetTreeRootPath);
        if (addAnd) {
            statementBuilder.append(" and ");
        }
        statementBuilder.append("(['j:targetNode'] ").append(escapedPath.indexOf('%') != -1 ? "like" : "=")
                .append(" '");
        statementBuilder.append(escapedPath).append("' or ['j:targetNode'] like '").append(escapedPath)
                .append("/%')");
        addAnd = true;
    }
    if (activityTypes != null && !activityTypes.isEmpty()) {
        if (addAnd) {
            statementBuilder.append(" and ");
        }
        int size = activityTypes.size();
        if (size > 1) {
            statementBuilder.append("(");
        }
        Iterator<String> iterator = activityTypes.iterator();
        while (iterator.hasNext()) {
            statementBuilder.append("['j:activityType'] = '").append(iterator.next()).append("'");
            if (iterator.hasNext()) {
                statementBuilder.append(" or ");
            }
        }
        if (size > 1) {
            statementBuilder.append(")");
        }
    }
    if (startDate > 0) {
        // do filtering by date
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(startDate);
        statementBuilder.append(" AND [jcr:created] >= '").append(ISO8601.format(c)).append("'");
    }
    statementBuilder.append(" order by [jcr:created] desc");
    String statement = statementBuilder.toString();
    QueryManager queryManager = jcrSessionWrapper.getWorkspace().getQueryManager();
    Query activitiesQuery = queryManager.createQuery(statement, Query.JCR_SQL2);
    activitiesQuery.setLimit(limit);
    activitiesQuery.setOffset(offset);
    QueryResult activitiesResult = activitiesQuery.execute();

    NodeIterator activitiesIterator = activitiesResult.getNodes();
    while (activitiesIterator.hasNext()) {
        JCRNodeWrapper activitiesNode = (JCRNodeWrapper) activitiesIterator.nextNode();
        activitiesSet.add(activitiesNode);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("{} activities retrieved in {} ms with query:\n{}",
                new Object[] { activitiesSet.size(), System.currentTimeMillis() - timer, statement });
    }

    return activitiesSet;
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

private SortedSet<TableInfo> getTablesIncludingReferences(BaseReportInfo report, HttpServletRequest request)
        throws ObjectNotFoundException, CantDoThatException, CodingErrorException {
    CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
    Set<TableInfo> allTables = company.getTables();
    SortedSet<TableInfo> tablesIncluding = new TreeSet<TableInfo>();
    TABLES_LOOP: for (TableInfo table : allTables) {
        for (BaseField field : table.getFields()) {
            if (field.getFieldCategory().equals(FieldCategory.REFERENCED_REPORT_DATA)) {
                BaseReportInfo referencedReport = ((ReferencedReportDataField) field).getReferencedReport();
                if (referencedReport.equals(report)) {
                    tablesIncluding.add(table);
                    continue TABLES_LOOP;
                }//w  w w. j a  v  a2 s  .c  o  m
            }
        }
    }
    return tablesIncluding;
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.protegeOwl.ProtegeOwl2LG.java

/**
 * This method associates OWLIndividuals and their properties: OWLDatatype
 * and OWLObject. Essentially, the is to tag each individual with the
 * property so that it helps in visualization and navigation.
 * //  w  w  w  .  ja  v a  2  s  .  co  m
 * @param lgInstance
 * @param rdfResource
 */
protected void resolveIndividualProperties(Entity lgInstance, RDFResource rdfResource) {

    // Temporary container for EMF properties.
    // Note: The EMF object does not enforce order. However, the XSD models
    // have required properties to occur in the XML in a specific order.
    // The comparator ensures a compatible order is maintained.
    SortedSet sortedProps = new TreeSet(propertyComparator);

    // Counter to use in property ID assignment to keep things unique.
    int i = 0;

    RDFSNamedClass myClass = null;
    for (Iterator userDefinedClasses = owlModel_.getUserDefinedOWLNamedClasses().iterator(); userDefinedClasses
            .hasNext();) {
        myClass = (RDFSNamedClass) userDefinedClasses.next();

        if (rdfResource.hasRDFType(myClass, false)) {
            String className = getRDFResourceLocalName(myClass);

            // Add this information as an instanceProperty.
            Property lgProp = CreateUtils.createProperty(generatePropertyID(++i), "isInstanceOf", className,
                    lgSupportedMappings_, null, null);
            sortedProps.add(lgProp);

            break;
        }
    }

    String rdfName = rdfResource.getLocalName();

    int presentationCount = 0;

    // Start with properties from RDF-defined property set ...
    for (Iterator props = rdfResource.getRDFProperties().iterator(); props.hasNext();) {
        RDFProperty prop = (RDFProperty) props.next();
        String propName = getRDFResourceLocalName(prop);
        // Do we care about this rdf property?
        if (isNoop(propName) || isNoopNamespace(propName))
            continue;

        // Do we have an EMF class match?
        String propClass = owlDatatypeName2lgPropClass_.get(propName);
        if (isNoop(propClass))
            continue;

        // Determine the EMF property name and datatype ...
        String lgDType = owlDatatypeName2lgDatatype_.get(propName);
        String lgLabel = owlDatatypeName2label_.get(propName);

        // Interpret RDF property value(s) ...
        for (Iterator values = rdfResource.getPropertyValues(prop).iterator(); values.hasNext();) {
            Object value = values.next();
            String resolvedText = resolveRDFText(rdfResource, value);

            // Special case for handling concept code and status, which are
            // set directly as attributes on the LexGrid instance.
            if (propName.matches(prefManager.getMatchPattern_conceptCode())) {
                lgInstance.setEntityCode(resolvedText);
            } else if (lgLabel != null && lgLabel.matches(prefManager.getMatchPattern_conceptStatus())) {
                lgInstance.setStatus(resolvedText);
                if (resolvedText.matches(prefManager.getMatchPattern_inactiveStatus()))
                    lgInstance.setIsActive(false);
            }
            // Otherwise instantiate a new EMF property and add the new
            // property to the list to eventually add to the instance.
            else {
                Property newProp = resolveProp(prop, propClass, generatePropertyID(++i), lgLabel, lgDType,
                        prop.getNamespace(), resolvedText, null);
                if (newProp.getValue() != null) {
                    sortedProps.add(newProp);
                    if (newProp instanceof Presentation)
                        presentationCount++;
                }
            }
        }
    }

    // Indicate whether the instance is primitive (no equivalent classes)
    // ...
    Collection values = rdfResource
            .getPropertyValues(rdfResource.getOWLModel().getOWLEquivalentClassProperty());
    if (values == null || values.isEmpty()) {
        Property lgProp = CreateUtils.createProperty(generatePropertyID(++i),
                prefManager.getPropertyName_primitive(), "true", lgSupportedMappings_, null, null);
        sortedProps.add(lgProp);
    } else {
        Property lgProp = CreateUtils.createProperty(generatePropertyID(++i),
                prefManager.getPropertyName_primitive(), "false", lgSupportedMappings_, null, null);
        sortedProps.add(lgProp);
    }

    // The LexGrid model requires a matching presentation for the entity
    // description. If no presentations exist, manufacture a default to
    // satisfy the requirement. If created, the name of the new property
    // is set to indicate where the value was found. Also support
    // explicit requests for "rdfs:label" as the preferred property.
    boolean generatePreferred = prefManager.getPrioritized_presentation_names().size() == 0
            || ProtegeOwl2LGConstants.PROPNAME_RDFS_LABEL
                    .equalsIgnoreCase(prefManager.getPrioritized_presentation_names().get(0))
            || presentationCount == 0;
    if (generatePreferred) {
        String entityDesc = lgInstance.getEntityDescription().getContent();
        sortedProps.add(CreateUtils.createPresentation(generatePropertyID(++i),
                rdfName.equals(entityDesc) ? ProtegeOwl2LGConstants.PROPNAME_RDF_ID
                        : ProtegeOwl2LGConstants.PROPNAME_RDFS_LABEL,
                entityDesc, true, lgSupportedMappings_, null, null));
    }

    // Track assignment of preferred presentation and definition.
    // For presentation, check to see if preference was set above.
    boolean assignedPreferredPres = generatePreferred;
    boolean assignedPreferredDefn = false;

    // Iterate through properties; stop when complete or if both a preferred
    // presentation and definition have been assigned ...
    for (Iterator<? extends Property> props = sortedProps.iterator(); props.hasNext()
            && !(assignedPreferredPres && assignedPreferredDefn);) {
        Object prop = props.next();
        if (!assignedPreferredPres && (prop instanceof Presentation)) {
            // Tag the property
            Presentation pres = (Presentation) prop;
            pres.setIsPreferred(Boolean.TRUE);
            // Entity description on instance should match preferred
            // presentation.
            EntityDescription ed = new EntityDescription();
            ed.setContent(((Presentation) prop).getValue().getContent());
            lgInstance.setEntityDescription(ed);
            // Remember that a preferred presentation was assigned ...
            assignedPreferredPres = true;
        }
        if (!assignedPreferredDefn && (prop instanceof Definition)) {
            // Tag the definition
            ((Definition) prop).setIsPreferred(Boolean.TRUE);
            // Remember that a preferred definition was assigned ...
            assignedPreferredDefn = true;
        }
    }

    // Now add all the sorted properties to the instance.
    for (Iterator<? extends Property> lgProps = sortedProps.iterator(); lgProps.hasNext();) {
        Property lgProp = (Property) lgProps.next();
        lgInstance.addAnyProperty(lgProp);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

String toJsonAdd1s(ParentChild data, SortedSet<String> children) throws JSONException {

    LinkedList<String> zips = new LinkedList<String>();
    Set<String> add1s = new HashSet<String>();
    Set<String> add2s = new HashSet<String>();

    boolean start = true;
    JSONObject pref = new JSONObject(data.getParents().getFirst());
    JSONObject city = new JSONObject(data.getParents().getLast());
    StringBuilder ret = new StringBuilder("{\"pref\":");

    pref.remove("yomi");
    ret.append(pref.toString());//  w w  w.j a  v a 2  s.  c om
    ret.append(",\"city\":");
    city.remove("yomi");
    city.remove("expiration");
    ret.append(city.toString());
    ret.append(",\"zips\":[");

    for (String json : data.getChildren()) {

        String add1 = new JSONObject(json).optString("add1", "");
        zips.add(json);
        if (add1s.add(add1)) {
            continue;
        }
        add2s.add(add1);
    }

    for (String json : zips) {

        JSONObject jo = new JSONObject(json);
        String add1 = jo.optString("add1", "");

        jo.remove("x0402");
        jo.remove("corp");
        jo.remove("add1Yomi");
        jo.remove("add2Yomi");
        jo.remove("corpYomi");

        if (add2s.contains(add1)) {

            if (!children.contains(add1)) {

                if (start) {
                    start = false;
                } else {
                    ret.append(",");
                }

                jo.remove("code");
                jo.remove("add2");
                jo.remove("note");
                jo.put("code", toHex(add1));
                ret.append(jo.toString());
                children.add(add1);
            }

        } else {

            if (start) {
                start = false;
            } else {
                ret.append(",");
            }

            String zip = jo.optString("code", "");
            jo.remove("code");
            jo.put("zip1", zip.substring(0, 3));
            jo.put("zip2", zip.substring(3));
            ret.append(jo.toString());
        }

    }

    return ret.append("]}").toString();
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

/**
 * Test whether field can legally be removed from a table
 * //w  w  w  .j a va2  s  . c om
 * @throws CantDoThatException
 *             Thrown if the field shouldn't be removed from it's parent
 *             table, with a message explaining why not
 */
private void removeFieldChecks(BaseField field, HttpServletRequest request)
        throws CantDoThatException, CodingErrorException, ObjectNotFoundException {
    // Don't allow deletion of the primary key
    if (field.equals(field.getTableContainingField().getPrimaryKey())) {
        throw new CantDoThatException("Can't delete the primary key field");
    }
    // Check the field isn't used in a relation
    SortedSet<TableInfo> relatedTables = new TreeSet<TableInfo>();
    CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
    Set<TableInfo> allTables = company.getTables();
    for (TableInfo testTable : allTables) {
        for (BaseField testField : testTable.getFields()) {
            if (testField instanceof RelationField) {
                RelationField testRelationField = (RelationField) testField;
                if (testRelationField.getDisplayField().equals(field)
                        || testRelationField.getRelatedField().equals(field)) {
                    relatedTables.add(testRelationField.getTableContainingField());
                }
            }
        }
    }
    if (relatedTables.size() > 0) {
        throw new CantDoThatException("The field " + field + " is used as a relation in the following tables: "
                + relatedTables + ". Please remove it from these tables first.");
    }
    // Check the field isn't used in any reports
    SortedSet<BaseReportInfo> reportsUsedIn = new TreeSet<BaseReportInfo>();
    for (TableInfo testTable : allTables) {
        for (BaseReportInfo testReport : testTable.getReports()) {
            // ignore default reports, those should be picked up by the
            // table checks above
            if (testReport.equals(testTable.getDefaultReport())) {
                continue;
            }
            for (ReportFieldInfo reportField : testReport.getReportFields()) {
                if (reportField.getBaseField().equals(field)) {
                    reportsUsedIn.add(testReport);
                } else if (reportField instanceof ReportCalcFieldInfo) {
                    String calcSQL = ((ReportCalcFieldInfo) reportField).getCalculationSQL(true);
                    if (calcSQL.contains(field.getInternalFieldName())) {
                        reportsUsedIn.add(testReport);
                    }
                }
            }
            if (testReport instanceof SimpleReportInfo) {
                SimpleReportInfo simpleTestReport = (SimpleReportInfo) testReport;
                for (ReportFilterInfo testReportFilter : simpleTestReport.getFilters()) {
                    BaseField filterField = null;
                    if (testReportFilter.isFilterFieldFromReport()) {
                        filterField = testReportFilter.getFilterReportField().getBaseField();
                    } else {
                        filterField = testReportFilter.getFilterBaseField();
                    }
                    if (filterField.equals(field)) {
                        reportsUsedIn.add(testReport);
                    }
                }
                for (JoinClauseInfo join : simpleTestReport.getJoins()) {
                    if (join.isLeftPartTable()) {
                        BaseField joinField = join.getLeftTableField();
                        if (joinField.equals(field)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                    if (join.isRightPartTable()) {
                        BaseField joinField = join.getRightTableField();
                        if (joinField.equals(field)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                }
            }
            ChartInfo reportSummary = testReport.getChart();
            for (ChartGroupingInfo grouping : reportSummary.getGroupings()) {
                BaseField groupingBaseField = grouping.getGroupingReportField().getBaseField();
                if (groupingBaseField.equals(field)) {
                    reportsUsedIn.add(testReport);
                }
            }
            for (ChartAggregateInfo summaryAggregate : reportSummary.getAggregateFunctions()) {
                BaseField aggregateBaseField = summaryAggregate.getReportField().getBaseField();
                if (aggregateBaseField.equals(field)) {
                    reportsUsedIn.add(testReport);
                }
                ReportFieldInfo secondaryAggregateField = summaryAggregate.getSecondaryReportField();
                if (secondaryAggregateField != null) {
                    aggregateBaseField = secondaryAggregateField.getBaseField();
                    if (aggregateBaseField.equals(field)) {
                        reportsUsedIn.add(testReport);
                    }
                }
            }
        }
    }
    if (reportsUsedIn.size() > 0) {
        String errorMessage = "The field " + field + " is used in the following reports: ";
        for (BaseReportInfo report : reportsUsedIn) {
            ModuleInfo reportModule = report.getModule();
            if (reportModule == null) {
                errorMessage += report.getParentTable() + "." + report + ", ";
            } else {
                errorMessage += reportModule + " > " + report + ", ";
            }
        }
        errorMessage = errorMessage.substring(0, errorMessage.length() - 2);
        errorMessage += ". Please remove it from fields, filters, calculations etc. in these reports before removing it from the table";
        throw new CantDoThatException(errorMessage);
    }
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

/**
 * Return a set of all reports that would have to be modified before
 * dropping the given report, i.e. those that join to this one
 * /* w w w.  j a v a 2  s  .  c om*/
 * TODO: some overlap between this and
 */
private SortedSet<BaseReportInfo> getDependentReports(SimpleReportInfo report, HttpServletRequest request)
        throws CantDoThatException, ObjectNotFoundException {
    CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
    Set<TableInfo> tables = company.getTables();
    SortedSet<BaseReportInfo> reportsUsedIn = new TreeSet<BaseReportInfo>();
    for (TableInfo table : tables) {
        for (BaseReportInfo testReport : table.getReports()) {
            // default reports won't have joins
            // and don't test for joins to self
            if (testReport.equals(testReport.getParentTable().getDefaultReport())
                    || testReport.equals(report)) {
                continue;
            }
            if (testReport instanceof SimpleReportInfo) {
                SimpleReportInfo simpleTestReport = (SimpleReportInfo) testReport;
                for (JoinClauseInfo join : simpleTestReport.getJoins()) {
                    if (!join.isLeftPartTable()) {
                        BaseReportInfo joinedReport = join.getLeftReportField().getParentReport();
                        if (joinedReport.equals(report)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                    if (!join.isRightPartTable()) {
                        BaseReportInfo joinedReport = join.getRightReportField().getParentReport();
                        if (joinedReport.equals(report)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                }
            }
        }
    }
    return reportsUsedIn;
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

private void cacheNodesBatch(List<Long> nodeIds) {
    int batchSize = 256;
    SortedSet<Long> batch = new TreeSet<Long>();
    for (Long nodeId : nodeIds) {
        batch.add(nodeId);//www.  j av a  2  s  .  c  om
        if (batch.size() >= batchSize) {
            // Preload
            List<Node> nodes = selectNodesByIds(batch);
            cacheNodesNoBatch(nodes);
            batch.clear();
        }
    }
    // Load any remaining nodes
    if (batch.size() > 0) {
        List<Node> nodes = selectNodesByIds(batch);
        cacheNodesNoBatch(nodes);
    }
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

/**
 * Loads the nodes into cache using batching.
 *//*from   ww  w  . j a va2 s .c  o m*/
private void cacheNodes(StoreRef storeRef, List<String> uuids) {
    StoreEntity store = getStoreNotNull(storeRef);
    Long storeId = store.getId();

    int batchSize = 256;
    SortedSet<String> batch = new TreeSet<String>();
    for (String uuid : uuids) {
        batch.add(uuid);
        if (batch.size() >= batchSize) {
            // Preload
            List<Node> nodes = selectNodesByUuids(storeId, batch);
            cacheNodesNoBatch(nodes);
            batch.clear();
        }
    }
    // Load any remaining nodes
    if (batch.size() > 0) {
        List<Node> nodes = selectNodesByUuids(storeId, batch);
        cacheNodesNoBatch(nodes);
    }
}