List of usage examples for com.google.common.collect ImmutableList size
int size();
From source file:com.google.template.soy.jbcsrc.restricted.BytecodeUtils.java
/** Returns an expression that returns a new {@link ArrayList} containing all the given items. */ public static Expression asList(Iterable<? extends Expression> items) { final ImmutableList<Expression> copy = ImmutableList.copyOf(items); if (copy.isEmpty()) { return MethodRef.IMMUTABLE_LIST_OF.get(0).invoke(); }/*from ww w . j av a 2s . c om*/ // Note, we cannot necessarily use ImmutableList for anything besides the empty list because // we may need to put a null in it. final Expression construct = ConstructorRef.ARRAY_LIST_SIZE.construct(constant(copy.size())); return new Expression(ARRAY_LIST_TYPE, Feature.NON_NULLABLE) { @Override protected void doGen(CodeBuilder mv) { construct.gen(mv); for (Expression child : copy) { mv.dup(); child.gen(mv); MethodRef.ARRAY_LIST_ADD.invokeUnchecked(mv); mv.pop(); // pop the bool result of arraylist.add } } }; }
From source file:dagger.internal.codegen.writer.EnumWriter.java
@Override public Appendable write(Appendable appendable, Context context) throws IOException { context = context.createSubcontext(//from ww w. ja va 2 s.c om FluentIterable.from(nestedTypeWriters).transform(new Function<TypeWriter, ClassName>() { @Override public ClassName apply(TypeWriter input) { return input.name; } }).toSet()); writeAnnotations(appendable, context); writeModifiers(appendable).append("enum ").append(name.simpleName()); Iterator<TypeName> implementedTypesIterator = implementedTypes.iterator(); if (implementedTypesIterator.hasNext()) { appendable.append(" implements "); implementedTypesIterator.next().write(appendable, context); while (implementedTypesIterator.hasNext()) { appendable.append(", "); implementedTypesIterator.next().write(appendable, context); } } appendable.append(" {"); checkState(!constantWriters.isEmpty(), "Cannot write an enum with no constants."); appendable.append('\n'); ImmutableList<ConstantWriter> constantWriterList = ImmutableList.copyOf(constantWriters.values()); for (ConstantWriter constantWriter : constantWriterList.subList(0, constantWriterList.size() - 1)) { constantWriter.write(appendable, context); appendable.append(",\n"); } constantWriterList.get(constantWriterList.size() - 1).write(appendable, context); appendable.append(";\n"); if (!fieldWriters.isEmpty()) { appendable.append('\n'); } for (VariableWriter fieldWriter : fieldWriters.values()) { fieldWriter.write(new IndentingAppendable(appendable), context).append("\n"); } for (ConstructorWriter constructorWriter : constructorWriters) { appendable.append('\n'); if (!isDefaultConstructor(constructorWriter)) { constructorWriter.write(new IndentingAppendable(appendable), context); } } for (MethodWriter methodWriter : methodWriters) { appendable.append('\n'); methodWriter.write(new IndentingAppendable(appendable), context); } for (TypeWriter nestedTypeWriter : nestedTypeWriters) { appendable.append('\n'); nestedTypeWriter.write(new IndentingAppendable(appendable), context); } appendable.append("}\n"); return appendable; }
From source file:org.geogit.api.plumbing.diff.FeatureDiff.java
/** * /*w w w .j a v a 2 s. c o m*/ * @param path the full path to the feature, including its name * @param newRevFeature the new version of the feature * @param oldRevFeature the old version of the feature * @param newRevFeatureType the new version of the feature type * @param oldRevFeatureType the old version of the feature type * @param all - true if all attributes should be added regardless of change */ public FeatureDiff(String path, RevFeature newRevFeature, RevFeature oldRevFeature, RevFeatureType newRevFeatureType, RevFeatureType oldRevFeatureType, boolean all) { this.path = path; this.newFeatureType = newRevFeatureType; this.oldFeatureType = oldRevFeatureType; diffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.sortedDescriptors(); ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> oldValues = oldRevFeature.getValues(); ImmutableList<Optional<Object>> newValues = newRevFeature.getValues(); BitSet updatedAttributes = new BitSet(newValues.size()); for (int i = 0; i < oldAttributes.size(); i++) { Optional<Object> oldValue = oldValues.get(i); int idx = newAttributes.indexOf(oldAttributes.get(i)); if (idx != -1) { Optional<Object> newValue = newValues.get(idx); if (!oldValue.equals(newValue) || all) { if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) { diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()), Optional.fromNullable((Geometry) newValue.orNull()))); } else { diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, newValue)); } } updatedAttributes.set(idx); } else { if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) { diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()), Optional.fromNullable((Geometry) null))); } else { diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, null)); } } } updatedAttributes.flip(0, newValues.size()); for (int i = updatedAttributes.nextSetBit(0); i >= 0; i = updatedAttributes.nextSetBit(i + 1)) { if (Geometry.class.isAssignableFrom(newAttributes.get(i).getType().getBinding())) { diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) null), Optional.fromNullable((Geometry) newValues.get(i).orNull()))); } else { diffs.put(newAttributes.get(i), new GenericAttributeDiffImpl(null, newValues.get(i))); } } }
From source file:org.geogit.osm.changeset.internal.CreateOSMChangesetOp.java
/** * Executes the diff operation./*from ww w .j a va 2 s .c om*/ * * @return an iterator to a set of differences between the two trees * @see DiffEntry */ @Override public Iterator<ChangeContainer> call() { Iterator<DiffEntry> nodeIterator = command(DiffOp.class).setFilter(OSMUtils.NODE_TYPE_NAME) .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call(); Iterator<DiffEntry> wayIterator = command(DiffOp.class).setFilter(OSMUtils.WAY_TYPE_NAME) .setNewVersion(newRefSpec).setOldVersion(oldRefSpec).setReportTrees(false).call(); Iterator<DiffEntry> iterator = Iterators.concat(nodeIterator, wayIterator); final EntityConverter converter = new EntityConverter(); Function<DiffEntry, ChangeContainer> function = new Function<DiffEntry, ChangeContainer>() { @Override @Nullable public ChangeContainer apply(@Nullable DiffEntry diff) { NodeRef ref = diff.changeType().equals(ChangeType.REMOVED) ? diff.getOldObject() : diff.getNewObject(); RevFeature revFeature = command(RevObjectParse.class).setObjectId(ref.objectId()) .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.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); } ChangeAction action = diff.changeType().equals(ChangeType.ADDED) ? ChangeAction.Create : diff.changeType().equals(ChangeType.MODIFIED) ? ChangeAction.Modify : ChangeAction.Delete; return new ChangeContainer(container, action); } }; return Iterators.transform(iterator, function); }
From source file:google.registry.backup.GcsDiffFileLister.java
List<GcsFileMetadata> listDiffFiles(DateTime fromTime) { logger.info("Requested restore from time: " + fromTime); // List all of the diff files on GCS and build a map from each file's upper checkpoint time // (extracted from the filename) to its asynchronously-loaded metadata, keeping only files with // an upper checkpoint time > fromTime. Map<DateTime, ListenableFuture<GcsFileMetadata>> upperBoundTimesToMetadata = new HashMap<>(); Iterator<ListItem> listItems; try {/*from w w w.j a v a 2 s . c o m*/ // TODO(b/23554360): Use a smarter prefixing strategy to speed this up. listItems = gcsService.list(gcsBucket, new ListOptions.Builder().setPrefix(DIFF_FILE_PREFIX).build()); } catch (IOException e) { throw new RuntimeException(e); } DateTime lastUpperBoundTime = START_OF_TIME; while (listItems.hasNext()) { final String filename = listItems.next().getName(); DateTime upperBoundTime = DateTime.parse(filename.substring(DIFF_FILE_PREFIX.length())); if (isBeforeOrAt(fromTime, upperBoundTime)) { upperBoundTimesToMetadata.put(upperBoundTime, executor.submit(new Callable<GcsFileMetadata>() { @Override public GcsFileMetadata call() throws Exception { return getMetadata(filename); } })); } lastUpperBoundTime = latestOf(upperBoundTime, lastUpperBoundTime); } if (upperBoundTimesToMetadata.isEmpty()) { logger.info("No files found"); return ImmutableList.of(); } // GCS file listing is eventually consistent, so it's possible that we are missing a file. The // metadata of a file is sufficient to identify the preceding file, so if we start from the // last file and work backwards we can verify that we have no holes in our chain (although we // may be missing files at the end). ImmutableList.Builder<GcsFileMetadata> filesBuilder = new ImmutableList.Builder<>(); logger.info("Restoring until: " + lastUpperBoundTime); DateTime checkpointTime = lastUpperBoundTime; while (checkpointTime.isAfter(fromTime)) { GcsFileMetadata metadata; if (upperBoundTimesToMetadata.containsKey(checkpointTime)) { metadata = Futures.getUnchecked(upperBoundTimesToMetadata.get(checkpointTime)); } else { String filename = DIFF_FILE_PREFIX + checkpointTime; logger.info("Patching GCS list; discovered file " + filename); metadata = getMetadata(filename); checkState(metadata != null, "Could not read metadata for file %s", filename); } filesBuilder.add(metadata); checkpointTime = getLowerBoundTime(metadata); } ImmutableList<GcsFileMetadata> files = filesBuilder.build().reverse(); logger.info("Actual restore from time: " + getLowerBoundTime(files.get(0))); logger.infofmt("Found %d files to restore", files.size()); return files; }
From source file:org.locationtech.geogig.api.plumbing.diff.FeatureDiff.java
/** * /* ww w . j ava2s.c o m*/ * @param path the full path to the feature, including its name * @param newRevFeature the new version of the feature * @param oldRevFeature the old version of the feature * @param newRevFeatureType the new version of the feature type * @param oldRevFeatureType the old version of the feature type * @param all - true if all attributes should be added regardless of change */ public FeatureDiff(String path, RevFeature newRevFeature, RevFeature oldRevFeature, RevFeatureType newRevFeatureType, RevFeatureType oldRevFeatureType, boolean all) { this.path = path; this.newFeatureType = newRevFeatureType; this.oldFeatureType = oldRevFeatureType; diffs = new HashMap<PropertyDescriptor, AttributeDiff>(); ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.sortedDescriptors(); ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.sortedDescriptors(); ImmutableList<Optional<Object>> oldValues = oldRevFeature.getValues(); ImmutableList<Optional<Object>> newValues = newRevFeature.getValues(); BitSet updatedAttributes = new BitSet(newValues.size()); for (int i = 0; i < oldAttributes.size(); i++) { Optional<Object> oldValue = oldValues.get(i); int idx = newAttributes.indexOf(oldAttributes.get(i)); if (idx != -1) { Optional<Object> newValue = newValues.get(idx); if (!oldValue.equals(newValue) || all) { if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) { diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()), Optional.fromNullable((Geometry) newValue.orNull()))); } else { diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, newValue)); } } updatedAttributes.set(idx); } else { if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) { diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()), Optional.fromNullable((Geometry) null))); } else { diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, null)); } } } updatedAttributes.flip(0, newValues.size()); for (int i = updatedAttributes.nextSetBit(0); i >= 0; i = updatedAttributes.nextSetBit(i + 1)) { if (Geometry.class.isAssignableFrom(newAttributes.get(i).getType().getBinding())) { diffs.put(newAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) null), Optional.fromNullable((Geometry) newValues.get(i).orNull()))); } else { diffs.put(newAttributes.get(i), new GenericAttributeDiffImpl(null, newValues.get(i))); } } }
From source file:com.facebook.buck.features.js.JsBundleGenrule.java
@Override public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) { SourcePathResolver sourcePathResolver = context.getSourcePathResolver(); ImmutableList<Step> buildSteps = super.getBuildSteps(context, buildableContext); OptionalInt lastRmStep = IntStream.range(0, buildSteps.size()).map(x -> buildSteps.size() - 1 - x) .filter(i -> buildSteps.get(i) instanceof RmStep).findFirst(); Preconditions.checkState(lastRmStep.isPresent(), "Genrule is expected to have at least on RmDir step"); ImmutableList.Builder<Step> builder = ImmutableList.<Step>builder() // First, all Genrule steps including the last RmDir step are added .addAll(buildSteps.subList(0, lastRmStep.getAsInt() + 1)) // Our MkdirStep must run after all RmSteps created by Genrule to prevent immediate // deletion of the directory. It must, however, run before the genrule command itself // runs. .add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), sourcePathResolver.getRelativePath(getSourcePathToOutput())))); if (rewriteSourcemap) { // If the genrule rewrites the source map, we have to create the parent dir, and record // the build artifact SourcePath sourcePathToSourceMap = getSourcePathToSourceMap(); buildableContext.recordArtifact(sourcePathResolver.getRelativePath(sourcePathToSourceMap)); builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(),//w w w. ja va2 s. c om sourcePathResolver.getRelativePath(sourcePathToSourceMap).getParent()))); } if (rewriteMisc) { // If the genrule rewrites the misc folder, we have to create the corresponding dir, and // record its contents SourcePath miscDirPath = getSourcePathToMisc(); buildableContext.recordArtifact(sourcePathResolver.getRelativePath(miscDirPath)); builder.add(MkdirStep.of(BuildCellRelativePath.fromCellRelativePath(context.getBuildCellRootPath(), getProjectFilesystem(), sourcePathResolver.getRelativePath(miscDirPath)))); } if (rewriteDepsFile) { // If the genrule rewrites the dependencies file, we have to record its contents SourcePath dependenciesFilePath = getSourcePathToDepsFile(); buildableContext.recordArtifact(sourcePathResolver.getRelativePath(dependenciesFilePath)); } // Last, we add all remaining genrule commands after the last RmStep return builder.addAll(buildSteps.subList(lastRmStep.getAsInt() + 1, buildSteps.size())).build(); }
From source file:com.google.template.soy.incrementaldomsrc.IncrementalDomSrcMain.java
/** * Generates Incremental DOM JS source files given a Soy parse tree, an options object, an * optional bundle of translated messages, and information on where to put the output files. * * @param soyTree The Soy parse tree to generate JS source code for. * @param jsSrcOptions The compilation options relevant to this backend. * @param outputPathFormat The format string defining how to build the output file path * corresponding to an input file path. * @throws SoySyntaxException If a syntax error is found. * @throws IOException If there is an error in opening/writing an output JS file. *//*from w ww . j a v a 2s . c om*/ public void genJsFiles(SoyFileSetNode soyTree, SoyJsSrcOptions jsSrcOptions, String outputPathFormat) throws SoySyntaxException, IOException { List<String> jsFileContents = genJsSrc(soyTree, jsSrcOptions); ImmutableList<SoyFileNode> srcsToCompile = ImmutableList .copyOf(Iterables.filter(soyTree.getChildren(), SoyFileNode.MATCH_SRC_FILENODE)); if (srcsToCompile.size() != jsFileContents.size()) { throw new AssertionError(String.format("Expected to generate %d code chunk(s), got %d", srcsToCompile.size(), jsFileContents.size())); } Multimap<String, Integer> outputs = MainEntryPointUtils.mapOutputsToSrcs(null /* locale */, outputPathFormat, "" /* inputPathsPrefix */, srcsToCompile); for (String outputFilePath : outputs.keySet()) { Writer out = Files.newWriter(new File(outputFilePath), UTF_8); try { boolean isFirst = true; for (int inputFileIndex : outputs.get(outputFilePath)) { if (isFirst) { isFirst = false; } else { // Concatenating JS files is not safe unless we know that the last statement from one // couldn't combine with the isFirst statement of the next. Inserting a semicolon will // prevent this from happening. out.write("\n;\n"); } out.write(jsFileContents.get(inputFileIndex)); } } finally { out.close(); } } }
From source file:com.facebook.buck.core.cell.AbstractCellConfig.java
/** * Translates the 'cell name'->override map into a 'Path'->override map. * * @param pathMapping a map containing paths to all of the cells we want to query. * @return 'Path'->override map/*ww w. j a v a 2s . c o m*/ */ public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<CellName, Path> pathMapping) throws InvalidCellOverrideException { ImmutableSet<CellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet()) .filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals)).toSet(); ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder(); for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) { if (!pathMapping.containsKey(cellWithOverride)) { throw new InvalidCellOverrideException( String.format("Trying to override settings for unknown cell %s", cellWithOverride)); } pathsWithOverrides.add(pathMapping.get(cellWithOverride)); } ImmutableMultimap<Path, CellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping)); for (Path pathWithOverrides : pathsWithOverrides.build()) { ImmutableList<CellName> namesForPath = RichStream.from(pathToRelativeName.get(pathWithOverrides)) .filter(name -> name.getLegacyName().isPresent()).toImmutableList(); if (namesForPath.size() > 1) { throw new InvalidCellOverrideException( String.format("Configuration override is ambiguous: cell rooted at %s is reachable " + "as [%s]. Please override the config by placing a .buckconfig.local file in the " + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath))); } } Map<Path, RawConfig> overridesByPath = new HashMap<>(); for (Map.Entry<CellName, Path> entry : pathMapping.entrySet()) { CellName cellRelativeName = entry.getKey(); Path cellPath = entry.getValue(); RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath); RawConfig config = getForCell(cellRelativeName); if (configFromOtherRelativeName != null) { // Merge configs RawConfig mergedConfig = RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config) .build(); overridesByPath.put(cellPath, mergedConfig); } else { overridesByPath.put(cellPath, config); } } return ImmutableMap.copyOf(overridesByPath); }
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; }/*from w w w .j a v a 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; }