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

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

Introduction

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

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:org.richfaces.resource.optimizer.resource.writer.impl.ResourceWriterImpl.java

private ResourceProcessor getMatchingResourceProcessor(final String requestPath) {
    return Iterables.get(Iterables.filter(resourceProcessors, new Predicate<ResourceProcessor>() {
        @Override/*  w w w . j av  a 2s . co  m*/
        public boolean apply(ResourceProcessor input) {
            return input.isSupportedFile(requestPath);
        }
    }), 0);
}

From source file:com.urswolfer.intellij.plugin.gerrit.ui.GerritToolWindowFactory.java

private void updateChangesBrowser(final ChangeInfo changeDetails, final Project project) {
    myRepositoryChangesBrowser.getViewer().setEmptyText("Loading...");
    myRepositoryChangesBrowser.setChangesToDisplay(Collections.<Change>emptyList());
    final GitRepository gitRepository = GerritGitUtil.getRepositoryForGerritProject(project,
            changeDetails.getProject());
    final VirtualFile virtualFile = gitRepository.getGitDir();
    final FilePathImpl filePath = new FilePathImpl(virtualFile);

    String ref = GerritUtil.getRef(changeDetails);

    GerritGitUtil.fetchChange(project, gitRepository, ref, new Callable<Void>() {
        @Override/*from   w ww . ja va  2  s .  c  om*/
        public Void call() throws Exception {
            final List<GitCommit> gitCommits;
            try {
                gitCommits = GitHistoryUtils.commitsDetails(project, filePath, new SymbolicRefs(),
                        Collections.singletonList(changeDetails.getCurrentRevision()));
            } catch (VcsException e) {
                throw new RuntimeException(e);
            }
            final GitCommit gitCommit = Iterables.get(gitCommits, 0);

            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    myRepositoryChangesBrowser.setChangesToDisplay(gitCommit.getChanges());
                }
            });
            return null;
        }
    });
}

From source file:edu.udo.scaffoldhunter.model.dataimport.ImportJob.java

/**
 * @param index//from w w  w  .  j a  v a  2  s .c o  m
 *            the index or row of the Property name
 * @return the property name for the given Index
 */
public String getPropertyName(int index) {
    return Iterables.get(propertyMappings.keySet(), index);
}

From source file:org.eclipse.tracecompass.tmf.core.parsers.custom.CustomEvent.java

/**
 * Get the contents of an event table cell for this event's row.
 *
 * @param index//from   w  w w  . j a va 2 s  .c o  m
 *            The ID/index of the field to display. This corresponds to the
 *            index in the event content.
 * @return The String to display in the cell
 * @deprecated Use {@link ITmfEventField#getField(String...)} instead.
 */
@Deprecated
public String getEventString(int index) {
    Collection<? extends ITmfEventField> fields = getContent().getFields();
    if (index < 0 || index >= fields.size()) {
        return ""; //$NON-NLS-1$
    }

    return nullToEmptyString(checkNotNull(Iterables.get(fields, index)).getValue());
}

From source file:brooklyn.networking.portforwarding.DockerPortForwarder.java

public Map<Integer, Integer> getPortMappings(MachineLocation targetMachine) {
    ComputeServiceContext context = ContextBuilder.newBuilder("docker").endpoint(dockerEndpoint)
            .credentials(dockerIdentity, dockerCredential)
            .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new SshjSshClientModule()))
            .build(ComputeServiceContext.class);

    DockerApi api = context.unwrapApi(DockerApi.class);
    String containerId = ((JcloudsSshMachineLocation) targetMachine).getJcloudsId();
    Container container = api.getRemoteApi().inspectContainer(containerId);
    context.close();//from  www.ja va2 s . co m
    Map<Integer, Integer> portMappings = Maps.newLinkedHashMap();
    if (container.getNetworkSettings() == null)
        return portMappings;
    for (Map.Entry<String, List<Map<String, String>>> entrySet : container.getNetworkSettings().getPorts()
            .entrySet()) {
        String containerPort = Iterables.get(Splitter.on("/").split(entrySet.getKey()), 0);
        String hostPort = Iterables.getOnlyElement(
                Iterables.transform(entrySet.getValue(), new Function<Map<String, String>, String>() {
                    @Override
                    public String apply(Map<String, String> hostIpAndPort) {
                        return hostIpAndPort.get("HostPort");
                    }
                }));
        portMappings.put(Integer.parseInt(containerPort), Integer.parseInt(hostPort));
    }
    return portMappings;
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Starts a servers, verifies that jobs are created correctly and an be retrieved from the job
 * services/* w  ww . j av  a 2  s .  co m*/
 */
