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:eu.ggnet.dwoss.misc.op.listings.SalesListingProducerOperation.java

/**
 * Create a filejacket from a collection of lines that are filtered by configuration parameters.
 * Lines are filtered by brand and group.
 * <p>/*from ww w.j  av  a  2s. com*/
 * @param config configuration for filtering and file creation
 * @param all    lines to be considered
 * @return a filejacket from a collection of lines that are filtered by configuration parameters.
 */
private FileJacket createListing(ListingConfiguration config, Collection<StackedLine> all) {
    try {
        SortedSet<StackedLine> filtered = all.stream()
                .filter(line -> (config.getAllBrands().contains(line.getBrand())
                        && config.getGroups().contains(line.getGroup())))
                .collect(Collectors.toCollection(TreeSet::new));
        if (filtered.isEmpty())
            return null;
        L.info("Creating listing {} with {} lines", config.getName(), filtered.size());
        JRDataSource datasource = new JRBeanCollectionDataSource(filtered);
        JasperPrint jasperPrint = JasperFillManager.fillReport(config.getJasperTemplateFile(),
                config.toReportParamters(), datasource);
        byte[] pdfContend = JasperExportManager.exportReportToPdf(jasperPrint);
        return new FileJacket(config.getFilePrefix() + config.getName(), ".pdf", pdfContend);
    } catch (JRException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java

/**
 * Assert expand function preserves original visitorLimit.
 * //from w w w.  j a v a  2 s. c  o m
 * @throws Exception
 */
@Test
public void testExpandPreserveVisitorLimit() throws Exception {
    SimpleDateFormat dateTimeFormat = CommonDateOperations.getDateTimeFormat();
    Date startTime = dateTimeFormat.parse("20080601-0900");
    Date endTime = dateTimeFormat.parse("20080601-1500");

    AvailableBlock toExpand = AvailableBlockBuilder.createBlock(startTime, endTime, 10);

    SortedSet<AvailableBlock> expanded20 = AvailableBlockBuilder.expand(toExpand, 20);
    assertEquals(18, expanded20.size());
    Date currentStart = startTime;
    for (AvailableBlock block : expanded20) {
        assertEquals(20, block.getDurationInMinutes());
        assertEquals(10, block.getVisitorLimit());
        assertEquals(currentStart, block.getStartTime());
        currentStart = DateUtils.addMinutes(currentStart, 20);
        assertEquals(currentStart, block.getEndTime());
    }

    SortedSet<AvailableBlock> expanded40 = AvailableBlockBuilder.expand(toExpand, 40);
    assertEquals(9, expanded40.size());
    currentStart = startTime;
    for (AvailableBlock block : expanded40) {
        assertEquals(40, block.getDurationInMinutes());
        assertEquals(10, block.getVisitorLimit());
        assertEquals(currentStart, block.getStartTime());
        currentStart = DateUtils.addMinutes(currentStart, 40);
        assertEquals(currentStart, block.getEndTime());
    }

    SortedSet<AvailableBlock> expanded60 = AvailableBlockBuilder.expand(toExpand, 60);
    assertEquals(6, expanded60.size());
    currentStart = startTime;
    for (AvailableBlock block : expanded60) {
        assertEquals(60, block.getDurationInMinutes());
        assertEquals(10, block.getVisitorLimit());
        assertEquals(currentStart, block.getStartTime());
        currentStart = DateUtils.addMinutes(currentStart, 60);
        assertEquals(currentStart, block.getEndTime());
    }
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java

/**
 * Create a regular schedule and add a single 15 minute outlier.
 * Combine and verify the outlier is not lost.
 * /*from w  w w .ja  va  2 s.  c  o  m*/
 * @throws Exception
 */
@Test
public void testCombinePreservesOutliersSmall() throws Exception {
    SimpleDateFormat dateFormat = CommonDateOperations.getDateFormat();
    SimpleDateFormat timeFormat = CommonDateOperations.getDateTimeFormat();
    Set<AvailableBlock> regularSchedule = AvailableBlockBuilder.createBlocks("9:00 AM", "3:00 PM", "MWF",
            dateFormat.parse("20090309"), dateFormat.parse("20090313"));

    assertEquals(3, regularSchedule.size());
    SortedSet<AvailableBlock> regularScheduleExpanded = AvailableBlockBuilder.expand(regularSchedule, 15);
    assertEquals(72, regularScheduleExpanded.size());
    Set<AvailableBlock> assertCombine = AvailableBlockBuilder.combine(regularScheduleExpanded);
    assertEquals(3, assertCombine.size());

    AvailableBlock outlier = AvailableBlockBuilder.createBlock(timeFormat.parse("20090312-1200"),
            timeFormat.parse("20090312-1215"));

    regularScheduleExpanded.add(outlier);
    assertEquals(73, regularScheduleExpanded.size());

    Set<AvailableBlock> recombined = AvailableBlockBuilder.combine(regularScheduleExpanded);
    assertEquals(4, recombined.size());

    assertTrue(recombined.contains(outlier));
}

From source file:org.jasig.schedassist.model.AvailableBlockBuilderTest.java

/**
 * Create a regular schedule and add a single 15 minute outlier.
 * Combine and verify the outlier is not lost.
 * /*ww  w  . j  av a 2s  .  c om*/
 * @throws Exception
 */
@Test
public void testCombinePreservesOutliersLarge() throws Exception {
    SimpleDateFormat dateFormat = CommonDateOperations.getDateFormat();
    SimpleDateFormat timeFormat = CommonDateOperations.getDateTimeFormat();
    Set<AvailableBlock> regularSchedule = AvailableBlockBuilder.createBlocks("9:00 AM", "3:00 PM", "MWF",
            dateFormat.parse("20090101"), dateFormat.parse("20090601"));

    assertEquals(65, regularSchedule.size());
    SortedSet<AvailableBlock> regularScheduleExpanded = AvailableBlockBuilder.expand(regularSchedule, 15);
    assertEquals(1560, regularScheduleExpanded.size());
    Set<AvailableBlock> assertCombine = AvailableBlockBuilder.combine(regularScheduleExpanded);
    assertEquals(65, assertCombine.size());

    AvailableBlock outlier = AvailableBlockBuilder.createBlock(timeFormat.parse("20090312-1200"),
            timeFormat.parse("20090312-1215"));

    regularScheduleExpanded.add(outlier);
    assertEquals(1561, regularScheduleExpanded.size());

    Set<AvailableBlock> recombined = AvailableBlockBuilder.combine(regularScheduleExpanded);
    assertEquals(66, recombined.size());

    assertTrue(recombined.contains(outlier));
}

From source file:org.libreplan.web.orders.ManageOrderElementAdvancesModel.java

@Override
@Transactional(readOnly = true)/*from ww w .ja  v  a  2 s . co  m*/
public AdvanceMeasurement getLastAdvanceMeasurement(DirectAdvanceAssignment assignment) {
    if (assignment != null) {
        SortedSet<AdvanceMeasurement> advanceMeasurements = assignment.getAdvanceMeasurements();
        if (advanceMeasurements.size() > 0) {
            return advanceMeasurements.first();
        }
    }
    return null;
}

From source file:net.pms.dlna.protocolinfo.DeviceProtocolInfo.java

/**
 * Returns the number of elements of the given
 * {@link DeviceProtocolInfoSource} type. If this contains more than
 * {@link Integer#MAX_VALUE} elements, returns {@link Integer#MAX_VALUE}.
 *
 * @param type the {@link DeviceProtocolInfoSource} type to get the number
 *            of elements for.//  w w  w . ja  v  a2  s . c  o  m
 * @return The number of elements in the {@link Set} for {@code type}.
 */
public int size(DeviceProtocolInfoSource<?> type) {
    setsLock.readLock().lock();
    try {
        SortedSet<ProtocolInfo> set = protocolInfoSets.get(type);
        return set == null ? 0 : set.size();
    } finally {
        setsLock.readLock().unlock();
    }
}

From source file:org.zanata.client.commands.pull.RawPullCommand.java

@Override
public void run() throws IOException {
    PullCommand.logOptions(log, getOpts());
    if (getOpts().isDryRun()) {
        log.info("DRY RUN: no permanent changes will be made");
    }/*from   w  w  w  .  ja  va  2 s  . c  om*/

    log.warn("Using EXPERIMENTAL project type 'file'.");

    LocaleList locales = getOpts().getLocaleMapList();
    if (locales == null) {
        throw new ConfigException("no locales specified");
    }
    RawPullStrategy strat = new RawPullStrategy();
    strat.setPullOptions(getOpts());

    List<String> docNamesForModule = getQualifiedDocNamesForCurrentModuleFromServer();
    SortedSet<String> localDocNames = new TreeSet<String>(docNamesForModule);

    SortedSet<String> docsToPull = localDocNames;
    if (getOpts().getFromDoc() != null) {
        if (!localDocNames.contains(getOpts().getFromDoc())) {
            log.error("Document with id {} not found, unable to start pull from unknown document. Aborting.",
                    getOpts().getFromDoc());
            // FIXME should this be throwing an exception to properly abort?
            // need to see behaviour with modules
            return;
        }
        docsToPull = localDocNames.tailSet(getOpts().getFromDoc());
        int numSkippedDocs = localDocNames.size() - docsToPull.size();
        log.info("Skipping {} document(s) before {}.", numSkippedDocs, getOpts().getFromDoc());
    }

    // TODO compare docNamesForModule with localDocNames, offer to delete
    // obsolete translations from filesystem
    if (docsToPull.isEmpty()) {
        log.info("No documents in remote module: {}; nothing to do", getOpts().getCurrentModule());
        return;
    } else {
        log.info("Source documents on server:");
        for (String docName : localDocNames) {
            if (docsToPull.contains(docName)) {
                log.info("           {}", docName);
            } else {
                log.info("(to skip)  {}", docName);
            }
        }
    }

    log.info("Pulling {} of {} docs for this module from the server", docsToPull.size(), localDocNames.size());
    log.debug("Doc names: {}", localDocNames);

    PushPullType pullType = getOpts().getPullType();
    boolean pullSrc = pullType == PushPullType.Both || pullType == PushPullType.Source;
    boolean pullTarget = pullType == PushPullType.Both || pullType == PushPullType.Trans;

    if (needToGetStatistics(pullTarget)) {
        log.info(
                "Setting minimum document completion percentage may potentially increase the processing time.");
    }

    if (pullSrc) {
        log.warn("Pull Type set to '" + pullType
                + "': existing source-language files may be overwritten/deleted");
        confirmWithUser(
                "This will overwrite/delete any existing documents and translations in the above directories.\n");
    } else {
        confirmWithUser("This will overwrite/delete any existing translations in the above directory.\n");
    }

    Optional<Map<String, Map<LocaleId, TranslatedPercent>>> optionalStats = prepareStatsIfApplicable(pullTarget,
            locales);

    for (String qualifiedDocName : docsToPull) {
        // TODO add filtering by file type? e.g. pull all dtd documents
        // only.

        try {
            String localDocName = unqualifiedDocName(qualifiedDocName);

            if (pullSrc) {
                Response response;
                try {
                    response = fileResourceClient.downloadSourceFile(getOpts().getProj(),
                            getOpts().getProjectVersion(), FileResource.FILETYPE_RAW_SOURCE_DOCUMENT,
                            qualifiedDocName);
                    InputStream srcDoc = response.readEntity(InputStream.class);
                    if (srcDoc != null) {
                        try {
                            strat.writeSrcFile(localDocName, srcDoc);
                        } finally {
                            srcDoc.close();
                        }
                    }
                } catch (ResponseProcessingException e) {
                    if (e.getResponse().getStatus() == 404) {
                        log.warn("No source document file is available for [{}]. Skipping.", qualifiedDocName);
                    } else {
                        throw e;
                    }
                }
            }

            if (pullTarget) {
                String fileExtension;
                if (getOpts().getIncludeFuzzy()) {
                    fileExtension = FileResource.FILETYPE_TRANSLATED_APPROVED_AND_FUZZY;
                } else {
                    fileExtension = FileResource.FILETYPE_TRANSLATED_APPROVED;
                }

                List<LocaleId> skippedLocales = Lists.newArrayList();
                for (LocaleMapping locMapping : locales) {
                    LocaleId locale = new LocaleId(locMapping.getLocale());

                    if (shouldPullThisLocale(optionalStats, localDocName, locale)) {
                        pullDocForLocale(strat, qualifiedDocName, localDocName, fileExtension, locMapping,
                                locale);
                    } else {
                        skippedLocales.add(locale);
                    }

                }
                if (!skippedLocales.isEmpty()) {
                    log.info(
                            "Translation file for document {} for locales {} are skipped due to insufficient completed percentage",
                            localDocName, skippedLocales);
                }
            }
        } catch (IOException | RuntimeException e) {
            log.error(
                    "Operation failed: " + e.getMessage() + "\n\n"
                            + "    To retry from the last document, please add the option: {}\n",
                    getOpts().buildFromDocArgument(qualifiedDocName));
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:org.alfresco.reporting.db.DatabaseHelperBean.java

public void init() {
    if (logger.isInfoEnabled())
        logger.info("Starting init - " + reportingHelper.getDatabaseProvider());

    try {/*from  w ww . j  av a  2  s  .  c  om*/
        Map<String, String> p = getShowTables();
        SortedSet<String> ss = new TreeSet<String>(p.keySet());
        Iterator<String> keys = ss.iterator();
        if (ss.size() == 0) {
            logger.info("  No reporting tables to display...");
        } else {
            while (keys.hasNext()) {
                String key = (String) keys.next();
                logger.info("  " + key + " (" + p.get(key) + ")");
            }
        } // end if ss.size()         
    } catch (Exception e) {
        logger.warn("Reporting table information could not be retrieved!!");
        logger.fatal("Exception was: " + e.getMessage());
    }

}

From source file:net.pms.dlna.protocolinfo.DeviceProtocolInfo.java

/**
 * Returns the total number of elements of all
 * {@link DeviceProtocolInfoSource} types. If the result is greater than
 * {@link Integer#MAX_VALUE} elements, returns {@link Integer#MAX_VALUE}.
 *
 * @return The number of elements.//ww w .j ava  2  s. com
 */
public int size() {
    long result = 0;
    setsLock.readLock().lock();
    try {
        for (SortedSet<ProtocolInfo> set : protocolInfoSets.values()) {
            if (set != null) {
                result += set.size();
            }
        }
    } finally {
        setsLock.readLock().unlock();
    }
    return result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
}

From source file:net.sourceforge.seqware.common.metadata.MetadataWSTest.java

/**
 * Test of addWorkflow method, of class MetadataWS with a novoalign.ini.
 *///  www.  j  av  a2s. c  o  m
@Test
public void testAddNovoAlignWorkflow() {
    logger.info("addWorkflow");
    String name = "novoalign";
    String version = "0.13.6.2";
    String description = "Novoalign";
    String baseCommand = "java -jar /u/seqware/provisioned-bundles/sqwprod/"
            + "Workflow_Bundle_GATKRecalibrationAndVariantCalling_1.2.29_"
            + "SeqWare_0.10.0/GATKRecalibrationAndVariantCalling/1.x.x/lib/"
            + "seqware-pipeline-0.10.0.jar --plugin net.sourceforge.seqware."
            + "pipeline.plugins.WorkflowLauncher -- --bundle /u/seqware/"
            + "provisioned-bundles/sqwprod/Workflow_Bundle_GATKRecalibration"
            + "AndVariantCalling_1.2.29_SeqWare_0.10.0 --workflow GATK"
            + "RecalibrationAndVariantCalling --version 1.3.16";
    java.io.File configFile = null, templateFile = null;
    try {
        configFile = new java.io.File(MetadataWSTest.class.getResource("novoalign.ini").toURI());
        templateFile = new java.io.File(
                MetadataWSTest.class.getResource("GATKRecalibrationAndVariantCalling_1.3.16.ftl").toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    java.io.File provisionDir = new java.io.File("/u/seqware/provisioned-bundles"
            + "/sqwprod/Workflow_Bundle_GATKRecalibrationAndVariantCalling_" + "1.2.29_SeqWare_0.10.0/");
    int expResult = ReturnValue.SUCCESS;
    ReturnValue result = instance.addWorkflow(name, version, description, baseCommand,
            configFile.getAbsolutePath(), templateFile.getAbsolutePath(), provisionDir.getAbsolutePath(), true,
            "", false, null, null, null);
    Assert.assertEquals(expResult, result.getExitStatus());

    // test certain properties of the workflow parameters in relation to SEQWARE-1444
    String workflow_id = result.getAttribute("sw_accession");
    Workflow workflow = instance.getWorkflow(Integer.valueOf(workflow_id));
    Assert.assertTrue("workflow retrieved is invalid", workflow.getWorkflowId() == result.getReturnValue());
    SortedSet<WorkflowParam> workflowParams = instance.getWorkflowParams(workflow_id);
    Assert.assertTrue("invalid number of workflow params retrieved", workflowParams.size() == 34);
    // check out the values of some suspicious values
    for (WorkflowParam param : workflowParams) {
        if (param.getKey().equals("colorspace")) {
            Assert.assertTrue("colorspace invalid", param.getDefaultValue().equals("0"));
        } else if (param.getKey().equals("novoalign_r1_adapter_trim")) {
            Assert.assertTrue("novoalign_r1_adapter_trim invalid",
                    param.getDefaultValue().equals("-a AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAGACCG"));
        }
    }

}