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:org.jclouds.ec2.compute.extensions.EC2SecurityGroupExtension.java

@Override
public Set<SecurityGroup> listSecurityGroupsForNode(String id) {
    checkNotNull(id, "id");
    String[] parts = AWSUtils.parseHandle(id);
    String region = parts[0];//from   w ww . j a  va2  s.  c o m
    String instanceId = parts[1];

    RunningInstance instance = getOnlyElement(
            Iterables.concat(client.getInstanceApi().get().describeInstancesInRegion(region, instanceId)));

    if (instance == null) {
        return ImmutableSet.of();
    }

    Set<String> groupNames = instance.getGroupNames();
    Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups = client.getSecurityGroupApi().get()
            .describeSecurityGroupsInRegion(region, Iterables.toArray(groupNames, String.class));

    return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter));
}

From source file:com.google.cloud.dataflow.sdk.coders.CoderProperties.java

/**
 * Verifies that for the given {@link Coder Coder<Iterable<T>>},
 * and value of type {@code Iterable<T>}, encoding followed by decoding yields an
 * equal value of type {@code Collection<T>}, in the given {@link Coder.Context}.
 *///from   ww  w.ja v a2 s.c om
@SuppressWarnings("unchecked")
public static <T, IT extends Iterable<T>> void coderDecodeEncodeContentsInSameOrderInContext(Coder<IT> coder,
        Coder.Context context, IT value) throws Exception {
    Iterable<T> result = decodeEncode(coder, context, value);
    // Matchers.contains() requires at least one element
    if (Iterables.isEmpty(value)) {
        assertThat(result, emptyIterable());
    } else {
        // This is the only Matchers.contains() overload that takes literal values
        assertThat(result, contains((T[]) Iterables.toArray(value, Object.class)));
    }
}

From source file:org.apache.samza.table.remote.TableWriteFunction.java

/**
 * Asynchronously delete all {@code records} with the specified {@code keys} from the remote store.
 * The default implementation calls deleteAsync for each key and return a combined future.
 *
 * @param keys keys for the table records to be written
 * @return CompletableFuture for the deleteAll request
 *//*from w  ww  .ja v  a 2  s.c om*/
default CompletableFuture<Void> deleteAllAsync(Collection<K> keys) {
    List<CompletableFuture<Void>> deleteFutures = keys.stream().map(this::deleteAsync)
            .collect(Collectors.toList());
    return CompletableFuture.allOf(Iterables.toArray(deleteFutures, CompletableFuture.class));
}

From source file:org.apache.giraph.GiraphRunner.java

@Override
public int run(String[] args) throws Exception {
    Options options = getOptions();//w w w.  j a va  2 s  .c o  m
    HelpFormatter formatter = new HelpFormatter();
    if (args.length == 0) {
        formatter.printHelp(getClass().getName(), options, true);
        return 0;
    }

    String vertexClassName = args[0];
    if (LOG.isDebugEnabled()) {
        LOG.debug("Attempting to run Vertex: " + vertexClassName);
    }

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    // Verify all the options have been provided
    for (String[] requiredOption : requiredOptions) {
        if (!cmd.hasOption(requiredOption[0])) {
            if (LOG.isInfoEnabled()) {
                LOG.info(requiredOption[1]);
            }
            return -1;
        }
    }

    int workers = Integer.parseInt(cmd.getOptionValue('w'));
    GiraphJob job = new GiraphJob(getConf(), "Giraph: " + vertexClassName);
    job.setVertexClass(Class.forName(vertexClassName));
    job.setVertexInputFormatClass(Class.forName(cmd.getOptionValue("if")));
    job.setVertexOutputFormatClass(Class.forName(cmd.getOptionValue("of")));

    if (cmd.hasOption("ip")) {
        FileInputFormat.addInputPath(job.getInternalJob(), new Path(cmd.getOptionValue("ip")));
    } else {
        if (LOG.isInfoEnabled()) {
            LOG.info("No input path specified. Ensure your InputFormat does" + " not require one.");
        }
    }

    if (cmd.hasOption("op")) {
        FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(cmd.getOptionValue("op")));
    } else {
        if (LOG.isInfoEnabled()) {
            LOG.info("No output path specified. Ensure your OutputFormat does" + " not require one.");
        }
    }

    if (cmd.hasOption("c")) {
        job.setVertexCombinerClass(Class.forName(cmd.getOptionValue("c")));
    }

    if (cmd.hasOption("wc")) {
        job.setWorkerContextClass(Class.forName(cmd.getOptionValue("wc")));
    }

    if (cmd.hasOption("aw")) {
        job.setAggregatorWriterClass(Class.forName(cmd.getOptionValue("aw")));
    }

    if (cmd.hasOption("ca")) {
        Configuration jobConf = job.getConfiguration();
        for (String paramValue : Splitter.on(',').split(cmd.getOptionValue("ca"))) {
            String[] parts = Iterables.toArray(Splitter.on('=').split(paramValue), String.class);
            if (parts.length != 2) {
                throw new IllegalArgumentException("Unable to parse custom " + " argument: " + paramValue);
            }
            if (LOG.isInfoEnabled()) {
                LOG.info("Setting custom argument [" + parts[0] + "] to [" + parts[1] + "]");
            }
            jobConf.set(parts[0], parts[1]);
        }
    }

    job.setWorkerConfiguration(workers, workers, 100.0f);

    boolean isQuiet = !cmd.hasOption('q');

    return job.run(isQuiet) ? 0 : -1;
}

