Example usage for com.google.common.collect Iterables size

List of usage examples for com.google.common.collect Iterables size

Introduction

In this page you can find the example usage for com.google.common.collect Iterables size.

Prototype

public static int size(Iterable<?> iterable) 

Source Link

Document

Returns the number of elements in iterable .

Usage

From source file:org.trancecode.xproc.step.XsltStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final Iterable<XdmNode> sourceDocuments = input.readNodes(XProcPorts.SOURCE);
    final XdmNode sourceDocument = Iterables.getFirst(sourceDocuments, null);

    final String providedOutputBaseUri = input.getOptionValue(XProcOptions.OUTPUT_BASE_URI);
    final URI outputBaseUri;
    if (providedOutputBaseUri != null && providedOutputBaseUri.length() > 0) {
        outputBaseUri = URI.create(providedOutputBaseUri);
    } else if (sourceDocument != null && sourceDocument.getBaseURI() != null
            && sourceDocument.getBaseURI().toString().length() > 0) {
        outputBaseUri = sourceDocument.getBaseURI();
    } else {//  ww  w . j a  v a2  s .  com
        outputBaseUri = input.getBaseUri();
    }
    assert outputBaseUri != null;
    LOG.trace("outputBaseUri = {}", outputBaseUri);

    final String version = input.getOptionValue(XProcOptions.VERSION, DEFAULT_VERSION);
    LOG.trace("version = {}", version);

    if (!SUPPORTED_VERSIONS.contains(version)) {
        throw XProcExceptions.xc0038(input.getStep().getLocation(), version);
    }

    if (version.equals("1.0") && Iterables.size(sourceDocuments) != 1) {
        throw XProcExceptions.xc0039(input.getLocation(), Iterables.size(sourceDocuments));
    }

    final XdmNode stylesheet = input.readNode(XProcPorts.STYLESHEET);
    assert stylesheet != null;

    final Processor processor = input.getPipelineContext().getProcessor();

    // TODO pipeline logging
    final XsltTransformer transformer;
    try {
        transformer = processor.newXsltCompiler().compile(stylesheet.asSource()).load();
        if (sourceDocument != null) {
            transformer.setInitialContextNode(sourceDocument);
        }
    } catch (final SaxonApiException e) {
        throw new PipelineException(e);
    }

    // TODO transformer.setMessageListener();
    final XdmDestination result = new XdmDestination();
    if (!outputBaseUri.toString().isEmpty()) {
        result.setBaseURI(outputBaseUri);
    }
    transformer.setDestination(result);
    transformer.getUnderlyingController().setBaseOutputURI(outputBaseUri.toString());

    final List<XdmNode> secondaryPortNodes = Lists.newArrayList();
    transformer.getUnderlyingController().setOutputURIResolver(new OutputURIResolver() {
        final Map<URI, XdmDestination> destinations = Maps.newHashMap();

        @Override
        public void close(final Result result) throws TransformerException {
            final URI uri = URI.create(result.getSystemId());
            assert destinations.containsKey(uri);
            final XdmDestination xdmResult = destinations.get(uri);
            LOG.trace("result base URI = {}", xdmResult.getXdmNode().getBaseURI());
            secondaryPortNodes.add(xdmResult.getXdmNode());
        }

        @Override
        public OutputURIResolver newInstance() {
            return this;
        }

        @Override
        public Result resolve(final String href, final String base) throws TransformerException {
            final URI uri = Uris.resolve(href, base);
            assert uri != null;
            LOG.debug("new result document: {}", uri);

            try {
                final XdmDestination xdmResult = new XdmDestination();
                xdmResult.setBaseURI(uri);
                destinations.put(uri, xdmResult);
                final Receiver receiver = xdmResult.getReceiver(processor.getUnderlyingConfiguration());
                receiver.setSystemId(uri.toString());

                return receiver;
            } catch (final SaxonApiException e) {
                throw new TransformerException(e);
            }
        }
    });

    final String initialMode = input.getOptionValue(XProcOptions.INITIAL_MODE, null);
    if (initialMode != null) {
        // FIXME does not handle namespaces
        try {
            transformer.setInitialMode(new QName(initialMode));
        } catch (IllegalArgumentException e) {
            throw XProcExceptions.xc0056(input.getLocation());
        }
    }

    final Map<QName, String> parameters = input.getParameters(XProcPorts.PARAMETERS);
    LOG.debug("parameters = {}", parameters);
    for (final Map.Entry<QName, String> parameter : parameters.entrySet()) {
        transformer.setParameter(parameter.getKey(), new XdmAtomicValue(parameter.getValue()));
    }

    final StringBuilder terminateMessage = new StringBuilder();
    transformer.setMessageListener((content, terminate, locator) -> {
        if (terminate) {
            LOG.trace("terminateMessage = {}", content);
            terminateMessage.append(content.toString());
        }

        // TODO use a message log
        System.err.println(content);
    });

    try {
        transformer.transform();
    } catch (final SaxonApiException e) {
        if (terminateMessage.length() > 0) {
            throw new PipelineException(terminateMessage.toString());
        }

        // TODO XProcException?
        throw new PipelineException(e);
    }

    output.writeNodes(XProcPorts.SECONDARY, secondaryPortNodes);
    output.writeNodes(XProcPorts.RESULT, result.getXdmNode());
}

