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

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

Introduction

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

Prototype

static <T> T[] toArray(Iterable<? extends T> iterable, T[] array) 

Source Link

Usage

From source file:com.linecorp.armeria.internal.metric.PrometheusMetricRequestDecorator.java

@SuppressWarnings({ "unchecked", "SuspiciousArrayCast" })
private PrometheusMetricRequestDecorator(CollectorRegistry collectorRegistry, Iterable<T> metricLabels,
        Function<RequestLog, Map<T, String>> labelingFunction, String prefix) {
    this(collectorRegistry,
            (T[]) Iterables.toArray(requireNonNull(metricLabels, "metricLabels"), MetricLabel.class),
            labelingFunction, prefix);//from   w  ww. java2s  .  c  om
}

From source file:org.blip.workflowengine.transferobject.ModifiablePropertyNode.java

@Override
public PropertyNode add(String key, Short value, Collection<Attribute> attributes) {
    return internalAdd(true, key, value, Iterables.toArray(attributes, Attribute.class));
}

From source file:org.apache.lens.cli.commands.LensFactCommands.java

/**
 * Adds the new fact storage./*w  w  w.j  a va2s. c o  m*/
 *
 * @param tablepair the tablepair
 * @return the string
 */
@CliCommand(value = "fact add storage", help = "adds a new storage to fact")
public String addNewFactStorage(@CliOption(key = { "",
        "table" }, mandatory = true, help = "<table> <path to storage-spec>") String tablepair) {
    Iterable<String> parts = Splitter.on(' ').trimResults().omitEmptyStrings().split(tablepair);
    String[] pair = Iterables.toArray(parts, String.class);
    if (pair.length != 2) {
        return "Syntax error, please try in following "
                + "format. fact add storage <table> <storage spec path>";
    }

    File f = new File(pair[1]);
    if (!f.exists()) {
        return "Storage spech path " + f.getAbsolutePath() + " does not exist. Please check the path";
    }

    APIResult result = getClient().addStorageToFact(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Fact table storage addition completed";
    } else {
        return "Fact table storage addition failed";
    }
}

From source file:org.eclipse.sirius.business.internal.movida.registry.StatusUpdater.java

private void checkActualDependencies(Entry entry) {
    Set<URI> declared = Sets.newHashSet(entry.getDeclaredDependencies());
    // Include both the logical URIs and their corresponding physical URIs
    // in the declared set.
    Set<URI> declaredResolved = Sets.newHashSet(Iterables.transform(declared, new Function<URI, URI>() {
        @Override//from   w  w  w .  j a  v  a 2  s. c om
        public URI apply(URI from) {
            return resourceSet.getURIConverter().normalize(from);
        }
    }));
    declared.addAll(declaredResolved);
    Set<URI> actual = entry.getActualDependencies();
    SetView<URI> undeclared = Sets.difference(actual, declared);
    if (!undeclared.isEmpty()) {
        entry.setState(ViewpointState.INVALID);
        Object[] data = Iterables.toArray(Iterables.transform(undeclared, Functions.toStringFunction()),
                String.class);
        addDiagnostic(entry, Diagnostic.ERROR, UNDECLARED_DEPENDENCY,
                "Sirius has undeclared dependencies to other resources.", data); //$NON-NLS-1$
    }
}

From source file:org.apache.apex.malhar.kafka.KafkaConsumerWrapper.java

public void emitImmediately(Map<AbstractKafkaPartitioner.PartitionMeta, Pair<Long, Long>> windowData) {
    for (Map.Entry<AbstractKafkaPartitioner.PartitionMeta, Pair<Long, Long>> windowEntry : windowData
            .entrySet()) {/*from w ww.j  av a  2  s  . c om*/
        AbstractKafkaPartitioner.PartitionMeta meta = windowEntry.getKey();
        Pair<Long, Long> replayOffsetSize = windowEntry.getValue();
        KafkaConsumer<byte[], byte[]> kc = consumers.get(meta.getCluster());
        if (kc == null && kc.assignment().contains(windowEntry.getKey().getTopicPartition())) {
            throw new RuntimeException("Coundn't find consumer to replay the message PartitionMeta : " + meta);
        }
        //pause other partition
        for (TopicPartition tp : kc.assignment()) {
            if (meta.getTopicPartition().equals(tp)) {
                kc.resume(tp);
            } else {
                try {
                    kc.position(tp);
                } catch (NoOffsetForPartitionException e) {
                    //the poll() method of a consumer will throw exception
                    // if any of subscribed consumers not initialized with position
                    handleNoOffsetForPartitionException(e, kc);
                }
                kc.pause(tp);
            }
        }
        // set the offset to window start offset
        kc.seek(meta.getTopicPartition(), replayOffsetSize.getLeft());
        long windowCount = replayOffsetSize.getRight();
        while (windowCount > 0) {
            try {
                ConsumerRecords<byte[], byte[]> records = kc.poll(ownerOperator.getConsumerTimeout());
                for (Iterator<ConsumerRecord<byte[], byte[]>> cri = records.iterator(); cri.hasNext()
                        && windowCount > 0;) {
                    ownerOperator.emitTuple(meta.getCluster(), cri.next());
                    windowCount--;
                }
            } catch (NoOffsetForPartitionException e) {
                throw new RuntimeException("Couldn't replay the offset", e);
            }
        }
        // set the offset after window
        kc.seek(meta.getTopicPartition(), replayOffsetSize.getLeft() + replayOffsetSize.getRight());
    }

    // resume all topics
    for (KafkaConsumer<byte[], byte[]> kc : consumers.values()) {
        kc.resume(Iterables.toArray(kc.assignment(), TopicPartition.class));
    }

}