@Test(dependsOnMethods = "testServerLifecycle", enabled = true)
public void testJobs() {
    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();

    String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();

    Server createdServer = api.getServerServices().addServer(nameOfServer,
            "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, Iterables.getLast(availableIps).getIp());

    assert serverLatestJobCompleted.apply(createdServer);

    // restart the server
    api.getServerServices().power(nameOfServer, PowerCommand.RESTART);

    Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);

    Job latestJob = Iterables.getLast(jobs);
    Long latestJobId = latestJob.getId();

    Job latestJobFetched = Iterables.getOnlyElement(api.getJobServices().getJobsById(latestJobId));

    assert latestJob.equals(latestJobFetched) : "Job and its representation found by ID don't match";

    long[] idsOfAllJobs = new long[jobs.size()];
    int i = 0;
    for (Job job : jobs) {
        idsOfAllJobs[i++] = job.getId();
    }

    Set<Job> jobsFetched = api.getJobServices().getJobsById(idsOfAllJobs);
    assert jobsFetched.size() == jobs.size() : format(
            "Number of jobs fetched by ids doesn't match the number of jobs "
                    + "requested. Requested/expected: %d. Found: %d.",
            jobs.size(), jobsFetched.size());

    // delete the server
    api.getServerServices().deleteByName(nameOfServer);
}

From source file:com.isotrol.impe3.nr.api.NodeQueries.java

/**
 * Merges all queries with should boolean operator
 * @param queries NodeQuery queries/*w  ww .j  a v  a2 s. c  om*/
 * @return NodeQuery with should operator with all queries.
 */
public static NodeQuery any(Iterable<? extends NodeQuery> queries) {
    queries = Iterables.filter(queries, Predicates.notNull());
    final int n = Iterables.size(queries);
    if (n == 0) {
        return null;
    } else if (n == 1) {
        return Iterables.get(queries, 0);
    }
    final NRBooleanQuery q = bool();
    for (NodeQuery c : queries) {
        q.should(c);
    }
    return q;
}

From source file:com.facebook.buck.parser.TargetSpecResolver.java

/**
 * @return a list of sets of build targets where each set contains all build targets that match a
 *     corresponding {@link TargetNodeSpec}.
 *//*from   w w  w.  ja  v a 2  s.  c  om*/
public <T extends HasBuildTarget> ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs(Cell rootCell,
        Iterable<? extends TargetNodeSpec> specs, TargetConfiguration targetConfiguration,
        FlavorEnhancer<T> flavorEnhancer, TargetNodeProviderForSpecResolver<T> targetNodeProvider,
        TargetNodeFilterForSpecResolver<T> targetNodeFilter)
        throws BuildFileParseException, InterruptedException {

    // Convert the input spec iterable into a list so we have a fixed ordering, which we'll rely on
    // when returning results.
    ImmutableList<TargetNodeSpec> orderedSpecs = ImmutableList.copyOf(specs);

    Multimap<Path, Integer> perBuildFileSpecs = groupSpecsByBuildFile(rootCell, orderedSpecs);

    // Kick off parse futures for each build file.
    ArrayList<ListenableFuture<Map.Entry<Integer, ImmutableSet<BuildTarget>>>> targetFutures = new ArrayList<>();
    for (Path buildFile : perBuildFileSpecs.keySet()) {
        Collection<Integer> buildFileSpecs = perBuildFileSpecs.get(buildFile);
        TargetNodeSpec firstSpec = orderedSpecs.get(Iterables.get(buildFileSpecs, 0));
        Cell cell = rootCell.getCell(firstSpec.getBuildFileSpec().getCellPath());

        // Format a proper error message for non-existent build files.
        if (!cell.getFilesystem().isFile(buildFile)) {
            throw new MissingBuildFileException(firstSpec.toString(),
                    cell.getFilesystem().getRootPath().relativize(buildFile));
        }

        for (int index : buildFileSpecs) {
            TargetNodeSpec spec = orderedSpecs.get(index);
            handleTargetNodeSpec(flavorEnhancer, targetNodeProvider, targetNodeFilter, targetFutures, cell,
                    buildFile, targetConfiguration, index, spec);
        }
    }

    return collectTargets(orderedSpecs.size(), targetFutures);
}

From source file:org.aksw.mex.log4mex.ExperimentConfigurationVO.java

/**
 * gets a specific algorithm of a configuration based on the algorithm class
 * @param algoInstanceName// w w w  . ja  v a 2  s .c o  m
 * @return
 */
