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

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

Introduction

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

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:com.google.jimfs.JimfsPath.java

@Override
public JimfsPath relativize(Path other) {
    JimfsPath otherPath = checkPath(other);
    if (otherPath == null) {
        throw new ProviderMismatchException(other.toString());
    }/*from   www .  jav  a 2 s  . co m*/

    checkArgument(Objects.equal(root, otherPath.root), "Paths have different roots: %s, %s", this, other);

    if (equals(other)) {
        return pathService.emptyPath();
    }

    if (isEmptyPath()) {
        return otherPath;
    }

    ImmutableList<Name> otherNames = otherPath.names;
    int sharedSubsequenceLength = 0;
    for (int i = 0; i < Math.min(getNameCount(), otherNames.size()); i++) {
        if (names.get(i).equals(otherNames.get(i))) {
            sharedSubsequenceLength++;
        } else {
            break;
        }
    }

    int extraNamesInThis = Math.max(0, getNameCount() - sharedSubsequenceLength);

    ImmutableList<Name> extraNamesInOther = (otherNames.size() <= sharedSubsequenceLength)
            ? ImmutableList.<Name>of()
            : otherNames.subList(sharedSubsequenceLength, otherNames.size());

    List<Name> parts = new ArrayList<>(extraNamesInThis + extraNamesInOther.size());

    // add .. for each extra name in this path
    parts.addAll(Collections.nCopies(extraNamesInThis, Name.PARENT));
    // add each extra name in the other path
    parts.addAll(extraNamesInOther);

    return pathService.createRelativePath(parts);
}

From source file:org.locationtech.geogig.plumbing.diff.Patch.java

private String featureTypeDiffAsString(FeatureTypeDiff diff) {
    StringBuilder sb = new StringBuilder();
    sb.append(diff.toString() + "\n");
    if (!diff.getNewFeatureType().equals(ObjectId.NULL) && !diff.getOldFeatureType().equals(ObjectId.NULL)) {
        RevFeatureType oldFeatureType = getFeatureTypeFromId(diff.getOldFeatureType()).get();
        RevFeatureType newFeatureType = getFeatureTypeFromId(diff.getNewFeatureType()).get();
        ImmutableList<PropertyDescriptor> oldDescriptors = oldFeatureType.descriptors();
        ImmutableList<PropertyDescriptor> newDescriptors = newFeatureType.descriptors();
        BitSet updatedDescriptors = new BitSet(newDescriptors.size());
        for (int i = 0; i < oldDescriptors.size(); i++) {
            PropertyDescriptor oldDescriptor = oldDescriptors.get(i);
            int idx = newDescriptors.indexOf(oldDescriptor);
            if (idx != -1) {
                updatedDescriptors.set(idx);
            } else {
                Class<?> oldType = oldDescriptor.getType().getBinding();
                sb.append(/*from www  . j  a  va2  s .  c  o m*/
                        "R\t" + oldDescriptors.get(i).getName().getLocalPart() + "[" + oldType.getName() + "]");
            }

        }
        updatedDescriptors.flip(0, updatedDescriptors.length());
        for (int i = updatedDescriptors.nextSetBit(0); i >= 0; i = updatedDescriptors.nextSetBit(i + 1)) {
            PropertyDescriptor newDescriptor = newDescriptors.get(i);
            Class<?> oldType = newDescriptor.getType().getBinding();
            sb.append("A\t" + newDescriptors.get(i).getName().getLocalPart() + "[" + oldType.getName() + "]");
        }
    }

    return sb.toString();
}

From source file:org.geogit.api.plumbing.diff.Patch.java