From source file:com.ning.billing.invoice.calculator.InvoiceCalculatorUtils.java

private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(
        final Iterable<InvoiceItem> invoiceItems) {
    BigDecimal amountAdjusted = BigDecimal.ZERO;
    if (invoiceItems == null) {
        return amountAdjusted;
    }//from   w  w w .  jav  a 2s  .c o  m

    for (final InvoiceItem invoiceItem : invoiceItems) {
        final Iterable<InvoiceItem> otherInvoiceItems = Iterables.filter(invoiceItems,
                new Predicate<InvoiceItem>() {
                    @Override
                    public boolean apply(final InvoiceItem input) {
                        return !input.getId().equals(invoiceItem.getId());
                    }
                });

        if (InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType())
                && (Iterables.size(otherInvoiceItems) == 1
                        && InvoiceItemType.CBA_ADJ
                                .equals(otherInvoiceItems.iterator().next().getInvoiceItemType())
                        && otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId())
                        && otherInvoiceItems.iterator().next().getAmount()
                                .compareTo(invoiceItem.getAmount().negate()) == 0)) {
            amountAdjusted = amountAdjusted.add(invoiceItem.getAmount());
        }
    }
    return amountAdjusted.setScale(NUMBER_OF_DECIMALS, ROUNDING_METHOD);
}

From source file:org.apache.druid.indexing.common.task.MergeTaskBase.java

protected MergeTaskBase(final String id, final String dataSource, final List<DataSegment> segments,
        final @Nullable SegmentWriteOutMediumFactory segmentWriteOutMediumFactory,
        Map<String, Object> context) {
    super(//from w  ww .j ava  2  s.c o  m
            // _not_ the version, just something uniqueish
            id != null ? id
                    : StringUtils.format("merge_%s_%s", computeProcessingID(dataSource, segments),
                            DateTimes.nowUtc().toString()),
            dataSource, computeMergedInterval(segments), context);

    // Verify segment list is nonempty
    Preconditions.checkArgument(segments.size() > 0, "segments nonempty");
    // Verify segments are all in the correct datasource
    Preconditions.checkArgument(Iterables.size(Iterables.filter(segments, new Predicate<DataSegment>() {
        @Override
        public boolean apply(@Nullable DataSegment segment) {
            return segment == null || !segment.getDataSource().equalsIgnoreCase(dataSource);
        }
    })) == 0, "segments in the wrong datasource");
    verifyInputSegments(segments);

    this.segments = segments;
    this.segmentWriteOutMediumFactory = segmentWriteOutMediumFactory;
}

From source file:org.gradle.api.internal.plugins.UnixStartScriptGenerator.java

