List of usage examples for com.google.common.base Functions toStringFunction
public static Function<Object, String> toStringFunction()
From source file:com.facebook.buck.android.ResourcesFilter.java
@Override public List<Step> getBuildSteps(BuildContext context, final BuildableContext buildableContext) { ImmutableList.Builder<Step> steps = ImmutableList.builder(); AndroidResourceDetails androidResourceDetails = androidResourceDepsFinder.getAndroidResourceDetails(); final FilterResourcesStep filterResourcesStep = createFilterResourcesStep( androidResourceDetails.resDirectories, androidResourceDetails.whitelistedStringDirs); steps.add(filterResourcesStep);//from w w w. j a v a 2 s . com final ImmutableSet<Path> resDirectories = filterResourcesStep.getOutputResourceDirs(); final Supplier<ImmutableSet<Path>> nonEnglishStringFiles = Suppliers .memoize(new Supplier<ImmutableSet<Path>>() { @Override public ImmutableSet<Path> get() { return filterResourcesStep.getNonEnglishStringFiles(); } }); for (Path outputResourceDir : resDirectories) { buildableContext.recordArtifactsInDirectory(outputResourceDir); } steps.add(new AbstractExecutionStep("record_build_output") { @Override public int execute(ExecutionContext context) { buildableContext.addMetadata(RES_DIRECTORIES_KEY, Iterables.transform(resDirectories, Functions.toStringFunction())); buildableContext.addMetadata(NON_ENGLISH_STRING_FILES_KEY, Iterables.transform(nonEnglishStringFiles.get(), Functions.toStringFunction())); return 0; } }); return steps.build(); }
From source file:org.eclipse.sirius.business.internal.movida.registry.StatusUpdater.java
private void checkActualDependencies(Entry entry) { Set<URI> declared = Sets.newHashSet(entry.getDeclaredDependencies()); // Include both the logical URIs and their corresponding physical URIs // in the declared set. Set<URI> declaredResolved = Sets.newHashSet(Iterables.transform(declared, new Function<URI, URI>() { @Override//w ww.j a v a 2 s . c o m public URI apply(URI from) { return resourceSet.getURIConverter().normalize(from); } })); declared.addAll(declaredResolved); Set<URI> actual = entry.getActualDependencies(); SetView<URI> undeclared = Sets.difference(actual, declared); if (!undeclared.isEmpty()) { entry.setState(ViewpointState.INVALID); Object[] data = Iterables.toArray(Iterables.transform(undeclared, Functions.toStringFunction()), String.class); addDiagnostic(entry, Diagnostic.ERROR, UNDECLARED_DEPENDENCY, "Sirius has undeclared dependencies to other resources.", data); //$NON-NLS-1$ } }
From source file:com.facebook.buck.android.PreDexMerge.java
private void addStepsForSplitDex(ImmutableList.Builder<Step> steps, BuildContext context, BuildableContext buildableContext) { // Collect all of the DexWithClasses objects to use for merging. ImmutableList<DexWithClasses> dexFilesToMerge = FluentIterable.from(preDexDeps) .transform(DexWithClasses.TO_DEX_WITH_CLASSES).filter(Predicates.notNull()).toList(); final SplitDexPaths paths = new SplitDexPaths(); final ImmutableSet<Path> secondaryDexDirectories = ImmutableSet.of(paths.metadataDir, paths.jarfilesDir); // Do not clear existing directory which might contain secondary dex files that are not // re-merged (since their contents did not change). steps.add(new MkdirStep(paths.jarfilesSubdir)); steps.add(new MkdirStep(paths.successDir)); steps.add(new MakeCleanDirectoryStep(paths.metadataSubdir)); steps.add(new MakeCleanDirectoryStep(paths.scratchDir)); buildableContext.addMetadata(SECONDARY_DEX_DIRECTORIES_KEY, Iterables.transform(secondaryDexDirectories, Functions.toStringFunction())); buildableContext.recordArtifact(primaryDexPath); buildableContext.recordArtifactsInDirectory(paths.jarfilesSubdir); buildableContext.recordArtifactsInDirectory(paths.metadataSubdir); buildableContext.recordArtifactsInDirectory(paths.successDir); PreDexedFilesSorter preDexedFilesSorter = new PreDexedFilesSorter(uberRDotJava.getRDotJavaDexWithClasses(), dexFilesToMerge, dexSplitMode.getPrimaryDexPatterns(), paths.scratchDir, dexSplitMode.getLinearAllocHardLimit(), dexSplitMode.getDexStore(), paths.jarfilesSubdir); final PreDexedFilesSorter.Result sortResult = preDexedFilesSorter.sortIntoPrimaryAndSecondaryDexes(context, steps);//from w ww.j av a2s . c o m steps.add(new SmartDexingStep(primaryDexPath, Suppliers.ofInstance(sortResult.primaryDexInputs), Optional.of(paths.jarfilesSubdir), Optional.of(Suppliers.ofInstance(sortResult.secondaryOutputToInputs)), sortResult.dexInputHashesProvider, paths.successDir, /* numThreads */ Optional.<Integer>absent(), AndroidBinary.DX_MERGE_OPTIONS)); // Record the primary dex SHA1 so exopackage apks can use it to compute their ABI keys. // Single dex apks cannot be exopackages, so they will never need ABI keys. steps.add(new RecordFileSha1Step(primaryDexPath, PRIMARY_DEX_HASH_KEY, buildableContext)); steps.add(new AbstractExecutionStep("write_metadata_txt") { @Override public int execute(ExecutionContext executionContext) { ProjectFilesystem filesystem = executionContext.getProjectFilesystem(); Map<Path, DexWithClasses> metadataTxtEntries = sortResult.metadataTxtDexEntries; List<String> lines = Lists.newArrayListWithCapacity(metadataTxtEntries.size()); try { for (Map.Entry<Path, DexWithClasses> entry : metadataTxtEntries.entrySet()) { Path pathToSecondaryDex = entry.getKey(); String containedClass = Iterables.get(entry.getValue().getClassNames(), 0); containedClass = containedClass.replace('/', '.'); String hash = filesystem.computeSha1(pathToSecondaryDex); lines.add( String.format("%s %s %s", pathToSecondaryDex.getFileName(), hash, containedClass)); } filesystem.writeLinesToPath(lines, paths.metadataFile); } catch (IOException e) { executionContext.logError(e, "Failed when writing metadata.txt multi-dex."); return 1; } return 0; } }); }
From source file:org.netbeans.modules.android.grammars.AndroidGrammar.java
protected Iterable<String> getChoices(AttributeInfo attr, final String prefix) { Iterable<String> values = Collections.emptySet(); if (Iterables.contains(attr.getFormats(), AttributeInfo.Format.BOOLEAN)) { values = Iterables.concat(values, Lists.newArrayList("true", "false")); }/*from w ww . ja v a 2s. com*/ if (Iterables.contains(attr.getFormats(), AttributeInfo.Format.ENUM)) { values = Iterables.concat(values, Iterables.filter(attr.getEnumValues(), startsWithPredicate(prefix))); } if (Iterables.contains(attr.getFormats(), AttributeInfo.Format.DIMENSION)) { int i = 0; while (i < prefix.length() && Character.isDigit(prefix.charAt(i))) { i++; } if (i > 0) { List<String> dimensions = Lists.newArrayList(); String number = prefix.substring(0, i); String unitPrefix = i < prefix.length() ? prefix.substring(i) : ""; for (String unit : new String[] { "dp", "sp", "pt", "mm", "in", "px" }) { if (unit.startsWith(unitPrefix)) { dimensions.add(number + unit); } } values = Iterables.concat(values, dimensions); } } if (Iterables.contains(attr.getFormats(), AttributeInfo.Format.REFERENCE)) { Iterable<String> offeredValues = Collections.emptyList(); if (prefix.startsWith("@") && prefix.indexOf('/') > 0) { offeredValues = Iterables .transform(Iterables.filter(refResolver.getReferences(), new Predicate<ResourceRef>() { @Override public boolean apply(ResourceRef input) { if (input.toString().startsWith(prefix)) { return true; } return false; } }), Functions.toStringFunction()); } else if (prefix.startsWith("@")) { final String valuePrefix = prefix.startsWith("@+") ? "@+" : "@"; offeredValues = Sets.newTreeSet(Iterables .transform(Iterables.filter(refResolver.getReferences(), new Predicate<ResourceRef>() { @Override public boolean apply(ResourceRef input) { if ((valuePrefix + input.resourceType).startsWith(prefix)) { return true; } return false; } }), new Function<ResourceRef, String>() { @Override public String apply(ResourceRef input) { return valuePrefix + input.resourceType + "/"; } })); } values = Iterables.concat(values, offeredValues); } return Iterables.filter(values, startsWithPredicate(prefix)); }
From source file:com.facebook.buck.android.UberRDotJavaBuildable.java
@Override public List<Step> getBuildSteps(BuildContext context, final BuildableContext buildableContext) throws IOException { ImmutableList.Builder<Step> steps = ImmutableList.builder(); AndroidResourceDetails androidResourceDetails = androidResourceDepsFinder.getAndroidResourceDetails(); final Set<String> rDotJavaPackages = androidResourceDetails.rDotJavaPackages; final ImmutableSet<String> resDirectories; final Supplier<ImmutableSet<String>> nonEnglishStringFiles; if (requiresResourceFilter()) { final FilterResourcesStep filterResourcesStep = createFilterResourcesStep( androidResourceDetails.resDirectories, androidResourceDetails.whitelistedStringDirs); steps.add(filterResourcesStep);//from w w w . j a va2 s . c o m resDirectories = filterResourcesStep.getOutputResourceDirs(); nonEnglishStringFiles = new Supplier<ImmutableSet<String>>() { @Override public ImmutableSet<String> get() { return FluentIterable.from(filterResourcesStep.getNonEnglishStringFiles()) .transform(Functions.toStringFunction()).toSet(); } }; for (String outputResourceDir : resDirectories) { buildableContext.recordArtifactsInDirectory(Paths.get(outputResourceDir)); } } else { resDirectories = androidResourceDetails.resDirectories; nonEnglishStringFiles = Suppliers.ofInstance(ImmutableSet.<String>of()); } if (!resDirectories.isEmpty()) { generateAndCompileRDotJavaFiles(resDirectories, rDotJavaPackages, steps, buildableContext); } steps.add(new AbstractExecutionStep("record_build_output") { @Override public int execute(ExecutionContext context) { buildableContext.addMetadata(RES_DIRECTORIES_KEY, resDirectories); buildableContext.addMetadata(NON_ENGLISH_STRING_FILES_KEY, nonEnglishStringFiles.get()); return 0; } }); return steps.build(); }
From source file:org.apache.helix.controller.strategy.AutoRebalanceStrategy.java
/** * Wrap {@link #computePartitionAssignment(List, Map, List)} with a function that takes concrete * types//from ww w . j av a 2 s . co m * @param liveNodes list of live participant ids * @param currentMapping map of partition id to map of participant id to state * @param allNodes list of all participant ids * @return the preference list and replica mapping */ public ZNRecord typedComputePartitionAssignment(final List<ParticipantId> liveNodes, final Map<PartitionId, Map<ParticipantId, State>> currentMapping, final List<ParticipantId> allNodes) { Comparator<ParticipantId> nodeComparator = new NodeComparator(); Comparator<ParticipantId> currentStateNodeComparator = new CurrentStateNodeComparator(currentMapping); List<ParticipantId> sortedLiveNodes = new ArrayList<ParticipantId>(liveNodes); Collections.sort(sortedLiveNodes, currentStateNodeComparator); List<ParticipantId> sortedAllNodes = new ArrayList<ParticipantId>(allNodes); Collections.sort(sortedAllNodes, nodeComparator); List<String> sortedNodeNames = Lists .newArrayList(Lists.transform(sortedAllNodes, Functions.toStringFunction())); int numReplicas = countStateReplicas(); ZNRecord znRecord = new ZNRecord(_resourceId.stringify()); if (sortedLiveNodes.size() == 0) { return znRecord; } int distRemainder = (numReplicas * _partitions.size()) % sortedLiveNodes.size(); int distFloor = (numReplicas * _partitions.size()) / sortedLiveNodes.size(); _nodeMap = new HashMap<ParticipantId, Node>(); _liveNodesList = new ArrayList<Node>(); for (ParticipantId id : sortedAllNodes) { Node node = new Node(id); node.capacity = 0; node.hasCeilingCapacity = false; _nodeMap.put(id, node); } for (int i = 0; i < sortedLiveNodes.size(); i++) { boolean usingCeiling = false; int targetSize = (_maximumPerNode > 0) ? Math.min(distFloor, _maximumPerNode) : distFloor; if (distRemainder > 0 && targetSize < _maximumPerNode) { targetSize += 1; distRemainder = distRemainder - 1; usingCeiling = true; } Node node = _nodeMap.get(sortedLiveNodes.get(i)); node.isAlive = true; node.capacity = targetSize; node.hasCeilingCapacity = usingCeiling; _liveNodesList.add(node); } // compute states for all replica ids _stateMap = generateStateMap(); // compute the preferred mapping if all nodes were up _preferredAssignment = computePreferredPlacement(sortedNodeNames); // logger.info("preferred mapping:"+ preferredAssignment); // from current mapping derive the ones in preferred location // this will update the nodes with their current fill status _existingPreferredAssignment = computeExistingPreferredPlacement(currentMapping); // from current mapping derive the ones not in preferred location _existingNonPreferredAssignment = computeExistingNonPreferredPlacement(currentMapping); // compute orphaned replicas that are not assigned to any node _orphaned = computeOrphaned(); if (logger.isInfoEnabled()) { logger.info("orphan = " + _orphaned); } moveNonPreferredReplicasToPreferred(); assignOrphans(); moveExcessReplicas(); prepareResult(znRecord); return znRecord; }
From source file:com.facebook.buck.event.listener.ChromeTraceBuildListener.java
@Subscribe public void ruleFinished(BuildRuleEvent.Finished finished) { writeChromeTraceEvent("buck", finished.getBuildRule().getFullyQualifiedName(), ChromeTraceEvent.Phase.END, ImmutableMap.<String, String>of("cache_result", finished.getCacheResult().toString().toLowerCase(), "success_type", finished.getSuccessType().transform(Functions.toStringFunction()).or("failed")), finished);/*w ww . ja va 2s.c o m*/ }
From source file:com.google.jimfs.PathService.java
/** * Returns the string form of the given path. *///w w w . ja va 2s . co m public String toString(JimfsPath path) { Name root = path.root(); String rootString = root == null ? null : root.toString(); Iterable<String> names = Iterables.transform(path.names(), Functions.toStringFunction()); return type.toString(rootString, names); }
From source file:com.google.cloud.storage.Cors.java
Bucket.Cors toPb() { Bucket.Cors pb = new Bucket.Cors(); pb.setMaxAgeSeconds(maxAgeSeconds);//from ww w. j a v a 2 s . co m pb.setResponseHeader(responseHeaders); if (methods != null) { pb.setMethod(newArrayList(transform(methods, Functions.toStringFunction()))); } if (origins != null) { pb.setOrigin(newArrayList(transform(origins, Functions.toStringFunction()))); } return pb; }
From source file:com.googlecode.blaisemath.svg.BlaiseGraphicsTestApp.java
@Action public void addDelegatingPointSet() { Set<String> list = new HashSet<String>(Arrays.asList("Africa", "Indiana Jones", "Micah Andrew Peterson", "Chrysanthemum", "Sequoia", "Asher Matthew Peterson", "Elisha", "Bob the Builder")); Map<String, Point2D> crds = Maps.newLinkedHashMap(); for (String s : list) { crds.put(s, new Point(10 * s.length(), 50 + 10 * s.indexOf(" "))); }//from ww w . j a v a2 s . c om DelegatingPointSetGraphic<String, Graphics2D> bp = new DelegatingPointSetGraphic<String, Graphics2D>( MarkerRenderer.getInstance(), TextRenderer.getInstance()); bp.addObjects(crds); bp.setDragEnabled(true); bp.getStyler().setLabelDelegate(Functions.toStringFunction()); bp.getStyler().setLabelStyleConstant(Styles.defaultTextStyle()); bp.getStyler().setStyleDelegate(new Function<String, AttributeSet>() { AttributeSet r = new AttributeSet(); public AttributeSet apply(String src) { int i1 = src.indexOf("a"), i2 = src.indexOf("e"), i3 = src.indexOf("i"), i4 = src.indexOf("o"); r.put(Styles.MARKER_RADIUS, i1 + 5); r.put(Styles.MARKER, Markers.getAvailableMarkers().get(i2 + 3)); r.put(Styles.STROKE, Color.BLACK); r.put(Styles.STROKE_WIDTH, 2 + i3 / 3f); r.put(Styles.FILL, new Color((i4 * 10 + 10) % 255, (i4 * 20 + 25) % 255, (i4 * 30 + 50) % 255)); return r; } }); bp.setPointSelectionEnabled(true); root1.addGraphic(bp); }