List of usage examples for com.google.common.collect ImmutableList get
E get(int index);
From source file:org.geogig.osm.internal.CreateOSMChangesetOp.java
/** * Executes the diff operation.//www . ja va 2s . c o m * * @return an iterator to a set of differences between the two trees * @see DiffEntry */ @Override protected AutoCloseableIterator<ChangeContainer> _call() { AutoCloseableIterator<DiffEntry> nodeIterator = command(DiffOp.class).setFilter(OSMUtils.NODE_TYPE_NAME) .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call(); AutoCloseableIterator<DiffEntry> wayIterator = command(DiffOp.class).setFilter(OSMUtils.WAY_TYPE_NAME) .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call(); AutoCloseableIterator<DiffEntry> iterator = AutoCloseableIterator.concat(nodeIterator, wayIterator); final EntityConverter converter = new EntityConverter(); final Function<DiffEntry, ChangeContainer> function = (diff) -> { NodeRef ref = diff.changeType().equals(ChangeType.REMOVED) ? diff.getOldObject() : diff.getNewObject(); RevFeature revFeature = command(RevObjectParse.class).setObjectId(ref.getObjectId()) .call(RevFeature.class).get(); RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(ref.getMetadataId()) .call(RevFeatureType.class).get(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( (SimpleFeatureType) revFeatureType.type()); ImmutableList<PropertyDescriptor> descriptors = revFeatureType.descriptors(); for (int i = 0; i < descriptors.size(); i++) { PropertyDescriptor descriptor = descriptors.get(i); Optional<Object> value = revFeature.get(i); featureBuilder.set(descriptor.getName(), value.orNull()); } SimpleFeature feature = featureBuilder.buildFeature(ref.name()); Entity entity = converter.toEntity(feature, id); EntityContainer container; if (entity instanceof Node) { container = new NodeContainer((Node) entity); } else { container = new WayContainer((Way) entity); } ChangeAction action = diff.changeType().equals(ChangeType.ADDED) ? ChangeAction.Create : diff.changeType().equals(ChangeType.MODIFIED) ? ChangeAction.Modify : ChangeAction.Delete; return new ChangeContainer(container, action); }; return AutoCloseableIterator.transform(iterator, function); }
From source file:com.google.api.codegen.php.PhpGapicContext.java
public Method getFirstMethod(Interface service) { ImmutableList<Method> methods = service.getMethods(); if (methods.size() > 0) { return methods.get(0); }/*from w w w . j a va 2s.c o m*/ throw new RuntimeException("No methods available."); }
From source file:it.unibz.inf.ontop.sql.ForeignKeyConstraint.java
/** * private constructor (use Builder instead) * /*from ww w . j a v a 2 s. com*/ * @param name * @param components */ private ForeignKeyConstraint(String name, ImmutableList<Component> components) { this.name = name; this.components = components; this.relation = (DatabaseRelationDefinition) components.get(0).getAttribute().getRelation(); this.referencedRelation = (DatabaseRelationDefinition) components.get(0).getReference().getRelation(); }
From source file:com.google.devtools.build.lib.skyframe.SkylarkModuleCycleReporter.java
@Override public boolean maybeReportCycle(SkyKey topLevelKey, CycleInfo cycleInfo, boolean alreadyReported, EventHandler eventHandler) { ImmutableList<SkyKey> pathToCycle = cycleInfo.getPathToCycle(); ImmutableList<SkyKey> cycle = cycleInfo.getCycle(); if (pathToCycle.isEmpty()) { return false; }/* ww w. ja va 2 s . c o m*/ SkyKey lastPathElement = pathToCycle.get(pathToCycle.size() - 1); if (alreadyReported) { return true; } else if (Iterables.all(cycle, IS_SKYLARK_MODULE_SKY_KEY) // The last element before the cycle has to be a PackageFunction or SkylarkModule. && (IS_PACKAGE_SKY_KEY.apply(lastPathElement) || IS_SKYLARK_MODULE_SKY_KEY.apply(lastPathElement))) { Function printer = new Function<SkyKey, String>() { @Override public String apply(SkyKey input) { if (input.argument() instanceof SkylarkImportLookupValue.SkylarkImportLookupKey) { return ((SkylarkImportLookupValue.SkylarkImportLookupKey) input.argument()).importLabel .toString(); } else if (input.argument() instanceof PackageIdentifier) { return ((PackageIdentifier) input.argument()) + "/BUILD"; } else { throw new UnsupportedOperationException(); } } }; StringBuilder cycleMessage = new StringBuilder().append("cycle detected in extension files: ") .append("\n ").append(printer.apply(lastPathElement)); AbstractLabelCycleReporter.printCycle(cycleInfo.getCycle(), cycleMessage, printer); // TODO(bazel-team): it would be nice to pass the Location of the load Statement in the // BUILD file. eventHandler.handle(Event.error(null, cycleMessage.toString())); return true; } else if (Iterables.any(cycle, IS_PACKAGE_LOOKUP) && Iterables.any(cycle, IS_WORKSPACE_FILE) && (IS_REPOSITORY_DIRECTORY.apply(lastPathElement) || IS_PACKAGE_SKY_KEY.apply(lastPathElement) || IS_EXTERNAL_PACKAGE.apply(lastPathElement))) { // We have a cycle in the workspace file, report as such. Label fileLabel = (Label) Iterables.getLast(Iterables.filter(cycle, IS_AST_FILE_LOOKUP)).argument(); String repositoryName = fileLabel.getPackageIdentifier().getRepository().strippedName(); eventHandler.handle(Event.error(null, "Failed to load Skylark extension '" + fileLabel.toString() + "'.\n" + "It usually happens when the repository is not defined prior to being used.\n" + "Maybe repository '" + repositoryName + "' was defined later in your WORKSPACE file?")); return true; } return false; }
From source file:com.facebook.buck.query.AbstractBinaryOperatorExpression.java
@Override public String toString() { ImmutableList<QueryExpression> operands = getOperands(); StringBuilder result = new StringBuilder(); for (int i = 1; i < operands.size(); i++) { result.append("("); }//from ww w .java 2 s . c o m result.append(operands.get(0)); for (int i = 1; i < operands.size(); i++) { result.append(" ").append(getOperator()).append(" ").append(operands.get(i)).append(")"); } return result.toString(); }
From source file:org.waveprotocol.box.server.persistence.blocks.impl.SegmentOperationImpl.java
/** * Returns reverted {@link SegmentOperation}. * * @param context the reversed context./*from w w w.ja v a 2 s . co m*/ */ @Override public SegmentOperationImpl revert(WaveletOperationContext context) { ImmutableList<? extends WaveletOperation> ops = getOperations(); ImmutableList.Builder<WaveletOperation> reverseOps = ImmutableList.builder(); for (int i = ops.size() - 1; i >= 0; i--) { WaveletOperation operation = ops.get(i); try { Preconditions.checkArgument(operation instanceof ReversibleOperation, "Bad operation type"); reverseOps.addAll(((ReversibleOperation) operation).reverse(context)); } catch (OperationException ex) { throw new RuntimeException(ex); } } return new SegmentOperationImpl(reverseOps.build()); }
From source file:com.facebook.buck.rules.coercer.VersionMatchedCollection.java
/** * @return the only item that matches the given version map, or throw. *//*from w w w . j a va 2 s .co m*/ public T getOnlyMatchingValue(ImmutableMap<BuildTarget, Version> selected) { ImmutableList<T> matching = getMatchingValues(selected); Preconditions.checkState(!matching.isEmpty(), "no matches for %s found", selected); Preconditions.checkState(matching.size() < 2, "multiple matches for %s found: %s", selected, matching); return matching.get(0); }
From source file:com.opengamma.strata.pricer.curve.SyntheticCurveCalibrator.java
/** * Constructs the synthetic market data from an existing rates provider and the configuration of the new curves. * /*from www . j av a2 s . c om*/ * @param group the curve group definition for the synthetic curves and instruments * @param inputProvider the input rates provider * @param refData the reference data, used to resolve the trades * @return the market data */ MarketData marketData(CurveGroupDefinition group, RatesProvider inputProvider, ReferenceData refData) { // Retrieve the set of required indices and the list of required currencies Set<Index> indicesRequired = new HashSet<Index>(); List<Currency> ccyRequired = new ArrayList<>(); for (CurveGroupEntry entry : group.getEntries()) { indicesRequired.addAll(entry.getIndices()); ccyRequired.addAll(entry.getDiscountCurrencies()); } // Retrieve the required time series if present in the original provider Map<IndexQuoteId, LocalDateDoubleTimeSeries> ts = new HashMap<>(); for (Index idx : indicesRequired) { ts.put(IndexQuoteId.of(idx), inputProvider.timeSeries(idx)); } LocalDate valuationDate = inputProvider.getValuationDate(); ImmutableList<NodalCurveDefinition> curveGroups = group.getCurveDefinitions(); // Create fake market quotes of 0, only to be able to generate trades Map<MarketDataId<?>, Double> mapId0 = new HashMap<>(); for (NodalCurveDefinition entry : curveGroups) { ImmutableList<CurveNode> nodes = entry.getNodes(); for (int i = 0; i < nodes.size(); i++) { for (MarketDataId<?> key : nodes.get(i).requirements()) { mapId0.put(key, 0.0d); } } } ImmutableMarketData marketQuotes0 = ImmutableMarketData.of(valuationDate, mapId0); // Generate market quotes from the trades Map<MarketDataId<?>, Object> mapIdSy = new HashMap<>(); for (NodalCurveDefinition entry : curveGroups) { ImmutableList<CurveNode> nodes = entry.getNodes(); for (CurveNode node : nodes) { ResolvedTrade trade = node.resolvedTrade(1d, marketQuotes0, refData); double mq = measures.value(trade, inputProvider); MarketDataId<?> k = node.requirements().iterator().next(); mapIdSy.put(k, mq); } } // Generate quotes for FX pairs. The first currency is arbitrarily selected as starting point. // The crosses are automatically generated by the MarketDataFxRateProvider used in calibration. for (int loopccy = 1; loopccy < ccyRequired.size(); loopccy++) { CurrencyPair ccyPair = CurrencyPair.of(ccyRequired.get(0), ccyRequired.get(loopccy)); FxRateId fxId = FxRateId.of(ccyPair); mapIdSy.put(fxId, FxRate.of(ccyPair, inputProvider.fxRate(ccyPair))); } return MarketData.of(valuationDate, mapIdSy, ts); }
From source file:com.facebook.buck.rules.macros.QueryMacroExpander.java
private Stream<BuildTarget> extractTargets(BuildTarget target, CellPathResolver cellNames, Optional<BuildRuleResolver> resolver, ImmutableList<String> input) throws MacroException { if (input.isEmpty()) { throw new MacroException("One quoted query expression is expected with optional flags"); }//from w w w.jav a 2s . c om String queryExpression = CharMatcher.anyOf("\"'").trimFrom(input.get(0)); final GraphEnhancementQueryEnvironment env = new GraphEnhancementQueryEnvironment(resolver, targetGraph, cellNames, target, ImmutableSet.of()); try { QueryExpression parsedExp = QueryExpression.parse(queryExpression, env); HashSet<String> targetLiterals = new HashSet<>(); parsedExp.collectTargetPatterns(targetLiterals); return targetLiterals.stream().flatMap(pattern -> { try { return env.getTargetsMatchingPattern(pattern, executorService).stream(); } catch (Exception e) { throw new RuntimeException(new MacroException("Error parsing target expression", e)); } }).map(queryTarget -> { Preconditions.checkState(queryTarget instanceof QueryBuildTarget); return ((QueryBuildTarget) queryTarget).getBuildTarget(); }); } catch (QueryException e) { throw new MacroException("Error parsing query from macro", e); } }
From source file:org.jclouds.cloudsigma2.compute.functions.TemplateOptionsToStatementWithoutPublicKey.java
@Override public Statement apply(TemplateOptions options) { ImmutableList.Builder<Statement> builder = ImmutableList.builder(); if (options.getRunScript() != null) { builder.add(options.getRunScript()); }//w w w . ja v a2 s . co m if (options.getPrivateKey() != null) { builder.add(new InstallRSAPrivateKey(options.getPrivateKey())); } ImmutableList<Statement> bootstrap = builder.build(); if (bootstrap.isEmpty()) { return null; } if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) { options.nameTask("bootstrap"); } return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap); }