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:edu.umn.msi.tropix.genomics.bowtie.impl.BowtieJobProcessorImpl.java

@Override
protected void doPreprocessing() {
    final String indexName = writeIndex();

    final List<String> databaseNames = writeDatabases();

    final String commandLineOptions = inputOptionsBuilder.getCommandLineOptions(inputParameters, databaseNames,
            indexName, null);//from w ww. ja v a  2 s.  c o m

    final JobDescriptionType jobDescriptionType = getJobDescription().getJobDescriptionType();
    final String[] args = Iterables
            .toArray(Iterables.filter(Arrays.asList(commandLineOptions.split("\\s+")), new Predicate<String>() {
                public boolean apply(final String str) {
                    return StringUtils.hasText(str.trim());
                }
            }), String.class);
    jobDescriptionType.setArgument(args);
    jobDescriptionType
            .setStdout(getStagingDirectory().getAbsolutePath() + getStagingDirectory().getSep() + "output.txt");
    jobDescriptionType
            .setStderr(getStagingDirectory().getAbsolutePath() + getStagingDirectory().getSep() + "log.err");
    jobDescriptionType.setDirectory(getStagingDirectory().getAbsolutePath());
}

From source file:org.sfs.jobs.AssignDocumentsToNodeJob.java

protected Observable<Void> execute0(VertxContext<Server> vertxContext) {
    return Defer.aVoid().flatMap(aVoid -> {
        ClusterInfo clusterInfo = vertxContext.verticle().getClusterInfo();
        return Observable.from(clusterInfo.getDataNodes());
    }).reduce(new HashMap<String, Long>(), (documentCountsByNode, persistentServiceDef) -> {
        Optional<Long> documentCount = persistentServiceDef.getDocumentCount();
        if (documentCount.isPresent()) {
            documentCountsByNode.put(persistentServiceDef.getId(), documentCount.get());
        }//from w ww  .j a  v a  2 s .c  o m
        return documentCountsByNode;
    }).filter(stringLongHashMap -> !stringLongHashMap.isEmpty()).flatMap(documentCountsByNode -> {
        Elasticsearch elasticsearch = vertxContext.verticle().elasticsearch();

        String[] activeNodeIds = Iterables.toArray(documentCountsByNode.keySet(), String.class);

        BoolQueryBuilder c0 = boolQuery().mustNot(existsQuery("node_id"));

        BoolQueryBuilder c1 = boolQuery().mustNot(termsQuery("node_id", activeNodeIds));

        BoolQueryBuilder query = boolQuery().should(c0).should(c1).minimumNumberShouldMatch(1);

        return Defer.aVoid().flatMap(new ListSfsStorageIndexes(vertxContext)).flatMap(index -> {
            producer = new ScanAndScrollStreamProducer(vertxContext, query).setIndeces(index)
                    .setTypes(elasticsearch.defaultType()).setReturnVersion(true);

            SearchHitEndableWriteStreamUpdateNodeId consumer = new SearchHitEndableWriteStreamUpdateNodeId(
                    vertxContext, documentCountsByNode);

            if (aborted) {
                producer.abort();
            }

            return AsyncIO.pump(producer, consumer);
        }).count().map(new ToVoid<>());
    }).singleOrDefault(null);
}

From source file:ec.tstoolkit.utilities.CheckedIterator.java

@Nonnull
public E[] toArray(@Nonnull Class<E> type) throws T {
    return Iterables.toArray(toList(), type);
}

From source file:org.apache.hive.service.cli.operation.ClassicTableTypeMapping.java

@Override
public String[] mapToHiveType(String clientTypeName) {
    Collection<String> hiveTableType = clientToHiveMap.get(clientTypeName.toUpperCase());
    if (hiveTableType == null) {
        LOG.warn("Not supported client table type " + clientTypeName);
        return new String[] { clientTypeName };
    }//from  w ww .  ja  va 2 s.c  o m
    return Iterables.toArray(hiveTableType, String.class);
}

From source file:org.immutables.ordinal.ImmutableOrdinalSet.java

/**
 * Creates immutable ordinal set from iterable of elements.
 * All elements expected to have same {@link OrdinalValue#domain()} as the first element,
 * otherwise exception will be thrown.// w  w w. ja va 2 s.  c  o m
 * @param <E> the element type
 * @param elements the elements, no nulls allowed
 * @return the immutable ordinal set
 */
@SuppressWarnings("unchecked")
// Safe unchecked, elements are defined to be of E or subtypes of E
// which is allowed for immutable collection
public static <E extends OrdinalValue<E>> ImmutableOrdinalSet<E> copyOf(Iterable<? extends E> elements) {
    if (elements instanceof ImmutableOrdinalSet) {
        return (ImmutableOrdinalSet<E>) elements;
    }
    return constructFromArray(Iterables.toArray(elements, OrdinalValue.class));
}