From source file:io.prestosql.plugin.accumulo.conf.AccumuloTableProperties.java

/**
 * Gets the configured locality groups for the table, or Optional.empty() if not set.
 * <p>/*from  w  w w  .ja  va  2  s  .c om*/
 * All strings are lowercase.
 *
 * @param tableProperties The map of table properties
 * @return Optional map of locality groups
 */
public static Optional<Map<String, Set<String>>> getLocalityGroups(Map<String, Object> tableProperties) {
    requireNonNull(tableProperties);

    @SuppressWarnings("unchecked")
    String groupStr = (String) tableProperties.get(LOCALITY_GROUPS);
    if (groupStr == null) {
        return Optional.empty();
    }

    ImmutableMap.Builder<String, Set<String>> groups = ImmutableMap.builder();

    // Split all configured locality groups
    for (String group : PIPE_SPLITTER.split(groupStr)) {
        String[] locGroups = Iterables.toArray(COLON_SPLITTER.split(group), String.class);

        if (locGroups.length != 2) {
            throw new PrestoException(INVALID_TABLE_PROPERTY,
                    "Locality groups string is malformed. See documentation for proper format.");
        }

        String grpName = locGroups[0];
        ImmutableSet.Builder<String> colSet = ImmutableSet.builder();

        for (String f : COMMA_SPLITTER.split(locGroups[1])) {
            colSet.add(f.toLowerCase(Locale.ENGLISH));
        }

        groups.put(grpName.toLowerCase(Locale.ENGLISH), colSet.build());
    }

    return Optional.of(groups.build());
}

From source file:dagger2.internal.codegen.writer.JavaWriter.java

