List of usage examples for com.google.common.base Functions toStringFunction
public static Function<Object, String> toStringFunction()
From source file:com.flaptor.indextank.suggest.PopularityIndex.java
public List<String> getMostPopular(String str) { str = normalize(str);// w w w .j a v a 2 s .com Leaf leaf; try { leaf = search(str, root); } catch (UnsupportedCharacterException e) { if (logger.isDebugEnabled()) { logger.debug("String with unsupported character, returning no suggestions. Problematic string is \"" + str + "\", character is \"" + e.getCharacter() + "\""); } return new ArrayList<String>(0); } if (leaf == null) { return ImmutableList.of(); } List<Leaf> sorted; if (leaf.suggestions == null) { sorted = ImmutableList.of(); } else { sorted = Ordering.natural().sortedCopy(leaf.suggestions); } return Lists.transform(sorted, Functions.toStringFunction()); }
From source file:org.eclipse.sirius.business.internal.movida.registry.StatusUpdater.java
private void checkAllActualDependenciesAreAvailable(Entry entry) { Set<URI> actualPhysical = ImmutableSet .copyOf(Iterables.transform(entry.getActualDependencies(), new Function<URI, URI>() { @Override/*from www . j a v a2 s .co m*/ public URI apply(URI from) { return resourceSet.getURIConverter().normalize(from); } })); Set<URI> availablePhysical = ImmutableSet .copyOf(Iterables.transform(entries.values(), new Function<Entry, URI>() { @Override public URI apply(Entry from) { return from.getResource().getURI(); }; })); Set<URI> unavailable = Sets.difference(actualPhysical, availablePhysical); if (!unavailable.isEmpty()) { entry.setState(ViewpointState.INVALID); Object[] data = Iterables.toArray(Iterables.transform(unavailable, Functions.toStringFunction()), String.class); addDiagnostic(entry, Diagnostic.ERROR, PHYSICAL_DEPENDENCY_UNAVAILABLE, "Sirius definition depends on resources not available.", data); //$NON-NLS-1$ } }
From source file:com.facebook.buck.java.Jsr199Javac.java
@Override public int buildWithClasspath(ExecutionContext context, ProjectFilesystem filesystem, SourcePathResolver resolver, BuildTarget invokingRule, ImmutableList<String> options, ImmutableSet<Path> javaSourceFilePaths, Optional<Path> pathToSrcsList, Optional<Path> workingDirectory) { JavaCompiler compiler = createCompiler(context, resolver); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = ImmutableSet.of(); try {/* w w w . j a v a2 s . c o m*/ compilationUnits = createCompilationUnits(fileManager, filesystem.getAbsolutifier(), javaSourceFilePaths); } catch (IOException e) { close(fileManager, compilationUnits); e.printStackTrace(context.getStdErr()); return 1; } if (pathToSrcsList.isPresent()) { // write javaSourceFilePaths to classes file // for buck user to have a list of all .java files to be compiled // since we do not print them out to console in case of error try { filesystem.writeLinesToPath(FluentIterable.from(javaSourceFilePaths) .transform(Functions.toStringFunction()).transform(ARGFILES_ESCAPER), pathToSrcsList.get()); } catch (IOException e) { close(fileManager, compilationUnits); context.logError(e, "Cannot write list of .java files to compile to %s file! Terminating compilation.", pathToSrcsList.get()); return 1; } } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); List<String> classNamesForAnnotationProcessing = ImmutableList.of(); Writer compilerOutputWriter = new PrintWriter(context.getStdErr()); JavaCompiler.CompilationTask compilationTask = compiler.getTask(compilerOutputWriter, fileManager, diagnostics, options, classNamesForAnnotationProcessing, compilationUnits); boolean isSuccess = false; BuckTracing.setCurrentThreadTracingInterfaceFromJsr199Javac( new BuckTracingEventBusBridge(context.getBuckEventBus(), invokingRule)); try { TranslatingJavacPhaseTracer.setupTracing(invokingRule, context.getClassLoaderCache(), context.getBuckEventBus(), compilationTask); // Ensure annotation processors are loaded from their own classloader. If we don't do this, // then the evidence suggests that they get one polluted with Buck's own classpath, which // means that libraries that have dependencies on different versions of Buck's deps may choke // with novel errors that don't occur on the command line. try (ProcessorBundle bundle = prepareProcessors(context.getBuckEventBus(), compiler.getClass().getClassLoader(), invokingRule, options)) { compilationTask.setProcessors(bundle.processors); // Invoke the compilation and inspect the result. isSuccess = compilationTask.call(); } catch (IOException e) { LOG.warn(e, "Unable to close annotation processor class loader. We may be leaking memory."); } finally { close(fileManager, compilationUnits); } } finally { // Clear the tracing interface so we have no chance of leaking it to code that shouldn't // be using it. BuckTracing.clearCurrentThreadTracingInterfaceFromJsr199Javac(); } for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { LOG.debug("javac: %s", DiagnosticPrettyPrinter.format(diagnostic)); } if (isSuccess) { return 0; } else { if (context.getVerbosity().shouldPrintStandardInformation()) { int numErrors = 0; int numWarnings = 0; for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { Diagnostic.Kind kind = diagnostic.getKind(); if (kind == Diagnostic.Kind.ERROR) { ++numErrors; handleMissingSymbolError(invokingRule, diagnostic, context, filesystem); } else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) { ++numWarnings; } context.getStdErr().println(DiagnosticPrettyPrinter.format(diagnostic)); } if (numErrors > 0 || numWarnings > 0) { context.getStdErr().printf("Errors: %d. Warnings: %d.\n", numErrors, numWarnings); } } return 1; } }
From source file:com.facebook.buck.parser.ParserNg.java
@Nullable public SortedMap<String, Object> getRawTargetNode(BuckEventBus eventBus, Cell cell, boolean enableProfiling, TargetNode<?> targetNode) throws InterruptedException, BuildFileParseException { try {/* w ww. ja v a 2 s. c o m*/ Cell owningCell = cell.getCell(targetNode.getBuildTarget()); ImmutableList<Map<String, Object>> allRawNodes = getRawTargetNodes(eventBus, owningCell, enableProfiling, cell.getAbsolutePathToBuildFile(targetNode.getBuildTarget())); String shortName = targetNode.getBuildTarget().getShortName(); for (Map<String, Object> rawNode : allRawNodes) { if (shortName.equals(rawNode.get("name"))) { SortedMap<String, Object> toReturn = new TreeMap<>(); toReturn.putAll(rawNode); toReturn.put("buck.direct_dependencies", FluentIterable.from(targetNode.getDeps()) .transform(Functions.toStringFunction()).toList()); return toReturn; } } } catch (Cell.MissingBuildFileException e) { throw new RuntimeException("Deeply unlikely to be true: the cell is missing: " + targetNode); } return null; }
From source file:ei.ne.ke.cassandra.cql3.template.DeleteStatementBuilder.java
/** * {@inheritDoc}/*w w w. ja v a 2 s.c om*/ */ @Override public String build() { Preconditions.checkNotNull(table, "You must set the name of a table"); StringBuilder sb = new StringBuilder(); sb.append("DELETE "); sb.append(StringUtils.join(selection, ", ")); sb.append(" FROM "); sb.append(table); if (!options.isEmpty()) { sb.append(" USING "); sb.append(StringUtils.join(Collections2.transform(options, Functions.toStringFunction()), " AND ")); } if (!relations.isEmpty()) { sb.append(" WHERE "); sb.append(StringUtils.join(Collections2.transform(relations, Functions.toStringFunction()), " AND ")); } sb.append(";"); return sb.toString(); }
From source file:org.killbill.billing.util.security.api.DefaultSecurityApi.java
@Override public void checkCurrentUserPermissions(final List<Permission> permissions, final Logical logical, final TenantContext context) throws SecurityApiException { final String[] permissionsString = Lists .<Permission, String>transform(permissions, Functions.toStringFunction()) .toArray(new String[permissions.size()]); try {//from w w w . j a va2 s . c o m final Subject subject = SecurityUtils.getSubject(); if (permissionsString.length == 1) { subject.checkPermission(permissionsString[0]); } else if (Logical.AND.equals(logical)) { subject.checkPermissions(permissionsString); } else if (Logical.OR.equals(logical)) { boolean hasAtLeastOnePermission = false; for (final String permission : permissionsString) { if (subject.isPermitted(permission)) { hasAtLeastOnePermission = true; break; } } // Cause the exception if none match if (!hasAtLeastOnePermission) { subject.checkPermission(permissionsString[0]); } } } catch (final AuthorizationException e) { throw new SecurityApiException(e, ErrorCode.SECURITY_NOT_ENOUGH_PERMISSIONS); } }
From source file:com.google.devtools.build.lib.rules.android.ManifestMergerActionBuilder.java
private <K, V> String mapToDictionaryString(Map<K, V> map) { return mapToDictionaryString(map, Functions.toStringFunction(), Functions.toStringFunction()); }
From source file:com.google.devtools.build.lib.rules.android.ManifestMergerActionBuilder.java
private <K, V> String mapToDictionaryString(Map<K, V> map, Function<? super K, String> keyConverter, Function<? super V, String> valueConverter) { if (keyConverter == null) { keyConverter = Functions.toStringFunction(); }/*from w w w . j av a 2s. c om*/ if (valueConverter == null) { valueConverter = Functions.toStringFunction(); } StringBuilder sb = new StringBuilder(); Iterator<Entry<K, V>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry<K, V> entry = iter.next(); sb.append(Functions.compose(ESCAPER, keyConverter).apply(entry.getKey())); sb.append(':'); sb.append(Functions.compose(ESCAPER, valueConverter).apply(entry.getValue())); if (iter.hasNext()) { sb.append(','); } } return sb.toString(); }
From source file:com.facebook.buck.java.JavacOptions.java
public RuleKey.Builder appendToRuleKey(RuleKey.Builder builder) { // TODO(simons): Include bootclasspath params. builder.set("sourceLevel", javacEnv.getSourceLevel()).set("targetLevel", javacEnv.getTargetLevel()) .set("debug", debug) .set("javacVersion", javacEnv.getJavacVersion().transform(Functions.toStringFunction()).orNull()); return annotationProcessingData.appendToRuleKey(builder); }
From source file:com.facebook.buck.cli.AuditClasspathCommand.java
@VisibleForTesting int printJsonClasspath(PartialGraph partialGraph) throws IOException { DependencyGraph graph = partialGraph.getDependencyGraph(); List<BuildTarget> targets = partialGraph.getTargets(); Multimap<String, String> targetClasspaths = LinkedHashMultimap.create(); for (BuildTarget target : targets) { BuildRule rule = graph.findBuildRuleByTarget(target); HasClasspathEntries hasClasspathEntries = getHasClasspathEntriesFrom(rule); if (hasClasspathEntries == null) { continue; }//from ww w . ja va2 s . co m targetClasspaths.putAll(target.getFullyQualifiedName(), Iterables.transform( hasClasspathEntries.getTransitiveClasspathEntries().values(), Functions.toStringFunction())); } ObjectMapper mapper = new ObjectMapper(); // Note: using `asMap` here ensures that the keys are sorted mapper.writeValue(console.getStdOut(), targetClasspaths.asMap()); return 0; }