From source file:org.openqa.selenium.firefox.xpi.XpiDriverService.java

@Override
public void start() throws IOException {
    lock.lock();/*w  w  w  .j  av  a2s .c  o m*/
    try {
        profile.setPreference(PORT_PREFERENCE, port);
        addWebDriverExtension(profile);
        profileDir = profile.layoutOnDisk();

        binary.setOutputWatcher(getOutputStream());

        ImmutableMap.Builder<String, String> envBuilder = new ImmutableMap.Builder<String, String>()
                .putAll(getEnvironment()).put("XRE_PROFILE_PATH", profileDir.getAbsolutePath())
                .put("MOZ_NO_REMOTE", "1").put("MOZ_CRASHREPORTER_DISABLE", "1") // Disable Breakpad
                .put("NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console

        if (Platform.getCurrent().is(Platform.LINUX) && profile.shouldLoadNoFocusLib()) {
            modifyLinkLibraryPath(envBuilder, profileDir);
        }
        Map<String, String> env = envBuilder.build();

        List<String> cmdArray = new ArrayList<>(getArgs());
        cmdArray.addAll(binary.getExtraOptions());
        cmdArray.add("-foreground");
        process = new CommandLine(binary.getPath(), Iterables.toArray(cmdArray, String.class));
        process.setEnvironmentVariables(env);
        process.updateDynamicLibraryPath(env.get(CommandLine.getLibraryPathPropertyName()));
        // On Snow Leopard, beware of problems the sqlite library
        if (!(Platform.getCurrent().is(Platform.MAC) && Platform.getCurrent().getMinorVersion() > 5)) {
            String firefoxLibraryPath = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_LIBRARY_PATH,
                    binary.getFile().getAbsoluteFile().getParentFile().getAbsolutePath());
            process.updateDynamicLibraryPath(firefoxLibraryPath);
        }

        process.copyOutputTo(getActualOutputStream());

        process.executeAsync();

        waitUntilAvailable();
    } finally {
        lock.unlock();
    }
}

From source file:org.apache.druid.segment.IndexBuilder.java