public void file(Filer filer, CharSequence name, Iterable<? extends Element> originatingElements)
        throws IOException {
    JavaFileObject sourceFile = filer.createSourceFile(name,
            Iterables.toArray(originatingElements, Element.class));
    Closer closer = Closer.create();/*from  ww  w  .j av  a2  s. c  o  m*/
    try {
        write(closer.register(sourceFile.openWriter()));
    } catch (Exception e) {
        try {
            sourceFile.delete();
        } catch (Exception e2) {
            // couldn't delete the file
        }
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.fcrepo.auth.oauth.api.AuthzEndpoint.java

/**
 * Saves an authorization code for later retrieval at the token endpoint.
 * /*from   w ww. j av  a 2  s  .  c  o  m*/
 * @param authCode
 * @param scopes
 * @param client
 * @throws RepositoryException
 */
private void saveAuthCode(final String authCode, final Set<String> scopes, final String client)
        throws RepositoryException {
    final Session session = sessions.getInternalSession(OAUTH_WORKSPACE);
    try {
        final Node codeNode = jcrTools.findOrCreateNode(session, "/authorization-codes/" + authCode);
        codeNode.setProperty(CLIENT_PROPERTY, client);
        codeNode.setProperty(Constants.SCOPES_PROPERTY, Iterables.toArray(scopes, String.class));
        session.save();
    } finally {
        session.logout();
    }

}

From source file:com.mind_era.knime_rapidminer.knime.nodes.RapidMinerNodeModel.java

/**
 * {@inheritDoc}//from   w  w  w  .  ja v  a  2s . c  om
 */
@Override
protected PortObject[] execute(final PortObject[] inData, final ExecutionContext exec) throws Exception {
    RapidMinerInit.init(false);
    RapidMinerInit.setPreferences();
    final Process process = processModel.loadProject(false);
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    final Future<IOContainer> future = executor.submit(new Callable<IOContainer>() {
        @Override
        public IOContainer call() throws Exception {
            return process.run(new IOContainer(Iterables.toArray(Collections2
                    .transform(Collections2.filter(Arrays.asList(inData), new Predicate<PortObject>() {
                        @Override
                        public boolean apply(final PortObject input) {
                            return input != null;
                        }
                    }), new Function<PortObject, ExampleSet>() {
                        @Override
                        public ExampleSet apply(final PortObject input) {
                            return MemoryExampleTable
                                    .createCompleteCopy(/*
                                                         * new
                                                         * SimpleExampleSet
                                                         * (
                                                         */new KnimeExampleTable(
                                            new WrappedTable((BufferedDataTable) input),
                                            rowIdColumnName.isEnabled(), rowIdColumnName.getStringValue()))
                                    .createExampleSet();
                        }
                    }), ExampleSet.class)));
        }
    });
    while (!future.isDone()) {
        Thread.sleep(500);
        try {
            exec.checkCanceled();
            final Operator currentOperator = process == null ? null : process.getCurrentOperator();
            if (currentOperator != null) {
                exec.setProgress("Operator: " + currentOperator.getName());
            } else {
                exec.setProgress("");
            }
        } catch (final CanceledExecutionException e) {
            process.stop();
            Thread.sleep(200);
            future.cancel(true);
            throw e;
        }
    }
    final IOContainer container = future.get();
    final ArrayList<BufferedDataTable> ret = new ArrayList<BufferedDataTable>();
    for (int resultIndex = 0; resultIndex < container.size(); ++resultIndex) {
        logger.debug("Converting the " + (resultIndex + 1) + "th result table.");
        final ExampleSet result = container.get(ExampleSet.class, resultIndex);
        ret.add(convertExampleSet(exec, result, rowIdColumnName.isEnabled(), rowIdColumnName.getStringValue(),
                lastResultTableSpecs != null && lastResultTableSpecs.length > resultIndex
                        ? lastResultTableSpecs[resultIndex]
                        : null));
    }
    if (ret.size() > getNrOutPorts()) {
        logger.warn("The last " + (ret.size() - getNrOutPorts()) + " output were discarded, only the first "
                + getNrOutPorts() + " exampleset were returned.");
    }
    for (int i = ret.size(); i-- > getNrOutPorts();) {
        ret.remove(i);
    }
    for (int i = getNrOutPorts() - ret.size(); i-- > 0;) {
        final BufferedDataContainer c = exec.createDataContainer(new DataTableSpec());
        c.close();
        ret.add(c.getTable());
    }
    return ret.toArray(new BufferedDataTable[ret.size()]);
}

From source file:org.obm.provisioning.json.ObmUserJsonSerializer.java

@Override
public void serialize(ObmUser value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    jgen.writeStartObject();//  w  ww.j  av a 2s .com
    jgen.writeObjectField(ID.asSpecificationValue(), value.getExtId());
    jgen.writeStringField(LOGIN.asSpecificationValue(), value.getLogin());
    jgen.writeStringField(LASTNAME.asSpecificationValue(), value.getLastName());
    jgen.writeStringField(PROFILE.asSpecificationValue(),
            value.getProfileName() != null ? value.getProfileName().getName() : null);
    jgen.writeStringField(FIRSTNAME.asSpecificationValue(), value.getFirstName());
    jgen.writeStringField(COMMONNAME.asSpecificationValue(), value.getCommonName());
    jgen.writeStringField(PASSWORD.asSpecificationValue(), value.getPassword());
    jgen.writeStringField(KIND.asSpecificationValue(), value.getKind());
    jgen.writeStringField(TITLE.asSpecificationValue(), value.getTitle());
    jgen.writeStringField(DESCRIPTION.asSpecificationValue(), value.getDescription());
    jgen.writeStringField(COMPANY.asSpecificationValue(), value.getCompany());
    jgen.writeStringField(SERVICE.asSpecificationValue(), value.getService());
    jgen.writeStringField(DIRECTION.asSpecificationValue(), value.getDirection());
    writeObjectsField(jgen, ADDRESSES.asSpecificationValue(), value.getAddress1(), value.getAddress2(),
            value.getAddress3());
    jgen.writeStringField(TOWN.asSpecificationValue(), value.getTown());
    jgen.writeStringField(ZIPCODE.asSpecificationValue(), value.getZipCode());
    jgen.writeStringField(BUSINESS_ZIPCODE.asSpecificationValue(), value.getExpresspostal());
    jgen.writeStringField(COUNTRY.asSpecificationValue(), value.getCountryCode());
    writeObjectsField(jgen, PHONES.asSpecificationValue(), value.getPhone(), value.getPhone2());
    jgen.writeStringField(MOBILE.asSpecificationValue(), value.getMobile());
    writeObjectsField(jgen, FAXES.asSpecificationValue(), value.getFax(), value.getFax2());
    jgen.writeBooleanField(ARCHIVED.asSpecificationValue(), value.isArchived());
    jgen.writeStringField(MAIL_QUOTA.asSpecificationValue(),
            String.valueOf(Objects.firstNonNull(value.getMailQuota(), 0)));
    jgen.writeStringField(MAIL_SERVER.asSpecificationValue(), getMailHostName(value));
    jgen.writeObjectField(MAILS.asSpecificationValue(),
            SerializationUtils.serializeUserEmailAddresses(value.getUserEmails()));
    jgen.writeObjectField(EFFECTIVEMAILS.asSpecificationValue(),
            Iterables.toArray(value.expandAllEmailDomainTuples(), String.class));
    jgen.writeBooleanField(HIDDEN.asSpecificationValue(), value.isHidden());
    jgen.writeObjectField(TIMECREATE.asSpecificationValue(), value.getTimeCreate());
    jgen.writeObjectField(TIMEUPDATE.asSpecificationValue(), value.getTimeUpdate());
    jgen.writeObjectField(GROUPS.asSpecificationValue(),
            extractGroupIdentifiers(value.getGroups(), value.getDomain()));
    jgen.writeEndObject();
}