List of usage examples for com.google.common.collect ImmutableList get
E get(int index);
From source file:com.google.devtools.build.lib.bazel.rules.sh.ShBinary.java
@Override public ConfiguredTarget create(RuleContext ruleContext) throws RuleErrorException { ImmutableList<Artifact> srcs = ruleContext.getPrerequisiteArtifacts("srcs", Mode.TARGET).list(); if (srcs.size() != 1) { ruleContext.attributeError("srcs", "you must specify exactly one file in 'srcs'"); return null; }//from w w w . j a v a 2s . c om Artifact symlink = ruleContext.createOutputArtifact(); // Note that src is used as the executable script too Artifact src = srcs.get(0); // The interpretation of this deceptively simple yet incredibly generic rule is complicated // by the distinction between targets and (not properly encapsulated) artifacts. It depends // on the notion of other rule's "files-to-build" sets, which are undocumented, making it // impossible to give a precise definition of what this rule does in all cases (e.g. what // happens when srcs = ['x', 'y'] but 'x' is an empty filegroup?). This is a pervasive // problem in Blaze. ruleContext.registerAction(new ExecutableSymlinkAction(ruleContext.getActionOwner(), src, symlink)); NestedSet<Artifact> filesToBuild = NestedSetBuilder.<Artifact>stableOrder().add(src).add(symlink).build(); Runfiles runfiles = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addTransitiveArtifacts(filesToBuild) .addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES).build(); RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable(ruleContext, runfiles, symlink); return new RuleConfiguredTargetBuilder(ruleContext).setFilesToBuild(filesToBuild) .setRunfilesSupport(runfilesSupport, symlink) .addProvider(RunfilesProvider.class, RunfilesProvider.simple(runfiles)).build(); }
From source file:com.google.errorprone.bugpatterns.AnnotationPosition.java
private Description handle(Tree tree, Name name, ModifiersTree modifiers, VisitorState state) { List<? extends AnnotationTree> annotations = modifiers.getAnnotations(); if (annotations.isEmpty()) { return NO_MATCH; }/* ww w . j a v a 2 s.c o m*/ int treePos = ((JCTree) tree).getStartPosition(); List<ErrorProneToken> tokens = annotationTokens(tree, state, treePos); Comment danglingJavadoc = findOrphanedJavadoc(name, tokens); ImmutableList<ErrorProneToken> modifierTokens = tokens.stream().filter(t -> MODIFIERS.contains(t.kind())) .collect(toImmutableList()); if (!modifierTokens.isEmpty()) { int firstModifierPos = treePos + modifierTokens.get(0).pos(); int lastModifierPos = treePos + getLast(modifierTokens).endPos(); Description description = checkAnnotations(tree, treePos, annotations, danglingJavadoc, firstModifierPos, lastModifierPos, state); if (!description.equals(NO_MATCH)) { return description; } } if (danglingJavadoc != null) { SuggestedFix.Builder builder = SuggestedFix.builder(); String javadoc = removeJavadoc(state, treePos, danglingJavadoc, builder); String message = "Javadocs should appear before any modifiers or annotations."; return buildDescription(tree).setMessage(message).addFix(builder.prefixWith(tree, javadoc).build()) .build(); } return NO_MATCH; }
From source file:org.locationtech.geogig.osm.cli.commands.OSMExport.java
private Iterator<EntityContainer> getFeatures(String ref) { Optional<ObjectId> id = geogig.command(RevParse.class).setRefSpec(ref).call(); if (!id.isPresent()) { return Iterators.emptyIterator(); }/*from w w w. ja v a 2s . c o m*/ LsTreeOp op = geogig.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES) .setReference(ref); if (bbox != null) { final Envelope env; try { env = new Envelope(Double.parseDouble(bbox.get(0)), Double.parseDouble(bbox.get(2)), Double.parseDouble(bbox.get(1)), Double.parseDouble(bbox.get(3))); } catch (NumberFormatException e) { throw new IllegalArgumentException("Wrong bbox definition"); } Predicate<Bounded> filter = new Predicate<Bounded>() { @Override public boolean apply(final Bounded bounded) { boolean intersects = bounded.intersects(env); return intersects; } }; op.setBoundsFilter(filter); } Iterator<NodeRef> iterator = op.call(); final EntityConverter converter = new EntityConverter(); Function<NodeRef, EntityContainer> function = new Function<NodeRef, EntityContainer>() { @Override @Nullable public EntityContainer apply(@Nullable NodeRef ref) { RevFeature revFeature = geogig.command(RevObjectParse.class).setObjectId(ref.objectId()) .call(RevFeature.class).get(); SimpleFeatureType featureType; if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) { featureType = OSMUtils.nodeType(); } else { featureType = OSMUtils.wayType(); } SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); RevFeatureType revFeatureType = RevFeatureTypeImpl.build(featureType); List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = revFeature.getValues(); for (int i = 0; i < descriptors.size(); i++) { PropertyDescriptor descriptor = descriptors.get(i); Optional<Object> value = values.get(i); featureBuilder.set(descriptor.getName(), value.orNull()); } SimpleFeature feature = featureBuilder.buildFeature(ref.name()); Entity entity = converter.toEntity(feature, null); EntityContainer container; if (entity instanceof Node) { container = new NodeContainer((Node) entity); } else { container = new WayContainer((Way) entity); } return container; } }; return Iterators.transform(iterator, function); }
From source file:org.geogit.osm.out.cli.OSMExport.java
private Iterator<EntityContainer> getFeatures(String ref) { Optional<ObjectId> id = geogit.command(RevParse.class).setRefSpec(ref).call(); if (!id.isPresent()) { return Iterators.emptyIterator(); }/*from ww w. java2 s . c om*/ LsTreeOp op = geogit.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES) .setReference(ref); if (bbox != null) { final Envelope env; try { env = new Envelope(Double.parseDouble(bbox.get(0)), Double.parseDouble(bbox.get(2)), Double.parseDouble(bbox.get(1)), Double.parseDouble(bbox.get(3))); } catch (NumberFormatException e) { throw new IllegalArgumentException("Wrong bbox definition"); } Predicate<Bounded> filter = new Predicate<Bounded>() { @Override public boolean apply(final Bounded bounded) { boolean intersects = bounded.intersects(env); return intersects; } }; op.setBoundsFilter(filter); } Iterator<NodeRef> iterator = op.call(); final EntityConverter converter = new EntityConverter(); Function<NodeRef, EntityContainer> function = new Function<NodeRef, EntityContainer>() { @Override @Nullable public EntityContainer apply(@Nullable NodeRef ref) { RevFeature revFeature = geogit.command(RevObjectParse.class).setObjectId(ref.objectId()) .call(RevFeature.class).get(); SimpleFeatureType featureType; if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) { featureType = OSMUtils.nodeType(); } else { featureType = OSMUtils.wayType(); } SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); RevFeatureType revFeatureType = RevFeatureType.build(featureType); List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> values = revFeature.getValues(); for (int i = 0; i < descriptors.size(); i++) { PropertyDescriptor descriptor = descriptors.get(i); Optional<Object> value = values.get(i); featureBuilder.set(descriptor.getName(), value.orNull()); } SimpleFeature feature = featureBuilder.buildFeature(ref.name()); Entity entity = converter.toEntity(feature); EntityContainer container; if (entity instanceof Node) { container = new NodeContainer((Node) entity); } else { container = new WayContainer((Way) entity); } return container; } }; return Iterators.transform(iterator, function); }
From source file:com.github.rinde.rinsim.central.GlobalStateObject.java
/** * Constructs a new {@link GlobalStateObject} using the routes specified. * @param routes The routes to use, this will replace any existing routes in * the vehicles. Exactly one route must be specified for each * vehicle.//from ww w.j av a 2 s . c o m * @return A newly constructed {@link GlobalStateObject} that only differs * from the current object in the vehicles' routes. */ public GlobalStateObject withRoutes(ImmutableList<ImmutableList<Parcel>> routes) { checkArgument(routes.size() == getVehicles().size()); final ImmutableList.Builder<VehicleStateObject> b = ImmutableList.builder(); for (int i = 0; i < getVehicles().size(); i++) { b.add(getVehicles().get(i).withRoute(routes.get(i))); } return create(getAvailableParcels(), b.build(), getTime(), getTimeUnit(), getSpeedUnit(), getDistUnit()); }
From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java
/** * Take a List of configuration layers and try to fit it into the xcode configuration layers * layout.// w w w . ja va2 s . c o m * * @throws com.facebook.buck.util.HumanReadableException if the configuration layers are not in * the right layout to be coerced into standard xcode layout. */ private static ConfigInXcodeLayout extractXcodeConfigurationLayers(BuildTarget buildTarget, XcodeRuleConfiguration configuration) { ConfigInXcodeLayout extractedLayers = null; ImmutableList<XcodeRuleConfiguration.Layer> layers = configuration.getLayers(); switch (layers.size()) { case 2: if (layers.get(0).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(1).getLayerType() == XcodeRuleConfiguration.LayerType.FILE) { extractedLayers = new ConfigInXcodeLayout(buildTarget, layers.get(0).getPath(), ImmutableMap.<String, String>of(), layers.get(1).getPath(), ImmutableMap.<String, String>of()); } break; case 4: if (layers.get(0).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(1).getLayerType() == XcodeRuleConfiguration.LayerType.INLINE_SETTINGS && layers.get(2).getLayerType() == XcodeRuleConfiguration.LayerType.FILE && layers.get(3).getLayerType() == XcodeRuleConfiguration.LayerType.INLINE_SETTINGS) { extractedLayers = new ConfigInXcodeLayout(buildTarget, layers.get(0).getPath(), layers.get(1).getInlineSettings().or(ImmutableMap.<String, String>of()), layers.get(2).getPath(), layers.get(3).getInlineSettings().or(ImmutableMap.<String, String>of())); } break; default: // handled later on by the fact that extractLayers is null break; } if (extractedLayers == null) { throw new HumanReadableException("Configuration layers cannot be expressed in xcode for target: " + buildTarget + "\n" + " expected: [File, Inline settings, File, Inline settings]"); } return extractedLayers; }
From source file:org.apache.cloudstack.utils.CloudStackVersion.java
/** * {@inheritDoc}/*ww w.j av a 2 s . co m*/ * * A couple of notes about the comparison rules for this method: * <ul> * <li>Three position versions are normalized to four position versions with the security release being * defaulted to zero (0). For example, for the purposes of comparision, <code>4.8.1</code> would be * normalized to <code>4.8.1.0</code> for all comparison operations.</li> * <li>A three position version with a null security release is considered equal to a four position * version number where the major release, minor release, and patch release are the same and the security * release for the four position version is zero (0). Therefore, the results of this method are <b>not</b> * symmetric with <code>equals</code></li> * <li>When comparing to <code>null</code>, this version is always considered greater than (i.e. returning * a value greater than zero (0).</li> * </ul> * * @param thatVersion The version to which to compare this instance * * @return A value less than zero (0) indicates this version is less than <code>thatVersion</code>. A value * equal to zero (0) indicates this value equals <code>thatValue</code>. A value greater than zero (0) * indicates this version is greater than <code>thatVersion</code>. * * @since 4.8.2.0 * */ @Override public int compareTo(final CloudStackVersion thatVersion) { if (thatVersion == null) { return 1; } // Normalize the versions to be 4 positions for the purposes of comparison ... final ImmutableList<Integer> values = normalizeVersionValues(asList()); final ImmutableList<Integer> thoseValues = normalizeVersionValues(thatVersion.asList()); for (int i = 0; i < values.size(); i++) { final int result = values.get(i).compareTo(thoseValues.get(i)); if (result != 0) { return result; } } return 0; }
From source file:org.apache.calcite.rel.metadata.RelMdSize.java
public List<Double> averageColumnSizes(Values rel, RelMetadataQuery mq) { final List<RelDataTypeField> fields = rel.getRowType().getFieldList(); final ImmutableList.Builder<Double> list = ImmutableList.builder(); for (int i = 0; i < fields.size(); i++) { RelDataTypeField field = fields.get(i); double d; if (rel.getTuples().isEmpty()) { d = averageTypeValueSize(field.getType()); } else {//from www . java2 s.c o m d = 0; for (ImmutableList<RexLiteral> literals : rel.getTuples()) { d += typeValueSize(field.getType(), literals.get(i).getValue()); } d /= rel.getTuples().size(); } list.add(d); } return list.build(); }
From source file:com.google.devtools.build.lib.remote.TreeNodeRepository.java
@SuppressWarnings("ReferenceEquality") // Segments are interned. private TreeNode buildParentNode(ImmutableList<ActionInput> inputs, ImmutableList<ImmutableList<String>> segments, int inputsStart, int inputsEnd, int segmentIndex) { if (segmentIndex == segments.get(inputsStart).size()) { // Leaf node reached. Must be unique. Preconditions.checkArgument(inputsStart == inputsEnd - 1, "Encountered two inputs with the same path."); // TODO: check that the actionInput is a single file! return interner.intern(new TreeNode(inputs.get(inputsStart))); }/*from w w w. j a va2 s. com*/ ArrayList<TreeNode.ChildEntry> entries = new ArrayList<>(); String segment = segments.get(inputsStart).get(segmentIndex); for (int inputIndex = inputsStart; inputIndex < inputsEnd; ++inputIndex) { if (inputIndex + 1 == inputsEnd || segment != segments.get(inputIndex + 1).get(segmentIndex)) { entries.add(new TreeNode.ChildEntry(segment, buildParentNode(inputs, segments, inputsStart, inputIndex + 1, segmentIndex + 1))); if (inputIndex + 1 < inputsEnd) { inputsStart = inputIndex + 1; segment = segments.get(inputsStart).get(segmentIndex); } } } return interner.intern(new TreeNode(entries)); }
From source file:com.google.devtools.build.remote.RemoteWorker.java
public ExecuteReply execute(Action action, Path execRoot) throws IOException, InterruptedException { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); try {/*from ww w . j a v a 2 s . co m*/ RemoteProtocol.Command command = RemoteProtocol.Command .parseFrom(cache.downloadBlob(action.getCommandDigest())); cache.downloadTree(action.getInputRootDigest(), execRoot); List<Path> outputs = new ArrayList<>(action.getOutputPathList().size()); for (String output : action.getOutputPathList()) { Path file = execRoot.getRelative(output); if (file.exists()) { throw new FileAlreadyExistsException("Output file already exists: " + file); } FileSystemUtils.createDirectoryAndParents(file.getParentDirectory()); outputs.add(file); } // TODO(olaola): time out after specified server-side deadline. Command cmd = new Command(command.getArgvList().toArray(new String[] {}), getEnvironmentVariables(command), new File(execRoot.getPathString())); cmd.execute(Command.NO_INPUT, Command.NO_OBSERVER, stdout, stderr, true); // Execute throws a CommandException on non-zero return values, so action has succeeded. ImmutableList<ContentDigest> outErrDigests = cache .uploadBlobs(ImmutableList.of(stdout.toByteArray(), stderr.toByteArray())); ActionResult.Builder result = ActionResult.newBuilder().setReturnCode(0) .setStdoutDigest(outErrDigests.get(0)).setStderrDigest(outErrDigests.get(1)); cache.uploadAllResults(execRoot, outputs, result); cache.setCachedActionResult(ContentDigests.computeActionKey(action), result.build()); return ExecuteReply.newBuilder().setResult(result) .setStatus(ExecutionStatus.newBuilder().setExecuted(true).setSucceeded(true)).build(); } catch (CommandException e) { ImmutableList<ContentDigest> outErrDigests = cache .uploadBlobs(ImmutableList.of(stdout.toByteArray(), stderr.toByteArray())); final int returnCode = e instanceof AbnormalTerminationException ? ((AbnormalTerminationException) e).getResult().getTerminationStatus().getExitCode() : -1; return ExecuteReply.newBuilder() .setResult(ActionResult.newBuilder().setReturnCode(returnCode) .setStdoutDigest(outErrDigests.get(0)).setStderrDigest(outErrDigests.get(1))) .setStatus(ExecutionStatus.newBuilder().setExecuted(true).setSucceeded(false) .setError(ExecutionStatus.ErrorCode.EXEC_FAILED).setErrorDetail(e.toString())) .build(); } catch (CacheNotFoundException e) { LOG.warning("Cache miss on " + ContentDigests.toString(e.getMissingDigest())); return ExecuteReply.newBuilder() .setCasError(CasStatus.newBuilder().setSucceeded(false).addMissingDigest(e.getMissingDigest()) .setError(CasStatus.ErrorCode.MISSING_DIGEST).setErrorDetail(e.toString())) .setStatus(ExecutionStatus.newBuilder().setExecuted(false).setSucceeded(false) .setError(e.getMissingDigest() == action.getCommandDigest() ? ExecutionStatus.ErrorCode.MISSING_COMMAND : ExecutionStatus.ErrorCode.MISSING_INPUT) .setErrorDetail(e.toString())) .build(); } }