From source file:com.inmobi.grill.cli.commands.GrillStorageCommands.java

@CliCommand(value = "update storage", help = "update storage")
public String updateStorage(@CliOption(key = { "",
        "storage" }, mandatory = true, help = "<storage-name> <storage-spec>") String specPair) {
    Iterable<String> parts = Splitter.on(' ').trimResults().omitEmptyStrings().split(specPair);
    String[] pair = Iterables.toArray(parts, String.class);
    if (pair.length != 2) {
        return "Syntax error, please try in following "
                + "format. create fact <fact spec path> <storage spec path>";
    }/*from  w  ww.j  a  va2s.co m*/

    File f = new File(pair[1]);

    if (!f.exists()) {
        return "Fact spec path" + f.getAbsolutePath() + " does not exist. Please check the path";
    }

    APIResult result = client.updateStorage(pair[0], pair[1]);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
        return "Update of " + pair[0] + " succeeded";
    } else {
        return "Update of " + pair[0] + " failed";
    }
}

From source file:org.sonatype.nexus.internal.httpclient.NexusSSLConnectionSocketFactory.java

private static String[] split(final String s) {
    if (Strings2.isBlank(s)) {
        return null;
    }/*  w ww.j av  a2 s .c om*/
    return Iterables.toArray(propertiesSplitter.split(s), String.class);
}

From source file:edu.cmu.lti.oaqa.baseqa.providers.parser.LingPipeParserProvider.java

@Override
public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
        throws ResourceInitializationException {
    boolean ret = super.initialize(aSpecifier, aAdditionalParams);
    // tokenizer//from  w w w  .j a v  a  2s . c o m
    String tokenFactoryName = String.class.cast(getParameterValue("token-factory"));
    Class<? extends TokenizerFactory> tokenFactoryClass;
    try {
        tokenFactoryClass = Class.forName(tokenFactoryName).asSubclass(TokenizerFactory.class);
    } catch (ClassNotFoundException e) {
        tokenFactoryClass = IndoEuropeanTokenizerFactory.class;
    }
    @SuppressWarnings("unchecked")
    Object[] tokenFactoryParams = Iterables
            .toArray(Iterable.class.cast(getParameterValue("token-factory-params")), Object.class);
    Class<?>[] tokenFactoryParamsTypes = Arrays.stream(tokenFactoryParams).map(p -> String.class)
            .toArray(Class[]::new);
    try {
        tokenizerFactory = tokenFactoryClass.getConstructor(tokenFactoryParamsTypes)
                .newInstance(tokenFactoryParams);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new ResourceInitializationException(e);
    }
    // pos
    String posModel = String.class.cast(getParameterValue("pos-model"));
    try (ObjectInputStream ois = new ObjectInputStream(this.getClass().getResourceAsStream(posModel))) {
        HiddenMarkovModel hmm = (HiddenMarkovModel) ois.readObject();
        decoder = new HmmDecoder(hmm);
    } catch (IOException | ClassNotFoundException e) {
        throw new ResourceInitializationException(e);
    }
    // lemmatizer
    // dependency parser
    return ret;
}

From source file:eu.esdihumboldt.hale.ui.schema.presets.internal.SchemaPresetContentProvider.java

@Override
public Object[] getChildren(Object parentElement) {
    if (parentElement instanceof SchemaCategory) {
        return Iterables.toArray(((SchemaCategory) parentElement).getSchemas(), Object.class);
    }/*from w w  w . j a  v  a 2 s.  c o  m*/
    return null;
}

From source file:dagger.internal.codegen.JavaPoetSourceFileGenerator.java

/** Generates a source file to be compiled for {@code T}. */
void generate(T input) throws SourceFileGenerationException {
    ClassName generatedTypeName = nameGeneratedType(input);
    try {//from  ww w  .  j a  v a  2s  .  c  o  m
        Optional<TypeSpec.Builder> type = write(generatedTypeName, input);
        if (!type.isPresent()) {
            return;
        }
        JavaFile javaFile = buildJavaFile(generatedTypeName, type.get());

        final JavaFileObject sourceFile = filer.createSourceFile(generatedTypeName.toString(),
                Iterables.toArray(javaFile.typeSpec.originatingElements, Element.class));
        try {
            new Formatter().formatSource(CharSource.wrap(javaFile.toString()), new CharSink() {
                @Override
                public Writer openStream() throws IOException {
                    return sourceFile.openWriter();
                }
            });
        } catch (FormatterException e) {
            throw new SourceFileGenerationException(Optional.of(generatedTypeName), e,
                    getElementForErrorReporting(input));
        }
    } catch (Exception e) {
        // if the code above threw a SFGE, use that
        Throwables.propagateIfPossible(e, SourceFileGenerationException.class);
        // otherwise, throw a new one
        throw new SourceFileGenerationException(Optional.<ClassName>absent(), e,
                getElementForErrorReporting(input));
    }
}