private String featureTypeDiffAsString(FeatureTypeDiff diff) {
    StringBuilder sb = new StringBuilder();
    sb.append(diff.toString() + "\n");
    if (!diff.getNewFeatureType().equals(ObjectId.NULL) && !diff.getOldFeatureType().equals(ObjectId.NULL)) {
        RevFeatureType oldFeatureType = getFeatureTypeFromId(diff.getOldFeatureType()).get();
        RevFeatureType newFeatureType = getFeatureTypeFromId(diff.getNewFeatureType()).get();
        ImmutableList<PropertyDescriptor> oldDescriptors = oldFeatureType.sortedDescriptors();
        ImmutableList<PropertyDescriptor> newDescriptors = newFeatureType.sortedDescriptors();
        BitSet updatedDescriptors = new BitSet(newDescriptors.size());
        for (int i = 0; i < oldDescriptors.size(); i++) {
            PropertyDescriptor oldDescriptor = oldDescriptors.get(i);
            int idx = newDescriptors.indexOf(oldDescriptor);
            if (idx != -1) {
                updatedDescriptors.set(idx);
            } else {
                Class<?> oldType = oldDescriptor.getType().getBinding();
                sb.append(//from   w  ww.  j  a  v  a2 s .co m
                        "R\t" + oldDescriptors.get(i).getName().getLocalPart() + "[" + oldType.getName() + "]");
            }

        }
        updatedDescriptors.flip(0, updatedDescriptors.length());
        for (int i = updatedDescriptors.nextSetBit(0); i >= 0; i = updatedDescriptors.nextSetBit(i + 1)) {
            PropertyDescriptor newDescriptor = newDescriptors.get(i);
            Class<?> oldType = newDescriptor.getType().getBinding();
            sb.append("A\t" + newDescriptors.get(i).getName().getLocalPart() + "[" + oldType.getName() + "]");
        }
    }

    return sb.toString();
}

From source file:com.squareup.javapoet.CodeWriter.java

/**
 * Returns the common prefix of {@code classNames} and the current nesting scope. For example,
 * suppose the current scope is {@code AbstractMap.SimpleEntry}. This will return 0 for {@code
 * List}, 1 for {@code AbstractMap}, 1 for {@code AbstractMap.SimpleImmutableEntry}, and 2 for
 * {@code AbstractMap.SimpleEntry} itself.
 *//*from   w w w .  jav  a2s  .c o m*/
private int commonPrefixLength(ImmutableList<String> classNames) {
    int size = Math.min(classNames.size(), typeSpecStack.size());
    for (int i = 0; i < size; i++) {
        String a = classNames.get(i);
        String b = typeSpecStack.get(i).name;
        if (!a.equals(b))
            return i;
    }
    return size;
}

From source file:org.kiji.schema.cassandra.CassandraKijiURI.java

/** {@inheritDoc} */
@Override//from  w w  w  .jav a  2 s.c om
protected StringBuilder appendClusterIdentifier(final StringBuilder sb, final boolean preserveOrdering) {
    super.appendClusterIdentifier(sb, preserveOrdering);
    ImmutableList<String> contactPoints = preserveOrdering ? mContactPoints : mContactPointsNormalized;
    if (contactPoints.size() == 1) {
        sb.append(contactPoints.get(0));
    } else {
        sb.append('(');
        Joiner.on(',').appendTo(sb, contactPoints);
        sb.append(')');
    }
    sb.append(':').append(mContactPort).append('/');

    return sb;
}

From source file:org.locationtech.geogig.model.internal.ClusteringStrategy.java

private Map<NodeId, DAGNode> lazyNodes(final RevTree tree) {
    if (tree.isEmpty()) {
        return ImmutableMap.of();
    }// w  w  w  .jav a  2 s . c  o m

    final TreeCache treeCache = storageProvider.getTreeCache();
    final int cacheTreeId = treeCache.getTreeId(tree).intValue();

    Map<NodeId, DAGNode> dagNodes = new HashMap<>();

    List<Node> treeNodes = tree.trees();
    for (int i = 0; i < treeNodes.size(); i++) {
        NodeId nodeId = computeId(treeNodes.get(i));
        DAGNode dagNode = DAGNode.treeNode(cacheTreeId, i);
        dagNodes.put(nodeId, dagNode);
    }

    ImmutableList<Node> featureNodes = tree.features();
    for (int i = 0; i < featureNodes.size(); i++) {
        NodeId nodeId = computeId(featureNodes.get(i));
        DAGNode dagNode = DAGNode.featureNode(cacheTreeId, i);
        dagNodes.put(nodeId, dagNode);
    }
    return dagNodes;
}

From source file:com.google.javascript.jscomp.newtypes.NominalType.java

