Example usage for java.util SortedSet size

List of usage examples for java.util SortedSet size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.projity.pm.task.Project.java

public int getRowHeight(SortedSet baseLines) {
    for (Iterator i = getTaskOutlineIterator(); i.hasNext();) {
        Task task = (Task) i.next();/*from  w  w w. ja va 2  s . c o  m*/
        int current = Snapshottable.CURRENT.intValue();
        for (int s = 0; s < Settings.numGanttBaselines(); s++) {
            if (s == current)
                continue;
            TaskSnapshot snapshot = (TaskSnapshot) task.getSnapshot(new Integer(s));
            if (snapshot != null)
                baseLines.add(new Integer(s));
        }
    }
    int num = (baseLines.size() == 0) ? 0 : (((Integer) baseLines.last()).intValue() + 1);
    int rowHeight = GraphicConfiguration.getInstance().getRowHeight()
            + num * GraphicConfiguration.getInstance().getBaselineHeight();
    return rowHeight;
}

From source file:mondrian.olap.Util.java

/**
 * Returns the intersection of two sorted sets. Does not modify either set.
 *
 * <p>Optimized for the case that both sets are {@link ArraySortedSet}.</p>
 *
 * @param set1 First set/*  www  .  java2  s .  c  om*/
 * @param set2 Second set
 * @return Intersection of the sets
 */
public static <E extends Comparable> SortedSet<E> intersect(SortedSet<E> set1, SortedSet<E> set2) {
    if (set1.isEmpty()) {
        return set1;
    }
    if (set2.isEmpty()) {
        return set2;
    }
    if (!(set1 instanceof ArraySortedSet) || !(set2 instanceof ArraySortedSet)) {
        final TreeSet<E> set = new TreeSet<E>(set1);
        set.retainAll(set2);
        return set;
    }
    final Comparable<?>[] result = new Comparable[Math.min(set1.size(), set2.size())];
    final Iterator<E> it1 = set1.iterator();
    final Iterator<E> it2 = set2.iterator();
    int i = 0;
    E e1 = it1.next();
    E e2 = it2.next();
    for (;;) {
        final int compare = e1.compareTo(e2);
        if (compare == 0) {
            result[i++] = e1;
            if (!it1.hasNext() || !it2.hasNext()) {
                break;
            }
            e1 = it1.next();
            e2 = it2.next();
        } else if (compare == 1) {
            if (!it2.hasNext()) {
                break;
            }
            e2 = it2.next();
        } else {
            if (!it1.hasNext()) {
                break;
            }
            e1 = it1.next();
        }
    }
    return new ArraySortedSet(result, 0, i);
}

From source file:github.daneren2005.dsub.service.OfflineMusicService.java

@Override
public List<Playlist> getPlaylists(boolean refresh, Context context, ProgressListener progressListener)
        throws Exception {
    List<Playlist> playlists = new ArrayList<Playlist>();
    File root = FileUtil.getPlaylistDirectory(context);
    String lastServer = null;//from w  w w.ja  v  a2  s  . c  o m
    boolean removeServer = true;
    for (File folder : FileUtil.listFiles(root)) {
        if (folder.isDirectory()) {
            String server = folder.getName();
            SortedSet<File> fileList = FileUtil.listFiles(folder);
            for (File file : fileList) {
                if (FileUtil.isPlaylistFile(file)) {
                    String id = file.getName();
                    String filename = FileUtil.getBaseName(id);
                    String name = server + ": " + filename;
                    Playlist playlist = new Playlist(server, name);
                    playlist.setComment(filename);

                    Reader reader = null;
                    BufferedReader buffer = null;
                    int songCount = 0;
                    try {
                        reader = new FileReader(file);
                        buffer = new BufferedReader(reader);

                        String line = buffer.readLine();
                        while ((line = buffer.readLine()) != null) {
                            // No matter what, end file can't have .complete in it
                            line = line.replace(".complete", "");
                            File entryFile = new File(line);

                            // Don't add file to playlist if it doesn't exist as cached or pinned!
                            File checkFile = entryFile;
                            if (!checkFile.exists()) {
                                // If normal file doens't exist, check if .complete version does
                                checkFile = new File(entryFile.getParent(),
                                        FileUtil.getBaseName(entryFile.getName()) + ".complete."
                                                + FileUtil.getExtension(entryFile.getName()));
                            }

                            String entryName = getName(entryFile);
                            if (checkFile.exists() && entryName != null) {
                                songCount++;
                            }
                        }

                        playlist.setSongCount(Integer.toString(songCount));
                    } catch (Exception e) {
                        Log.w(TAG, "Failed to count songs in playlist", e);
                    } finally {
                        Util.close(buffer);
                        Util.close(reader);
                    }

                    if (songCount > 0) {
                        playlists.add(playlist);
                    }
                }
            }

            if (!server.equals(lastServer) && fileList.size() > 0) {
                if (lastServer != null) {
                    removeServer = false;
                }
                lastServer = server;
            }
        } else {
            // Delete legacy playlist files
            try {
                folder.delete();
            } catch (Exception e) {
                Log.w(TAG, "Failed to delete old playlist file: " + folder.getName());
            }
        }
    }

    if (removeServer) {
        for (Playlist playlist : playlists) {
            playlist.setName(playlist.getName().substring(playlist.getId().length() + 2));
        }
    }
    return playlists;
}

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

