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.opengamma.strata.measure.fxopt.FxOptionVolatilitiesMarketDataFunction.java

@Override
public MarketDataBox<FxOptionVolatilities> build(FxOptionVolatilitiesId id, MarketDataConfig marketDataConfig,
        ScenarioMarketData marketData, ReferenceData refData) {

    FxOptionVolatilitiesDefinition volatilitiesDefinition = marketDataConfig
            .get(FxOptionVolatilitiesDefinition.class, id.getName().getName());
    ValuationZoneTimeDefinition zoneTimeDefinition = marketDataConfig.get(ValuationZoneTimeDefinition.class);
    int nScenarios = marketData.getScenarioCount();
    MarketDataBox<LocalDate> valuationDates = marketData.getValuationDate();
    MarketDataBox<ZonedDateTime> valuationDateTimes = zoneTimeDefinition.toZonedDateTime(valuationDates);

    int nParameters = volatilitiesDefinition.getParameterCount();
    ImmutableList<MarketDataBox<Double>> inputs = volatilitiesDefinition.volatilitiesInputs().stream()
            .map(q -> marketData.getValue(q)).collect(toImmutableList());
    ImmutableList<FxOptionVolatilities> vols = IntStream.range(0, nScenarios)
            .mapToObj(scenarioIndex -> volatilitiesDefinition
                    .volatilities(valuationDateTimes.getValue(scenarioIndex),
                            DoubleArray.of(nParameters,
                                    paramIndex -> inputs.get(paramIndex).getValue(scenarioIndex)),
                            refData))//from  w  w  w  .j a  v a  2 s  .  c  o  m
            .collect(toImmutableList());

    return nScenarios > 1 ? MarketDataBox.ofScenarioValues(vols) : MarketDataBox.ofSingleValue(vols.get(0));
}

From source file:com.hmaimi.jodis.RoundRobinJedisPool.java

/**
 * Get a jedis instance from pool./*from  w w  w  .  java  2s .c o  m*/
 * <p>
 * We do not have a returnResource method, just close the jedis instance
 * returned directly.
 * 
 * @return
 */
public Jedis getResource() {
    ImmutableList<PooledObject> pools = this.pools;
    if (pools.isEmpty()) {
        throw new JedisException("Proxy list empty");
    }
    for (;;) {
        int current = nextIdx.get();
        int next = current >= pools.size() - 1 ? 0 : current + 1;
        if (nextIdx.compareAndSet(current, next)) {
            return pools.get(next).pool.getResource();
        }
    }
}

From source file:com.google.api.codegen.java.JavaGapicContext.java

public String partitionKeyCode(ImmutableList<FieldSelector> discriminatorFields) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < discriminatorFields.size(); i++) {
        if (i > 0) {
            buf.append(" + \"|\" + ");
        }/*from   w  w  w.  j  ava2  s.  c o  m*/
        String simpleName = discriminatorFields.get(i).getLastField().getSimpleName();
        buf.append("request.get" + lowerUnderscoreToUpperCamel(simpleName) + "()");
    }
    return buf.toString();
}

From source file:com.google.template.soy.jssrc.internal.JsSrcSubject.java

void causesErrors(String... expectedErrorMsgSubstrings) {
    FormattingErrorReporter formattingErrorReporter = new FormattingErrorReporter();
    this.errorReporter = formattingErrorReporter;

    generateCode();/*from  www  . j a v  a 2  s.  c o m*/

    ImmutableList<String> errorMessages = formattingErrorReporter.getErrorMessages();
    assertThat(errorMessages).hasSize(expectedErrorMsgSubstrings.length);
    for (int i = 0; i < expectedErrorMsgSubstrings.length; ++i) {
        assertThat(errorMessages.get(i)).contains(expectedErrorMsgSubstrings[i]);
    }
}

From source file:com.google.api.codegen.transformer.py.PythonImportSectionTransformer.java

/**
 * For each ProtoFile dependency, put its TypeAlias in allTypeTable; and if it is a local import,
 * then put it in the given localImportNames, otherwise if it is a shared import, but it in the
 * given sharedImportNames./*  w ww.  j a  v  a 2 s.c  o m*/
 */