NominalType instantiateGenerics(List<JSType> types) {
    ImmutableList<String> typeParams = this.rawType.getTypeParameters();
    Preconditions.checkState(types.size() == typeParams.size());
    Map<String, JSType> typeMap = new LinkedHashMap<>();
    for (int i = 0; i < typeParams.size(); i++) {
        typeMap.put(typeParams.get(i), types.get(i));
    }/*from  w w w.j  a  v a 2s.c o m*/
    return instantiateGenerics(typeMap);
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraClientPool.java

private void sanityCheckRingConsistency() {
    Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost = HashMultimap.create();
    for (InetSocketAddress host : currentPools.keySet()) {
        Cassandra.Client client = null;/*from w  ww.  j a v  a2s  .  c o  m*/
        try {
            client = CassandraClientFactory.getClientInternal(host, config.ssl(), config.socketTimeoutMillis(),
                    config.socketQueryTimeoutMillis());
            try {
                client.describe_keyspace(config.keyspace());
            } catch (NotFoundException e) {
                return; // don't care to check for ring consistency when we're not even fully initialized
            }
            tokenRangesToHost.put(ImmutableSet.copyOf(client.describe_ring(config.keyspace())), host);
        } catch (Exception e) {
            log.warn("failed to get ring info from host: {}", host, e);
        } finally {
            if (client != null) {
                client.getOutputProtocol().getTransport().close();
            }
        }

        if (tokenRangesToHost.isEmpty()) {
            log.warn(
                    "Failed to get ring info for entire Cassandra cluster ({}); ring could not be checked for consistency.",
                    config.keyspace());
            return;
        }

        if (tokenRangesToHost.keySet().size() == 1) { // all nodes agree on a consistent view of the cluster. Good.
            return;
        }

        RuntimeException e = new IllegalStateException(
                "Hosts have differing ring descriptions.  This can lead to inconsistent reads and lost data. ");
        log.error("QA-86204 " + e.getMessage() + tokenRangesToHost, e);

        // provide some easier to grok logging for the two most common cases
        if (tokenRangesToHost.size() > 2) {
            for (Map.Entry<Set<TokenRange>, Collection<InetSocketAddress>> entry : tokenRangesToHost.asMap()
                    .entrySet()) {
                if (entry.getValue().size() == 1) {
                    log.error("Host: " + entry.getValue().iterator().next()
                            + " disagrees with the other nodes about the ring state.");
                }
            }
        }
        if (tokenRangesToHost.keySet().size() == 2) {
            ImmutableList<Set<TokenRange>> sets = ImmutableList.copyOf(tokenRangesToHost.keySet());
            Set<TokenRange> set1 = sets.get(0);
            Set<TokenRange> set2 = sets.get(1);
            log.error("Hosts are split.  group1: " + tokenRangesToHost.get(set1) + " group2: "
                    + tokenRangesToHost.get(set2));
        }

        CassandraVerifier.logErrorOrThrow(e.getMessage(), config.safetyDisabled());
    }
}

From source file:org.apache.rya.indexing.entity.storage.mongo.MongoEntityStorage.java

/**
 * Searches the Entity storage for all Entities that contain all the
 * specified explicit type IDs./*from   w  w  w.  ja va  2  s .  c o m*/
 * @param explicitTypeIds the {@link ImmutableList} of {@link RyaURI}s that
 * are being searched for.
 * @return the {@link List} of {@link Entity}s that have all the specified
 * explicit type IDs. If nothing was found an empty {@link List} is
 * returned.
 * @throws EntityStorageException
 */
private List<Entity> searchHasAllExplicitTypes(final ImmutableList<RyaURI> explicitTypeIds)
        throws EntityStorageException {
    final List<Entity> hasAllExplicitTypesEntities = new ArrayList<>();
    if (!explicitTypeIds.isEmpty()) {
        // Grab the first type from the explicit type IDs.
        final RyaURI firstType = explicitTypeIds.get(0);

        // Check if that type exists anywhere in storage.
        final List<RyaURI> subjects = new ArrayList<>();
        Optional<Type> type;
        try {
            if (mongoTypeStorage == null) {
                mongoTypeStorage = new MongoTypeStorage(mongo, ryaInstanceName);
            }
            type = mongoTypeStorage.get(firstType);
        } catch (final TypeStorageException e) {
            throw new EntityStorageException("Unable to get entity type: " + firstType, e);
        }
        if (type.isPresent()) {
            // Grab the subjects for all the types we found matching "firstType"
            final ConvertingCursor<TypedEntity> cursor = search(Optional.empty(), type.get(),
                    Collections.emptySet());
            while (cursor.hasNext()) {
                final TypedEntity typedEntity = cursor.next();
                final RyaURI subject = typedEntity.getSubject();
                subjects.add(subject);
            }
        }

        // Now grab all the Entities that have the subjects we found.
        for (final RyaURI subject : subjects) {
            final Optional<Entity> entityFromSubject = get(subject);
            if (entityFromSubject.isPresent()) {
                final Entity candidateEntity = entityFromSubject.get();
                // Filter out any entities that don't have all the same
                // types associated with them as our original list of
                // explicit type IDs. We already know the entities we found
                // have "firstType" but now we have access to all the other
                // types they have.
                if (candidateEntity.getExplicitTypeIds().containsAll(explicitTypeIds)) {
                    hasAllExplicitTypesEntities.add(candidateEntity);
                }
            }
        }
    }

    return hasAllExplicitTypesEntities;
}

From source file:edu.mit.streamjit.impl.compiler2.SubsetBiasAllocationStrategy.java

@Override
public void allocateGroup(ActorGroup group, Range<Integer> iterations, List<Core> cores, Configuration config) {
    int id = group.id();
    int numCores = config.getParameter("Group" + id + "CoreCount", Configuration.IntParameter.class).getValue();
    Configuration.PermutationParameter<Integer> coreOrderParam = config.getParameter("Group" + id + "CoreOrder",
            Configuration.PermutationParameter.class, Integer.class);
    ImmutableList<? extends Integer> coreOrder = coreOrderParam.getUniverse();
    int rawBiasCount = config.getParameter("Group" + id + "BiasCount", Configuration.IntParameter.class)
            .getValue();/*from  w  ww. j  a v a  2  s.  c  om*/
    int biasCount = Math.min(rawBiasCount, numCores - 1);
    float bias = config.getParameter("Group" + id + "Bias", Configuration.FloatParameter.class).getValue();

    try {
        List<Core> subset = new ArrayList<>(numCores);
        for (int i = 0; i < coreOrder.size() && subset.size() < numCores; ++i)
            if (coreOrder.get(i) < cores.size())
                subset.add(cores.get(coreOrder.get(i)));
        List<Core> biasSubset = new ArrayList<>(biasCount);
        while (biasSubset.size() < biasCount)
            biasSubset.add(subset.remove(0));

        float deficitFraction = biasCount * (1 - bias) / numCores, surplusFraction = 1 - deficitFraction;
        assert deficitFraction >= 0 && surplusFraction >= 0 : String.format("%d %d %f -> %f %f", numCores,
                biasCount, bias, deficitFraction, surplusFraction);
        iterations = iterations.canonical(DiscreteDomain.integers());
        int totalIterations = iterations.upperEndpoint() - iterations.lowerEndpoint();
        int biasIterations = (int) (totalIterations * deficitFraction);
        //We pass a null config to ensure we don't interfere with the other strategy.
        if (biasCount > 0)
            new FullDataParallelAllocationStrategy(biasCount).allocateGroup(group,
                    Range.closedOpen(iterations.lowerEndpoint(), iterations.lowerEndpoint() + biasIterations),
                    biasSubset, null);
        if (numCores - biasCount > 0)
            new FullDataParallelAllocationStrategy(numCores - biasCount).allocateGroup(group,
                    Range.closedOpen(iterations.lowerEndpoint() + biasIterations, iterations.upperEndpoint()),
                    subset, null);
    } catch (Exception ex) {
        StringBuilder sb = new StringBuilder();
        sb.append(iterations).append(" of ").append(group).append("\n");
        sb.append(String.format("numCores %d, raw biasCount %d, biasCount %d, bias %f, order %s", numCores,
                rawBiasCount, biasCount, bias, coreOrder));
        throw new RuntimeException(sb.toString(), ex);
    }
}