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:msi.gama.common.util.OldFileUtils.java

/**
 * Construct an absolute file path.//w w  w.  j a  va2s  . co m
 *
 * @param scope
 *            the scope
 * @param fp
 *            the fp
 * @param mustExist
 *            the must exist
 * @return the string
 * @throws GamaRuntimeException
 *             the gama runtime exception
 */
static public String constructAbsoluteFilePathAlternate(final IScope scope, final String fp,
        final boolean mustExist) throws GamaRuntimeException {
    String filePath = null;
    Iterable<String> baseDirectories = null;
    final IExperimentAgent a = scope.getExperiment();
    // final List<String> referenceDirectories = a.getWorkingPaths();

    try {
        baseDirectories = Iterables.transform(a.getWorkingPaths(), each -> {
            try {
                return withTrailingSep(URLDecoder.decode(each, "UTF-8"));
            } catch (final UnsupportedEncodingException e1) {
                return each;
            }
        });
        filePath = URLDecoder.decode(fp, "UTF-8");
    } catch (final UnsupportedEncodingException e1) {
        filePath = fp;
    }
    final GamaRuntimeException ex = new GamaRuntimeFileException(scope,
            "File denoted by " + filePath + " not found.");
    File file = null;
    if (FileUtils.isAbsolutePath(filePath)) {
        file = new File(filePath);
        if (file.exists() || !mustExist) {
            try {
                return file.getCanonicalPath();
            } catch (final IOException e) {
                e.printStackTrace();
                return file.getAbsolutePath();
            }
        }
        for (final String baseDirectory : baseDirectories) {
            file = new File(baseDirectory + removeRoot(filePath));
            if (file.exists()) {
                try {
                    return file.getCanonicalPath();
                } catch (final IOException e) {
                    e.printStackTrace();
                    return file.getAbsolutePath();
                }
            }
            ex.addContext(file.getAbsolutePath());
        }
    } else {
        for (final String baseDirectory : baseDirectories) {
            file = new File(baseDirectory + filePath);
            if (file.exists()) {
                try {
                    // We have to try if the test is necessary.
                    if (scope.getExperiment().isHeadless()) {
                        // if (GAMA.isInHeadLessMode()) {
                        return file.getAbsolutePath();
                    } else {
                        return file.getCanonicalPath();
                    }

                } catch (final IOException e) {
                    e.printStackTrace();
                    return file.getAbsolutePath();
                }
            }

            ex.addContext(file.getAbsolutePath());
        }
        // We havent found the file, but it may not exist. In that case, the
        // first directory is used as a reference.
        if (!mustExist) {
            try {
                return new File(Iterables.get(baseDirectories, 0) + filePath).getCanonicalPath();
            } catch (final IOException e) {
                throw ex;
            }
        }
    }

    throw ex;
}

From source file:org.jclouds.virtualbox.functions.CreateAndInstallVm.java

@Inject
public CreateAndInstallVm(
        CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
        IMachineToNodeMetadata imachineToNodeMetadata, Predicate<SshClient> sshResponds,
        Function<IMachine, SshClient> sshClientForIMachine, MachineUtils machineUtils,
        MachineController machineController, @BuildVersion String version,
        @Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl) {
    this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
    this.sshResponds = sshResponds;
    this.sshClientForIMachine = sshClientForIMachine;
    this.machineUtils = machineUtils;
    this.imachineToNodeMetadata = imachineToNodeMetadata;
    this.machineController = machineController;
    this.version = Iterables.get(Splitter.on('-').split(version), 0);
    this.preconfigurationUrl = preconfigurationUrl;
}

From source file:blue.lapis.pore.impl.inventory.PorePlayerInventory.java

@Override
public void setLeggings(ItemStack leggings) {
    Iterables.get(this.getHandle().query(EquipmentTypes.LEGGINGS).<Slot>slots(), 0)
            .set(ItemStackConverter.of(leggings));
}

From source file:c5db.interfaces.replication.QuorumConfiguration.java

private static long getGreatestIndexCommittedByMajority(Set<Long> peers, Map<Long, Long> peersLastAckedIndex) {
    SortedMultiset<Long> committedIndexes = TreeMultiset.create();
    committedIndexes.addAll(peers.stream().map(peerId -> peersLastAckedIndex.getOrDefault(peerId, 0L))
            .collect(Collectors.toList()));
    return Iterables.get(committedIndexes.descendingMultiset(), calculateNumericalMajority(peers.size()) - 1);
}

From source file:io.prestosql.sql.planner.plan.SetOperationNode.java

/**
 * Returns the output to input symbol mapping for the given source channel
 *///  w w w . java 2s  . co  m
public Map<Symbol, SymbolReference> sourceSymbolMap(int sourceIndex) {
    ImmutableMap.Builder<Symbol, SymbolReference> builder = ImmutableMap.builder();
    for (Map.Entry<Symbol, Collection<Symbol>> entry : outputToInputs.asMap().entrySet()) {
        builder.put(entry.getKey(), Iterables.get(entry.getValue(), sourceIndex).toSymbolReference());
    }

    return builder.build();
}