public AlgorithmVO Algorithm(String algoInstanceName) {
    if (this._algorithms == null) {
        this._algorithms = new ArrayList<>();
    }

    AlgorithmVO ret = null;
    try {
        Collection<AlgorithmVO> t = Collections2.filter(this._algorithms,
                p -> p.getIndividualName().equals(algoInstanceName));
        if (t != null && t.size() > 0) {
            ret = Iterables.get(t, 0);
        }
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return ret;
}

From source file:org.jclouds.profitbricks.compute.ProfitBricksComputeServiceAdapter.java

protected NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name,
        TemplateWithDataCenter template) {
    checkArgument(template.getLocation().getScope() == LocationScope.ZONE,
            "Template must use a ZONE-scoped location");
    final String dataCenterId = template.getDataCenter().id();

    Hardware hardware = template.getHardware();

    TemplateOptions options = template.getOptions();
    final String loginUser = isNullOrEmpty(options.getLoginUser()) ? "root" : options.getLoginUser();
    final String password = options.hasLoginPassword() ? options.getLoginPassword() : Passwords.generate();

    final org.jclouds.compute.domain.Image image = template.getImage();

    // provision all storages based on hardware
    List<? extends Volume> volumes = hardware.getVolumes();
    List<String> storageIds = Lists.newArrayListWithExpectedSize(volumes.size());

    int i = 1;/*from w w w. j  av  a 2s .co  m*/
    for (final Volume volume : volumes)
        try {
            logger.trace("<< provisioning storage '%s'", volume);
            final Storage.Request.CreatePayload.Builder storageBuilder = Storage.Request.creatingBuilder();
            if (i == 1) {
                storageBuilder.mountImageId(image.getId());
                // we don't need to pass password to the API if we're using a snapshot
                Provisionable.Type provisionableType = Provisionable.Type
                        .fromValue(image.getUserMetadata().get(ProvisionableToImage.KEY_PROVISIONABLE_TYPE));
                if (provisionableType == Provisionable.Type.IMAGE)
                    storageBuilder.imagePassword(password);
            }
            storageBuilder.dataCenterId(dataCenterId).name(format("%s-disk-%d", name, i++))
                    .size(volume.getSize());

            String storageId = (String) provisioningManager
                    .provision(jobFactory.create(dataCenterId, new Supplier<Object>() {

                        @Override
                        public Object get() {
                            return api.storageApi().createStorage(storageBuilder.build());
                        }
                    }));

            storageIds.add(storageId);
            logger.trace(">> provisioning complete for storage. returned id='%s'", storageId);
        } catch (Exception ex) {
            if (i - 1 == 1) // if first storage (one with image) provisioning fails; stop method
                throw Throwables.propagate(ex);
            logger.warn(ex, ">> failed to provision storage. skipping..");
        }

    int lanId = DEFAULT_LAN_ID;
    if (options.getNetworks() != null)
        try {
            String networkId = Iterables.get(options.getNetworks(), 0);
            lanId = Integer.parseInt(networkId);
        } catch (Exception ex) {
            logger.warn("no valid network id found from options. using default id='%d'", DEFAULT_LAN_ID);
        }

    Double cores = ComputeServiceUtils.getCores(hardware);

    // provision server and connect boot storage (first provisioned)
    String serverId = null;
    try {
        String storageBootDeviceId = Iterables.get(storageIds, 0); // must have atleast 1
        final Server.Request.CreatePayload serverRequest = Server.Request.creatingBuilder()
                .dataCenterId(dataCenterId).name(name).bootFromStorageId(storageBootDeviceId)
                .cores(cores.intValue()).ram(hardware.getRam()).availabilityZone(AvailabilityZone.AUTO)
                .hasInternetAccess(true).lanId(lanId).build();
        logger.trace("<< provisioning server '%s'", serverRequest);

        serverId = (String) provisioningManager
                .provision(jobFactory.create(dataCenterId, new Supplier<Object>() {

                    @Override
                    public Object get() {
                        return api.serverApi().createServer(serverRequest);
                    }
                }));
        logger.trace(">> provisioning complete for server. returned id='%s'", serverId);

    } catch (Exception ex) {
        logger.error(ex, ">> failed to provision server. rollbacking..");
        destroyStorages(storageIds, dataCenterId);
        throw Throwables.propagate(ex);
    }

    // connect the rest of storages to server; delete if fails
    final int storageCount = storageIds.size();
    for (int j = 1; j < storageCount; j++) { // skip first; already connected
        String storageId = storageIds.get(j);
        try {
            logger.trace("<< connecting storage '%s' to server '%s'", storageId, serverId);
            final Storage.Request.ConnectPayload request = Storage.Request.connectingBuilder()
                    .storageId(storageId).serverId(serverId).build();

            provisioningManager.provision(jobFactory.create(group, new Supplier<Object>() {

                @Override
                public Object get() {
                    return api.storageApi().connectStorageToServer(request);
                }
            }));

            logger.trace(">> storage connected.");
        } catch (Exception ex) {
            // delete unconnected storage
            logger.warn(ex, ">> failed to connect storage '%s'. deleting..", storageId);
            destroyStorage(storageId, dataCenterId);
        }
    }

    // Last paranoid check
    waitDcUntilAvailable.apply(dataCenterId);

    LoginCredentials serverCredentials = LoginCredentials.builder().user(loginUser).password(password).build();

    Server server = getNode(serverId);

    return new NodeAndInitialCredentials<Server>(server, serverId, serverCredentials);
}