public QueryableIndex buildMMappedMergedIndex() {
    IndexMerger indexMerger = TestHelper.getTestIndexMergerV9(segmentWriteOutMediumFactory);
    Preconditions.checkNotNull(tmpDir, "tmpDir");

    final List<QueryableIndex> persisted = Lists.newArrayList();
    try {/*from   w w w  .j  a va 2s . com*/
        for (int i = 0; i < rows.size(); i += ROWS_PER_INDEX_FOR_MERGING) {
            persisted
                    .add(TestHelper.getTestIndexIO()
                            .loadIndex(
                                    indexMerger.persist(
                                            buildIncrementalIndexWithRows(schema, maxRows,
                                                    rows.subList(i,
                                                            Math.min(rows.size(),
                                                                    i + ROWS_PER_INDEX_FOR_MERGING))),
                                            new File(tmpDir, StringUtils.format("testIndex-%s",
                                                    UUID.randomUUID().toString())),
                                            indexSpec, null)));
        }
        final QueryableIndex merged = TestHelper.getTestIndexIO().loadIndex(
                indexMerger.merge(Lists.transform(persisted, new Function<QueryableIndex, IndexableAdapter>() {
                    @Override
                    public IndexableAdapter apply(QueryableIndex input) {
                        return new QueryableIndexIndexableAdapter(input);
                    }
                }), true, Iterables.toArray(Iterables.transform(Arrays.asList(schema.getMetrics()),
                        new Function<AggregatorFactory, AggregatorFactory>() {
                            @Override
                            public AggregatorFactory apply(AggregatorFactory input) {
                                return input.getCombiningFactory();
                            }
                        }), AggregatorFactory.class),
                        new File(tmpDir, StringUtils.format("testIndex-%s", UUID.randomUUID())), indexSpec));
        for (QueryableIndex index : persisted) {
            index.close();
        }
        return merged;
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.cdap.internal.app.runtime.plugin.MacroParser.java

private MacroMetadata getMacroFunctionMetadata(int startIndex, int endIndex, String macroStr,
        int argsStartIndex) {
    // check for closing ")" and allow escaping "\)" and doubly-escaping "\\)"
    int closingParenIndex = getFirstUnescapedTokenIndex(')', macroStr, 0);
    if (closingParenIndex < 0 || !macroStr.endsWith(")")) {
        throw new InvalidMacroException(
                String.format("Could not find enclosing ')' for macro arguments in '%s'.", macroStr));
    } else if (closingParenIndex != macroStr.length() - 1) {
        throw new InvalidMacroException(
                String.format("Macro arguments in '%s' have extra invalid trailing ')'.", macroStr));
    }//  ww w .java  2s  . c  o  m

    // arguments and macroFunction are expected to have escapes replaced when being evaluated
    String arguments = replaceEscapedSyntax(macroStr.substring(argsStartIndex + 1, macroStr.length() - 1));
    String macroFunction = replaceEscapedSyntax(macroStr.substring(0, argsStartIndex));

    String[] args = Iterables.toArray(Splitter.on(ARGUMENT_DELIMITER).split(arguments), String.class);
    return new MacroMetadata(macroEvaluator.evaluate(macroFunction, args), startIndex, endIndex);
}

From source file:msi.gaml.descriptions.StatementWithChildrenDescription.java

@Override
public void replaceChildrenWith(final Iterable<IDescription> array) {
    final List<IDescription> descs = Arrays.asList(Iterables.toArray(array, IDescription.class));
    children.clear();// ww  w .j a  v  a 2  s  .  c  o m
    children.addAll(descs);
}

From source file:org.apache.jackrabbit.oak.plugins.index.property.jmx.PropertyIndexStats.java

private CompositeData getStatsForIndex(String path, NodeState idx, int maxValueCount, int maxDepth,
        int maxPathCount) throws OpenDataException {
    Map<String, Object> result = new HashMap<String, Object>();

    //Add placeholder
    result.put("path", path);
    result.put("values", new String[0]);
    result.put("paths", new String[0]);
    result.put("valueCount", -1L);
    result.put("pathCount", -1);
    result.put("maxPathCount", maxPathCount);
    result.put("maxDepth", maxDepth);
    result.put("maxValueCount", maxValueCount);

    String status = "No index found at path " + path;
    NodeState data = idx.getChildNode(INDEX_CONTENT_NODE_NAME);
    if (data.exists()) {
        if (idx.getBoolean(UNIQUE_PROPERTY_NAME)) {
            status = "stats not supported for unique indexes";
        } else {/*from   w  w  w.ja va  2 s .c  om*/
            long childNodeCount = data.getChildNodeCount(maxValueCount);
            if (childNodeCount == Long.MAX_VALUE || childNodeCount > maxValueCount) {
                status = String.format("stats cannot be determined as number of values exceed the max limit of "
                        + "[%d]. Estimated value count [%d]", maxValueCount, childNodeCount);
            } else {
                String[] values = Iterables.toArray(Iterables.limit(data.getChildNodeNames(), maxValueCount),
                        String.class);

                String[] paths = determineIndexedPaths(data.getChildNodeEntries(), maxDepth, maxPathCount);
                result.put("values", values);
                result.put("paths", paths);
                result.put("pathCount", paths.length);
                status = "Result determined and above path list can be safely used based on current indexed data";
            }
            result.put("valueCount", childNodeCount);
        }
    }

    result.put("status", status);
    return new CompositeDataSupport(getType(), result);
}

From source file:ec.nbdemetra.ui.properties.NodePropertySetBuilder.java

@Override
public Sheet.Set build() {
    Sheet.Set result = name != null ? new Sheet.Set() : Sheet.createPropertiesSet();
    if (!Strings.isNullOrEmpty(name)) {
        result.setName(name);/*from w  w  w.ja  v  a2 s.  co  m*/
    }
    if (!Strings.isNullOrEmpty(tabName)) {
        result.setValue("tabName", tabName);
    }
    if (!Strings.isNullOrEmpty(displayName)) {
        result.setDisplayName(displayName);
    }
    if (!Strings.isNullOrEmpty(shortDescription)) {
        result.setShortDescription(shortDescription);
    }
    result.put(Iterables.toArray(nodeProperties, Node.Property.class));
    return result;
}