private String createJoinedDefaultJvmOpts(Iterable<String> defaultJvmOpts) {
    Iterable<String> quotedDefaultJvmOpts = Iterables.transform(defaultJvmOpts, new Function<String, String>() {
        public String apply(String jvmOpt) {
            //quote ', ", \, $. Probably not perfect. TODO: identify non-working cases, fail-fast on them
            jvmOpt = jvmOpt.replace("\\", "\\\\");
            jvmOpt = jvmOpt.replace("\"", "\\\"");
            jvmOpt = jvmOpt.replace("'", "'\"'\"'");
            jvmOpt = jvmOpt.replace("`", "'\"`\"'");
            jvmOpt = jvmOpt.replace("$", "\\$");
            StringBuilder quotedJvmOpt = new StringBuilder();
            quotedJvmOpt.append("\"");
            quotedJvmOpt.append(jvmOpt);
            quotedJvmOpt.append("\"");
            return quotedJvmOpt.toString();
        }/*w w  w .  j a  v a  2 s  .c  o m*/
    });

    //put the whole arguments string in single quotes, unless defaultJvmOpts was empty,
    // in which case we output "" to stay compatible with existing builds that scan the script for it
    Joiner spaceJoiner = Joiner.on(" ");
    if (Iterables.size(quotedDefaultJvmOpts) > 0) {
        StringBuilder singleQuoteJvmOpt = new StringBuilder();
        singleQuoteJvmOpt.append("'");
        singleQuoteJvmOpt.append(spaceJoiner.join(quotedDefaultJvmOpts));
        singleQuoteJvmOpt.append("'");
        return singleQuoteJvmOpt.toString();
    }

    return "\"\"";
}

From source file:org.obm.push.utils.UserEmailParserUtils.java

private String[] buildUserFromLoginParts(Iterable<String> parts) {
    int nbParts = Iterables.size(parts);
    if (nbParts > 2) {
        throw new IllegalArgumentException();
    } else if (nbParts == 2) {
        Iterator<String> iterator = parts.iterator();
        String domain = iterator.next();
        String login = iterator.next();
        checkField("domain", domain);
        checkField("login", login);
        return new String[] { login, domain };
    }/*  w  w w  . j  ava2 s .c o m*/
    return null;
}

From source file:se.kth.csc.controller.ApiProviderImpl.java

@Override
@PreAuthorize("hasRole('admin')")
public void setAdmin(Account account, boolean admin) throws ForbiddenException {
    if (!admin && Iterables.size(findAccounts(true, null)) < 2) { // Trying to remove an admin and less than two admins left
        throw new ForbiddenException("Can not remove the last admin");
    } else {//from   w  w  w. ja  v  a 2s . c  o  m
        account.setAdmin(admin);

        messageBus.convertAndSend("/topic/user/" + account.getPrincipalName(),
                new UserAdminStatusChanged(account.getPrincipalName(), admin));
    }
}

From source file:com.splicemachine.derby.utils.Vacuum.java

public void vacuumDatabase() throws SQLException {

    ensurePriorTransactionsComplete();/*w  w  w . j a  v  a 2  s .  co m*/

    //get all the conglomerates from sys.sysconglomerates
    PreparedStatement ps = null;
    ResultSet rs = null;
    LongOpenHashSet activeConglomerates = LongOpenHashSet.newInstance();
    try {
        ps = connection.prepareStatement("select conglomeratenumber from sys.sysconglomerates");
        rs = ps.executeQuery();

        while (rs.next()) {
            activeConglomerates.add(rs.getLong(1));
        }
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
    }
    LOG.info("Found " + activeConglomerates.size() + " active conglomerates.");

    //get all the tables from HBaseAdmin
    try {
        Iterable<TableDescriptor> hTableDescriptors = partitionAdmin.listTables();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Found " + Iterables.size(hTableDescriptors) + " HBase tables.");
        }

        for (TableDescriptor table : hTableDescriptors) {
            try {
                String[] tableName = parseTableName(table.getTableName());
                if (tableName.length < 2) {
                    LOG.warn("Table name doesn't have two components (namespace : name) ignoring: "
                            + table.getTableName());
                    continue;
                }
                long tableConglom = Long.parseLong(tableName[1]);
                if (tableConglom < DataDictionary.FIRST_USER_TABLE_NUMBER) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Ignoring system table: " + table.getTableName());
                    }
                    continue; //ignore system tables
                }
                if (!activeConglomerates.contains(tableConglom)) {
                    LOG.info("Deleting inactive table: " + table.getTableName());
                    partitionAdmin.deleteTable(tableName[1]);
                } else if (LOG.isTraceEnabled()) {
                    LOG.trace("Skipping still active table: " + table.getTableName());
                }
            } catch (NumberFormatException nfe) {
                /*This is either TEMP, TRANSACTIONS, SEQUENCES, or something
                * that's not managed by splice. Ignore it
                */
                LOG.info("Ignoring non-numeric table name: " + table.getTableName());
            }
        }
    } catch (IOException e) {
        LOG.error("Unexpected exception", e);
        throw PublicAPI.wrapStandardException(Exceptions.parseException(e));
    }
}