public ModuleInfo addModule(HttpServletRequest request, CompanyInfo company)
        throws ObjectNotFoundException, DisallowedException {
    if (company == null) {
        company = this.authManager.getCompanyForLoggedInUser(request);
    }/*from   ww w  . ja  v a  2  s.co m*/
    // Make sure module name is unique
    String baseModuleName = "New Module";
    String moduleName = baseModuleName;
    SortedSet<ModuleInfo> modules = company.getModules();
    Set<String> existingModuleNames = new HashSet<String>();
    int indexNumber = 0;
    for (ModuleInfo existingModule : modules) {
        existingModuleNames.add(existingModule.getModuleName());
    }
    if (modules.size() > 0) {
        ModuleInfo lastModule = modules.last();
        indexNumber = lastModule.getIndexNumber() + 10;
    } else {
        indexNumber = 10;
    }
    int moduleCount = 0;
    while (existingModuleNames.contains(moduleName)) {
        moduleCount++;
        moduleName = baseModuleName + " " + String.valueOf(moduleCount);
    }
    ModuleInfo newModule = new Module(moduleName, "actions/go-home.png", indexNumber);
    newModule.setColour("blue");
    HibernateUtil.currentSession().save(newModule);
    HibernateUtil.activateObject(company);
    company.addModule(newModule);
    UsageLogger usageLogger = new UsageLogger(this.relationalDataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logReportSchemaChange(user, null, AppAction.ADD_MODULE, newModule.getModuleName());
    UsageLogger.startLoggingThread(usageLogger);
    return newModule;
}

From source file:net.sf.jasperreports.engine.util.JRApiWriter.java

/**
 * Writes out the contents of a series colors block for a chart.  Assumes the caller
 * has already written the <code>&lt;seriesColors&gt;</code> tag.
 *
 * @param seriesColors the colors to write
 *///from   w ww .j  a  va  2s  .  c o m
private void writeSeriesColors(SortedSet<JRSeriesColor> seriesColors, String parentName) {
    if (seriesColors == null || seriesColors.size() == 0) {
        return;
    }
    //FIXME why do we need an array?
    JRSeriesColor[] colors = seriesColors.toArray(new JRSeriesColor[seriesColors.size()]);
    for (int i = 0; i < colors.length; i++) {
        String seriesColorName = parentName + "SeriesColor" + i;
        write("JRBaseSeriesColor " + seriesColorName + " = new JRBaseSeriesColor(" + colors[i].getSeriesOrder()
                + ", {0});\n", colors[i].getColor());
        write(parentName + ".addSeriesColor(" + seriesColorName + ");\n");
        flush();
    }
}

From source file:org.apache.flume.channel.file.Log.java

/**
 * Write the current checkpoint object and then swap objects so that
 * the next checkpoint occurs on the other checkpoint directory.
 *
 * Synchronization is not required because this method acquires a
 * write lock. So this method gets exclusive access to all the
 * data structures this method accesses.
 * @param force  a flag to force the writing of checkpoint
 * @throws IOException if we are unable to write the checkpoint out to disk
 *///from  ww w  .  j  a va  2s.c om
private Boolean writeCheckpoint(Boolean force) throws Exception {
    boolean checkpointCompleted = false;
    long usableSpace = checkpointDir.getUsableSpace();
    if (usableSpace <= minimumRequiredSpace) {
        throw new IOException("Usable space exhaused, only " + usableSpace + " bytes remaining, required "
                + minimumRequiredSpace + " bytes");
    }
    boolean lockAcquired = tryLockExclusive();
    if (!lockAcquired) {
        return false;
    }
    SortedSet<Integer> logFileRefCountsAll = null, logFileRefCountsActive = null;
    try {
        if (queue.checkpoint(force)) {
            long logWriteOrderID = queue.getLogWriteOrderID();

            //Since the active files might also be in the queue's fileIDs,
            //we need to either move each one to a new set or remove each one
            //as we do here. Otherwise we cannot make sure every element in
            //fileID set from the queue have been updated.
            //Since clone is smarter than insert, better to make
            //a copy of the set first so that we can use it later.
            logFileRefCountsAll = queue.getFileIDs();
            logFileRefCountsActive = new TreeSet<Integer>(logFileRefCountsAll);

            int numFiles = logFiles.length();
            for (int i = 0; i < numFiles; i++) {
                LogFile.Writer logWriter = logFiles.get(i);
                int logFileID = logWriter.getLogFileID();
                File logFile = logWriter.getFile();
                LogFile.MetaDataWriter writer = LogFileFactory.getMetaDataWriter(logFile, logFileID);
                try {
                    writer.markCheckpoint(logWriter.position(), logWriteOrderID);
                } finally {
                    writer.close();
                }
                logFileRefCountsAll.remove(logFileID);
                LOGGER.info("Updated checkpoint for file: " + logFile + " position: " + logWriter.position()
                        + " logWriteOrderID: " + logWriteOrderID);
            }

            // Update any inactive data files as well
            Iterator<Integer> idIterator = logFileRefCountsAll.iterator();
            while (idIterator.hasNext()) {
                int id = idIterator.next();
                LogFile.RandomReader reader = idLogFileMap.remove(id);
                File file = reader.getFile();
                reader.close();
                LogFile.MetaDataWriter writer = LogFileFactory.getMetaDataWriter(file, id);
                try {
                    writer.markCheckpoint(logWriteOrderID);
                } finally {
                    writer.close();
                }
                reader = LogFileFactory.getRandomReader(file, encryptionKeyProvider);
                idLogFileMap.put(id, reader);
                LOGGER.debug("Updated checkpoint for file: " + file + "logWriteOrderID " + logWriteOrderID);
                idIterator.remove();
            }
            Preconditions.checkState(logFileRefCountsAll.size() == 0,
                    "Could not update all data file timestamps: " + logFileRefCountsAll);
            //Add files from all log directories
            for (int index = 0; index < logDirs.length; index++) {
                logFileRefCountsActive.add(logFiles.get(index).getLogFileID());
            }
            checkpointCompleted = true;
        }
    } finally {
        unlockExclusive();
    }
    //Do the deletes outside the checkpointWriterLock
    //Delete logic is expensive.
    if (open && checkpointCompleted) {
        removeOldLogs(logFileRefCountsActive);
    }
    //Since the exception is not caught, this will not be returned if
    //an exception is thrown from the try.
    return true;
}

From source file:org.sakaiproject.content.tool.ListItem.java

protected void captureAccess(ParameterParser params, String index) {
    String access_mode = params.getString("access_mode" + index);

    if (access_mode == null || AccessMode.GROUPED.toString().equals(access_mode)) {
        // we inherit more than one group and must check whether group access changes at this item
        String[] access_groups = params.getStrings("access_groups" + index);

        SortedSet<String> new_groups = new TreeSet<String>();
        if (access_groups != null) {
            new_groups.addAll(Arrays.asList(access_groups));
        }//ww  w.  j  a v a2 s . co m
        SortedSet<String> new_group_refs = convertToRefs(new_groups);

        Collection inh_grps = getInheritedGroupRefs();
        boolean groups_are_inherited = (new_group_refs.size() == inh_grps.size())
                && inh_grps.containsAll(new_group_refs);

        if (groups_are_inherited) {
            new_groups.clear();
            setGroupsById(new_groups);
            setAccessMode(AccessMode.INHERITED);
        } else {
            setGroupsById(new_groups);
            setAccessMode(AccessMode.GROUPED);
        }

        setPubview(false);
    } else if (ResourcesAction.PUBLIC_ACCESS.equals(access_mode)) {
        if (!isPubviewInherited()) {
            setPubview(true);
            setAccessMode(AccessMode.INHERITED);
        }
    } else if (AccessMode.INHERITED.toString().equals(access_mode)) {
        captureAccessRoles(params, index);
        setAccessMode(AccessMode.INHERITED);
        this.groups.clear();
    }
}

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   w  w  w  . ja  v a  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

/**
 * Test whether field can legally be removed from a table
 * //  w w  w  .  ja  v a2 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: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);/*  w w  w.  j ava 2s .  co  m*/
        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);
    }
}