From source file:org.jclouds.virtualbox.experiment.KickstartTest2.java

protected void setupCredentials() {
    identity = System.getProperty("test." + provider + ".identity", "administrator");
    credential = System.getProperty("test." + provider + ".credential", "12345");
    endpoint = URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/"));
    apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.2r73507");
    majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
}

From source file:org.jon.ivmark.graphit.core.graph.traversal.Traversable.java

/**
 * Get the element at the specified position.
 */
public E get(int index) {
    return Iterables.get(iterable, index);
}

From source file:org.jclouds.vcloud.compute.strategy.VCloudAddNodeWithTagStrategy.java

@Override
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
    InstantiateVAppTemplateOptions options = processorCount((int) getCores(template.getHardware()))
            .memory(template.getHardware().getRam())
            .disk((long) ((template.getHardware().getVolumes().get(0).getSize()) * 1024 * 1024l));

    String customizationScript = null;
    if (template.getOptions() instanceof VCloudTemplateOptions) {
        customizationScript = VCloudTemplateOptions.class.cast(template.getOptions()).getCustomizationScript();
        if (customizationScript != null) {
            options.customizeOnInstantiate(false);
            options.deploy(false);/*  ww w .j  a va 2 s  .  c o  m*/
            options.powerOn(false);
        }
    }

    if (!template.getOptions().shouldBlockUntilRunning())
        options.block(false);

    URI VDC = URI.create(template.getLocation().getId());
    URI templateId = URI.create(template.getImage().getId());

    logger.debug(">> instantiating vApp vDC(%s) template(%s) name(%s) options(%s) ", VDC, templateId, name,
            options);

    VApp vAppResponse = client.instantiateVAppTemplateInVDC(VDC, templateId, name, options);
    logger.debug("<< instantiated VApp(%s)", vAppResponse.getName());

    Task task = vAppResponse.getTasks().get(0);

    if (customizationScript == null) {
        return blockOnDeployAndPowerOnIfConfigured(options, vAppResponse, task);
    } else {
        if (!successTester.apply(task.getHref())) {
            throw new RuntimeException(
                    String.format("failed to %s %s: %s", "instantiate", vAppResponse.getName(), task));
        }
        Vm vm = Iterables.get(client.getVApp(vAppResponse.getHref()).getChildren(), 0);
        GuestCustomizationSection guestConfiguration = vm.getGuestCustomizationSection();
        // guestConfiguration
        // .setCustomizationScript(guestConfiguration.getCustomizationScript()
        // != null ?
        // guestConfiguration
        // .getCustomizationScript()
        // + "\n" + customizationScript : customizationScript);
        guestConfiguration.setCustomizationScript(customizationScript);
        task = client.updateGuestCustomizationOfVm(vm.getHref(), guestConfiguration);
        if (!successTester.apply(task.getHref())) {
            throw new RuntimeException(
                    String.format("failed to %s %s: %s", "updateGuestCustomizationOfVm", vm.getName(), task));
        }
        task = client.deployAndPowerOnVAppOrVm(vAppResponse.getHref());
        return blockOnDeployAndPowerOnIfConfigured(options, vAppResponse, task);
    }

}

From source file:org.apache.brooklyn.util.yaml.Yamls.java

/** 
 * For pre-parsed yaml, walks the maps/lists to return the given sub-item.
 * In the given path://from  w w  w .  java  2s.c om
 * <ul>
 *   <li>A vanilla string is assumed to be a key into a map.
 *   <li>A string in the form like "[0]" is assumed to be an index into a list
 * </ul>
 * 
 * Also see {@link Jsonya}, such as {@code Jsonya.of(current).at(path).get()}.
 * 
 * @return The object at the given path, or {@code null} if that path does not exist.
 */
@Beta
@SuppressWarnings("unchecked")
public static Object getAtPreParsed(Object current, List<String> path) {
    for (String pathPart : path) {
        if (pathPart.startsWith("[") && pathPart.endsWith("]")) {
            String index = pathPart.substring(1, pathPart.length() - 1);
            try {
                current = Iterables.get((Iterable<?>) current, Integer.parseInt(index));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Invalid index '" + index + "', in path " + path);
            } catch (IndexOutOfBoundsException e) {
                throw new IllegalArgumentException("Invalid index '" + index + "', in path " + path);
            }
        } else {
            current = ((Map<String, ?>) current).get(pathPart);
        }
        if (current == null)
            return null;
    }
    return current;
}

From source file:org.apache.whirr.service.zookeeper.ZooKeeperService.java

private List<String> getPrivateIps(List<NodeMetadata> nodes) {
    return Lists.transform(Lists.newArrayList(nodes), new Function<NodeMetadata, String>() {
        @Override/* w w w  . j a v a2  s  . c o m*/
        public String apply(NodeMetadata node) {
            return Iterables.get(node.getPrivateAddresses(), 0).getHostAddress();
        }
    });
}