From source file:org.janusgraph.graphdb.types.TypeUtil.java

public static boolean hasAnyIndex(PropertyKey key) {
    InternalRelationType type = (InternalRelationType) key;
    return !Iterables.isEmpty(type.getKeyIndexes()) || Iterables.size(type.getRelationIndexes()) > 1; //The type itself is also returned as an index
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.layout.SequenceZOrderingRefresher.java

/**
 * Filter the diagram children parts with type to move. Sort them with the
 * sorter if not null. Reverse the result if move to front.
 *///from   www  .  j a v a2  s . c om
private void moveParts(Class<? extends IGraphicalEditPart> typeToMove, boolean moveToFront,
        Function<IGraphicalEditPart, Integer> sorter) {
    List<? extends IGraphicalEditPart> partsToMove = Lists
            .newArrayList(Iterables.filter(sequenceDiagramPart.getChildren(), typeToMove));

    if (sorter != null) {
        Ordering<IGraphicalEditPart> onResultOf = Ordering.natural().onResultOf(sorter);
        if (moveToFront) {
            onResultOf = onResultOf.reverse();
        }
        Collections.sort(partsToMove, onResultOf);
    }

    // Bring combined fragments to back/front
    if (!partsToMove.isEmpty()) {
        int index = moveToFront
                ? Iterables.size(Iterables.filter(sequenceDiagramPart.getChildren(), IGraphicalEditPart.class))
                        - 1
                : 0;
        for (IGraphicalEditPart frame : partsToMove) {
            sequenceDiagramPart.reorderChild(frame, index);
            index = index + (moveToFront ? -1 : 1);
        }
    }
}

From source file:com.stratio.decision.functions.SaveToSolrActionExecutionFunction.java

@Override
public void process(Iterable<StratioStreamingMessage> messages) throws Exception {

    Integer partitionSize = maxBatchSize;

    if (partitionSize <= 0) {
        partitionSize = Iterables.size(messages);
    }/* w ww .j  av a  2 s .  c om*/

    Iterable<List<StratioStreamingMessage>> partitionIterables = Iterables.partition(messages, partitionSize);

    try {

        for (List<StratioStreamingMessage> messageList : partitionIterables) {

            Map<String, Collection<SolrInputDocument>> elemntsToInsert = new HashMap<String, Collection<SolrInputDocument>>();
            int count = 0;
            for (StratioStreamingMessage stratioStreamingMessage : messageList) {
                count += 1;
                SolrInputDocument document = new SolrInputDocument();
                document.addField("stratio_decision_id", System.nanoTime() + "-" + count);
                for (ColumnNameTypeValue column : stratioStreamingMessage.getColumns()) {
                    document.addField(column.getColumn(), column.getValue());
                }
                checkCore(stratioStreamingMessage);
                Collection<SolrInputDocument> collection = elemntsToInsert
                        .get(stratioStreamingMessage.getStreamName());
                if (collection == null) {
                    collection = new HashSet<>();
                }
                collection.add(document);
                elemntsToInsert.put(stratioStreamingMessage.getStreamName(), collection);
            }
            while (retryStrategy.shouldRetry()) {
                try {
                    for (Map.Entry<String, Collection<SolrInputDocument>> elem : elemntsToInsert.entrySet()) {
                        getSolrclient(elem.getKey()).add(elem.getValue());
                    }
                    break;
                } catch (SolrException e) {
                    try {
                        log.error("Solr cloud status not yet properly initialized, retrying");
                        retryStrategy.errorOccured();
                    } catch (RuntimeException ex) {
                        log.error("Error while initializing Solr Cloud core ", ex.getMessage());
                    }
                }
            }
            flushClients();
        }
    } catch (Exception ex) {
        log.error("Error in Solr: " + ex.getMessage());
    }

}