private void populateTypeTable(List<ProtoFile> protoFileDependencies, ModelTypeTable allTypeTable,
        Set<String> localImportNames, Set<String> sharedImportNames, String packageName) {
    for (ProtoFile protoFile : protoFileDependencies) {
        // For python, adding a single message from the proto file to the type table will populate
        // the type table with the correct imports.
        ImmutableList<MessageType> messages = protoFile.getMessages();
        if (!messages.isEmpty()) {
            TypeRef typeRef = TypeRef.of(messages.get(0));
            allTypeTable.getAndSaveNicknameFor(typeRef);

            if (protoFile.getFullName().equals(packageName)) {
                localImportNames.add(allTypeTable.getFullNameFor(typeRef));
            } else {
                sharedImportNames.add(allTypeTable.getFullNameFor(typeRef));
            }
        }
    }
}

From source file:org.locationtech.geogig.spring.service.LegacyMergeFeatureService.java

private int getDescriptorIndex(String key, ImmutableList<PropertyDescriptor> properties) {
    for (int i = 0; i < properties.size(); i++) {
        PropertyDescriptor prop = properties.get(i);
        if (prop.getName().toString().equals(key)) {
            return i;
        }//from   ww w.  ja  v  a 2s .  c o  m
    }
    return -1;
}

From source file:rocks.devonthe.stickychunk.chunkload.ChunkLoadCallback.java

/**
 * Callback for loading Tickets during world load.
 * <p>/* w  w w . ja  v a  2s .  c  o  m*/
 * The list of forced chunks is not saved with Tickets, this callback
 * is your place to reassociate chunks to Tickets, using the extra
 * information saved with the ticket or your own external configuration.
 * Any unneeded tickets must be manually released.
 * <p>
 * The list of tickets contains both standard plugin and
 * player-associated tickets that were registered by this plugin.
 * <p>
 * The list of tickets has been truncated to the maximum allowed for
 * your plugin, so may not be all saved tickets in the event that the
 * maximum tickets for your plugin was decreased.
 *
 * @param tickets The list of tickets that need chunks registered
 * @param world   The world tickets were loaded for
 */
@Override
public void onLoaded(ImmutableList<LoadingTicket> tickets, World world) {
    ArrayList<LoadedRegion> assignedRegions = Lists.newArrayList();

    StickyChunk.getInstance().getLogger().info("registering tickets");

    while (unassignedRegions.size() > 0) {
        int index = 0;
        for (LoadedRegion region : unassignedRegions) {
            if (world.getUniqueId().equals(region.getWorld().getUniqueId())) {
                region.assignTicket(tickets.get(index));
                assignedRegions.add(region);
                StickyChunk.getInstance().getLogger()
                        .info(String.format("registering ticket to %s", region.getOwner().toString()));
            }
            index++;
        }

        unassignedRegions.removeAll(assignedRegions);
    }

    assignedRegions.forEach(region -> dataStore.addPlayerRegion(region.getOwner(), region));
}

From source file:com.facebook.litho.testing.viewtree.ViewTreeAssert.java

private String getHasVisibleTextErrorMessage(final String text) {
    String errorMsg = String.format("Cannot find text \"%s\" in view hierarchy:%n%s. ", text,
            actual.makeString(GET_TEXT_FUNCTION));

    final ImmutableList<View> similarPath = getPathToVisibleSimilarText(text);
    if (similarPath != null) {
        errorMsg += String.format("\nHowever, a near-match was found: \"%s\"",
                GET_TEXT_FUNCTION.apply(similarPath.get(similarPath.size() - 1)));
    } else {//w w w . j av a  2 s . c o  m
        errorMsg += "\nNo near-match was found.";
    }
    return errorMsg;
}

From source file:org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobStore.java

@Override
public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {
    ImmutableList.Builder<GoogleCloudStorageObject> objectsBuilder = ImmutableList.builder();
    for (MultipartPart part : parts) {
        objectsBuilder.add(api.getObjectApi().getObject(mpu.containerName(),
                Strings2.urlEncode(getMPUPartName(mpu, part.partNumber()))));
    }//  w ww.  ja  v a2 s  .c  o  m

    ObjectTemplate destination = blobMetadataToObjectTemplate.apply(mpu.blobMetadata());
    final ImmutableList<GoogleCloudStorageObject> objects = objectsBuilder.build();
    if (!objects.isEmpty()) {
        destination.storageClass(objects.get(0).storageClass());
    }
    if (mpu.putOptions().getBlobAccess() == BlobAccess.PUBLIC_READ) {
        ObjectAccessControls controls = ObjectAccessControls.builder().entity("allUsers")
                .bucket(mpu.containerName()).role(READER).build();
        destination.addAcl(controls);
    }

    ComposeObjectTemplate template = ComposeObjectTemplate.builder().fromGoogleCloudStorageObject(objects)
            .destination(destination).build();
    String eTag = api.getObjectApi()
            .composeObjects(mpu.containerName(), Strings2.urlEncode(mpu.blobName()), template).etag();

    // remove parts, composite object keeps a reference to them
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    for (MultipartPart part : parts) {
        builder.add(getMPUPartName(mpu, part.partNumber()));
    }
    removeBlobs(mpu.containerName(), builder.build());

    return eTag;
}

From source file:google.registry.tools.CreateLrpTokensCommand.java

@Override
public void run() throws Exception {
    checkArgument((assignee == null) == (assigneesFile != null),
            "Exactly one of either assignee or filename must be specified.");
    checkArgument((assigneesFile == null) || (metadata == null),
            "Metadata cannot be specified along with a filename.");
    checkArgument((assignee == null) || (metadataColumns == null),
            "Metadata columns cannot be specified along with an assignee.");
    final Set<String> validTlds = ImmutableSet.copyOf(Splitter.on(',').split(tlds));
    for (String tld : validTlds) {
        assertTldExists(tld);//from   www .j  a  va  2  s.co m
    }

    LineReader reader = new LineReader((assigneesFile != null) ? Files.newReader(assigneesFile.toFile(), UTF_8)
            : new StringReader(assignee));

    String line = null;
    do {
        ImmutableSet.Builder<LrpTokenEntity> tokensToSaveBuilder = new ImmutableSet.Builder<>();
        for (String token : generateTokens(BATCH_SIZE)) {
            line = reader.readLine();
            if (!isNullOrEmpty(line)) {
                ImmutableList<String> values = ImmutableList
                        .copyOf(Splitter.onPattern(COMMA_EXCEPT_WHEN_QUOTED_REGEX)
                                // Results should not be surrounded in double quotes.
                                .trimResults(CharMatcher.is('\"')).split(line));
                LrpTokenEntity.Builder tokenBuilder = new LrpTokenEntity.Builder().setAssignee(values.get(0))
                        .setToken(token).setValidTlds(validTlds);
                if (metadata != null) {
                    tokenBuilder.setMetadata(metadata);
                } else if (metadataColumns != null) {
                    ImmutableMap.Builder<String, String> metadataBuilder = ImmutableMap.builder();
                    for (ImmutableMap.Entry<String, Integer> entry : metadataColumns.entrySet()) {
                        checkArgument(values.size() > entry.getValue(),
                                "Entry for %s does not have a value for %s (index %s)", values.get(0),
                                entry.getKey(), entry.getValue());
                        metadataBuilder.put(entry.getKey(), values.get(entry.getValue()));
                    }
                    tokenBuilder.setMetadata(metadataBuilder.build());
                }
                tokensToSaveBuilder.add(tokenBuilder.build());
            }
        }
        final ImmutableSet<LrpTokenEntity> tokensToSave = tokensToSaveBuilder.build();
        // Wrap in a retrier to deal with transient 404 errors (thrown as RemoteApiExceptions).
        retrier.callWithRetry(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                saveTokens(tokensToSave);
                return null;
            }
        }, RemoteApiException.class);
    } while (line != null);
}