Example usage for com.google.common.base Functions toStringFunction

List of usage examples for com.google.common.base Functions toStringFunction

Introduction

In this page you can find the example usage for com.google.common.base Functions toStringFunction.

Prototype

public static Function<Object, String> toStringFunction() 

Source Link

Document

Returns a function that calls toString() on its argument.

Usage

From source file:com.googlecode.blaisemath.graphics.core.DelegatingPointSetGraphic.java

/**
 * Construct with source objects and locations as a map
 * @param crdManager manages point locations
 * @param renderer used for drawing the points
 * @param labelRenderer draws labels//from www .  ja v  a  2 s. c  om
 */
public DelegatingPointSetGraphic(CoordinateManager<S, Point2D> crdManager,
        @Nullable Renderer<Point2D, G> renderer, @Nullable Renderer<AnchoredText, G> labelRenderer) {
    setRenderer(renderer);
    setLabelRenderer(labelRenderer);

    styler.setStyleConstant(Styles.DEFAULT_POINT_STYLE);
    styler.setTipDelegate(Functions.toStringFunction());

    coordListener = new CoordinateListener() {
        @Override
        @InvokedFromThread("unknown")
        public void coordinatesChanged(final CoordinateChangeEvent evt) {
            BSwingUtilities.invokeOnEventDispatchThread(new Runnable() {
                @Override
                public void run() {
                    updatePointGraphics(evt.getAdded(), evt.getRemoved());
                }
            });
        }
    };

    setCoordinateManager(crdManager);
}

From source file:com.facebook.buck.java.AccumulateClassNamesStep.java

@Override
public String getDescription(ExecutionContext context) {
    String sourceString = pathToJarOrClassesDirectory.transform(Functions.toStringFunction()).or("null");
    return String.format("get_class_names %s > %s", sourceString, whereClassNamesShouldBeWritten);
}

From source file:adwords.axis.v201506.advancedoperations.FindAndRemoveCriteriaFromSharedSet.java

public static void runExample(AdWordsServices adWordsServices, AdWordsSession session, Long campaignId)
        throws Exception {
    // Get the CampaignSharedSetService.
    CampaignSharedSetServiceInterface campaignSharedSetService = adWordsServices.get(session,
            CampaignSharedSetServiceInterface.class);

    // First, retrieve all shared sets associated with the campaign.
    int offset = 0;
    SelectorBuilder selectorBuilder = new SelectorBuilder()
            .fields(CampaignSharedSetField.SharedSetId, CampaignSharedSetField.CampaignId,
                    CampaignSharedSetField.SharedSetName, CampaignSharedSetField.SharedSetType)
            .equals(CampaignSharedSetField.CampaignId, campaignId.toString())
            .in(CampaignSharedSetField.SharedSetType, SharedSetType.NEGATIVE_KEYWORDS.getValue(),
                    SharedSetType.NEGATIVE_PLACEMENTS.getValue())
            .limit(PAGE_SIZE);/*from   www . ja va 2 s  . co  m*/

    List<Long> sharedSetIds = Lists.newArrayList();
    CampaignSharedSetPage campaignSharedSetPage;
    do {
        selectorBuilder.offset(offset);
        campaignSharedSetPage = campaignSharedSetService.get(selectorBuilder.build());
        for (CampaignSharedSet campaignSharedSet : campaignSharedSetPage.getEntries()) {
            sharedSetIds.add(campaignSharedSet.getSharedSetId());
            System.out.printf("Campaign shared set ID %d and name '%s' found for campaign ID %d.%n",
                    campaignSharedSet.getSharedSetId(), campaignSharedSet.getSharedSetName(),
                    campaignSharedSet.getCampaignId());
        }
        offset += PAGE_SIZE;
    } while (offset < campaignSharedSetPage.getTotalNumEntries());

    if (sharedSetIds.isEmpty()) {
        System.out.printf("No shared sets found for campaign ID %d.%n", campaignId);
        return;
    }

    // Next, retrieve criterion IDs for all found shared sets.
    SharedCriterionServiceInterface sharedCriterionService = adWordsServices.get(session,
            SharedCriterionServiceInterface.class);

    // Transform shared set IDs to strings.
    String[] sharedSetIdStrings = Collections2.transform(sharedSetIds, Functions.toStringFunction())
            .toArray(new String[sharedSetIds.size()]);

    offset = 0;
    selectorBuilder = new SelectorBuilder()
            .fields("SharedSetId", "Id", "KeywordText", "KeywordMatchType", "PlacementUrl")
            .in("SharedSetId", sharedSetIdStrings).limit(PAGE_SIZE);

    List<SharedCriterionOperation> removeCriterionOperations = Lists.newArrayList();
    SharedCriterionPage sharedCriterionPage;
    do {
        selectorBuilder.offset(offset);
        sharedCriterionPage = sharedCriterionService.get(selectorBuilder.build());
        for (SharedCriterion sharedCriterion : sharedCriterionPage.getEntries()) {
            if (CriterionType.KEYWORD.equals(sharedCriterion.getCriterion().getType())) {
                Keyword keyword = (Keyword) sharedCriterion.getCriterion();
                System.out.printf("Shared negative keyword with ID %d and text '%s' was found.%n",
                        keyword.getId(), keyword.getText());
            } else if (CriterionType.PLACEMENT.equals(sharedCriterion.getCriterion().getType())) {
                Placement placement = (Placement) sharedCriterion.getCriterion();
                System.out.printf("Shared negative placement with ID %d and URL '%s' was found.%n",
                        placement.getId(), placement.getUrl());
            } else {
                System.out.printf("Shared criterion with ID %d was found.%n",
                        sharedCriterion.getCriterion().getId());
            }

            // Create an operation to remove this criterion.
            SharedCriterionOperation removeCriterionOperation = new SharedCriterionOperation();
            removeCriterionOperation.setOperator(Operator.REMOVE);

            SharedCriterion sharedCriterionToRemove = new SharedCriterion();

            Criterion criterionToRemove = new Criterion();
            criterionToRemove.setId(sharedCriterion.getCriterion().getId());

            sharedCriterionToRemove.setCriterion(criterionToRemove);
            sharedCriterionToRemove.setSharedSetId(sharedCriterion.getSharedSetId());

            removeCriterionOperation.setOperand(sharedCriterionToRemove);

            removeCriterionOperations.add(removeCriterionOperation);
        }
        offset += PAGE_SIZE;
    } while (offset < sharedCriterionPage.getTotalNumEntries());

    // Finally, remove the criteria.
    if (removeCriterionOperations.isEmpty()) {
        System.out.printf("No shared criteria to remove.%n");
    } else {
        SharedCriterionReturnValue sharedCriterionReturnValue = sharedCriterionService
                .mutate(removeCriterionOperations
                        .toArray(new SharedCriterionOperation[removeCriterionOperations.size()]));
        for (SharedCriterion removedCriterion : sharedCriterionReturnValue.getValue()) {
            System.out.printf("Shared criterion ID %d was successfully removed from shared set ID %d.%n",
                    removedCriterion.getCriterion().getId(), removedCriterion.getSharedSetId());
        }
    }
}

From source file:org.apache.twill.internal.state.SystemMessages.java

/**
 * Helper method to get System {@link Message} for resetting log levels for one or all runnables.
 *
 * @param runnableName The name of the runnable to set the log level, null if apply to all runnables.
 * @return An instance of System {@link Message} to reset the log levels.
 *//*from   ww w. j av a2  s .  c  o m*/
public static Message resetLogLevels(@Nullable String runnableName, Set<String> loggerNames) {
    return new SimpleMessage(Message.Type.SYSTEM,
            runnableName == null ? Message.Scope.ALL_RUNNABLE : Message.Scope.RUNNABLE, runnableName,
            Command.Builder.of(RESET_LOG_LEVEL)
                    .addOptions(Maps.uniqueIndex(loggerNames, Functions.toStringFunction())).build());
}

From source file:com.googlecode.blaisemath.graph.view.VisualGraph.java

/**
 * Initializes view graph for the graph in the graph manager. This includes
 * setting up any styling appropriate for the graph, as well as updating
 * the nodes and edges in the view graph.
 *//*from w w  w  .ja  va 2 s  . c  om*/
protected final void initViewGraph() {
    if (viewGraph == null) {
        if (viewGraphSupplier != null) {
            viewGraph = viewGraphSupplier.get();
        } else {
            viewGraph = new DelegatingNodeLinkGraphic<Object, Edge<Object>, G>(
                    layoutManager.getCoordinateManager(), null, null, null);
            viewGraph.getNodeStyler().setStyleConstant(DEFAULT_NODE_STYLE);
        }

        // set up default styles, in case the graph isn't visible by default
        if (viewGraph.getNodeStyler().getStyleDelegate() == null) {
            viewGraph.getNodeStyler().setStyleConstant(DEFAULT_NODE_STYLE);
        }
        if (viewGraph.getNodeStyler().getLabelDelegate() == null) {
            viewGraph.getNodeStyler().setLabelDelegate(Functions.toStringFunction());
        }
        if (viewGraph.getNodeStyler().getTipDelegate() == null) {
            viewGraph.getNodeStyler().setTipDelegate(Functions.toStringFunction());
        }
        if (viewGraph.getEdgeStyler().getStyleDelegate() == null) {
            viewGraph.getEdgeStyler().setStyleConstant(DEFAULT_EDGE_STYLE);
        }
    } else {
        viewGraph.setCoordinateManager(layoutManager.getCoordinateManager());
    }
    viewGraph.setEdgeSet(layoutManager.getGraph().edges());
}

From source file:de.learnlib.algorithms.features.observationtable.OTUtils.java

public static <I, D> void displayHTMLInBrowser(ObservationTable<I, D> table)
        throws IOException, HeadlessException, UnsupportedOperationException {
    displayHTMLInBrowser(table, Functions.toStringFunction(), Functions.toStringFunction());
}

From source file:org.terasology.mm.RepositoryConnector.java

public Collection<String> findAvailableVersions(String moduleId) {

    Artifact artifact = new DefaultArtifact(groupId, moduleId, "jar", "[0,)");

    VersionRangeRequest rangeRequest = new VersionRangeRequest();
    rangeRequest.setArtifact(artifact);//  w ww.  j  a  v  a2s. c o  m
    rangeRequest.setRepositories(repos);

    VersionRangeResult rangeResult;
    try {
        rangeResult = system.resolveVersionRange(session, rangeRequest);
    } catch (VersionRangeResolutionException e) {
        logger.error("The requested range could not be parsed", e);
        return Collections.emptyList();
    }

    // transform List<Version> to a List<String> using toString()
    return FluentIterable.from(rangeResult.getVersions()).transform(Functions.toStringFunction()).toList();
}

From source file:com.facebook.buck.java.AbstractJavacOptions.java

public void appendOptionsToList(ImmutableList.Builder<String> optionsBuilder,
        final Function<Path, Path> pathRelativizer) {

    // Add some standard options.
    optionsBuilder.add("-source", getSourceLevel());
    optionsBuilder.add("-target", getTargetLevel());

    // Set the sourcepath to stop us reading source files out of jars by mistake.
    optionsBuilder.add("-sourcepath", "");

    if (isDebug()) {
        optionsBuilder.add("-g");
    }/*from ww  w .j  av a  2s . c  o  m*/

    if (isVerbose()) {
        optionsBuilder.add("-verbose");
    }

    // Override the bootclasspath if Buck is building Java code for Android.
    if (getBootclasspath().isPresent()) {
        optionsBuilder.add("-bootclasspath", getBootclasspath().get());
    } else {
        String bcp = getSourceToBootclasspath().get(getSourceLevel());
        if (bcp != null) {
            optionsBuilder.add("-bootclasspath", bcp);
        }
    }

    // Add annotation processors.
    if (!getAnnotationProcessingParams().isEmpty()) {

        // Specify where to generate sources so IntelliJ can pick them up.
        Path generateTo = getAnnotationProcessingParams().getGeneratedSourceFolderName();
        if (generateTo != null) {
            optionsBuilder.add("-s").add(pathRelativizer.apply(generateTo).toString());
        }

        // Specify processorpath to search for processors.
        optionsBuilder.add("-processorpath",
                Joiner.on(File.pathSeparator)
                        .join(FluentIterable.from(getAnnotationProcessingParams().getSearchPathElements())
                                .transform(pathRelativizer).transform(Functions.toStringFunction())));

        // Specify names of processors.
        if (!getAnnotationProcessingParams().getNames().isEmpty()) {
            optionsBuilder.add("-processor", Joiner.on(',').join(getAnnotationProcessingParams().getNames()));
        }

        // Add processor parameters.
        for (String parameter : getAnnotationProcessingParams().getParameters()) {
            optionsBuilder.add("-A" + parameter);
        }

        if (getAnnotationProcessingParams().getProcessOnly()) {
            optionsBuilder.add("-proc:only");
        }
    }

    // Add extra arguments.
    optionsBuilder.addAll(getExtraArguments());
}

From source file:com.facebook.buck.java.JavacInMemoryStep.java

@Override
protected int buildWithClasspath(ExecutionContext context, Set<Path> buildClasspathEntries) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Preconditions.checkNotNull(compiler,
            "If using JRE instead of JDK, ToolProvider.getSystemJavaCompiler() may be null.");
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits;
    try {// w  w  w.  j av a 2 s. co m
        compilationUnits = createCompilationUnits(fileManager,
                context.getProjectFilesystem().getAbsolutifier());
    } catch (IOException e) {
        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 {
            context.getProjectFilesystem().writeLinesToPath(
                    Iterables.transform(javaSourceFilePaths, Functions.toStringFunction()),
                    pathToSrcsList.get());
        } catch (IOException e) {
            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<JavaFileObject>();
    List<String> options = getOptions(context, buildClasspathEntries);
    List<String> classNamesForAnnotationProcessing = ImmutableList.of();
    Writer compilerOutputWriter = new PrintWriter(context.getStdErr());
    JavaCompiler.CompilationTask compilationTask = compiler.getTask(compilerOutputWriter, fileManager,
            diagnostics, options, classNamesForAnnotationProcessing, compilationUnits);

    // Invoke the compilation and inspect the result.
    boolean isSuccess = compilationTask.call();
    if (isSuccess) {
        if (abiKeyFile != null) {
            try {
                String firstLine = Files.readFirstLine(abiKeyFile, Charsets.UTF_8);
                if (firstLine != null) {
                    abiKey = new Sha1HashCode(firstLine);
                }
            } catch (IOException e) {
                e.printStackTrace(context.getStdErr());
                return 1;
            }
        }
        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;
                } else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) {
                    ++numWarnings;
                }

                context.getStdErr().println(diagnostic);
            }

            if (numErrors > 0 || numWarnings > 0) {
                context.getStdErr().printf("Errors: %d. Warnings: %d.\n", numErrors, numWarnings);
            }
        }
        return 1;
    }
}

From source file:com.facebook.buck.java.JavacOptions.java

public void appendOptionsToList(ImmutableList.Builder<String> optionsBuilder,
        final Function<Path, Path> pathRelativizer, AnnotationProcessingDataDecorator decorator) {
    Preconditions.checkNotNull(optionsBuilder);

    // Add some standard options.
    optionsBuilder.add("-target", javacEnv.getSourceLevel());
    optionsBuilder.add("-source", javacEnv.getTargetLevel());

    if (debug) {/*  w w w.ja  va 2s .co  m*/
        optionsBuilder.add("-g");
    }

    if (verbose) {
        optionsBuilder.add("-verbose");
    }

    // Override the bootclasspath if Buck is building Java code for Android.
    if (bootclasspath.isPresent()) {
        optionsBuilder.add("-bootclasspath", bootclasspath.get());
    }

    // Add annotation processors.
    AnnotationProcessingData annotationProcessingData = decorator.decorate(this.annotationProcessingData);
    if (!annotationProcessingData.isEmpty()) {

        // Specify where to generate sources so IntelliJ can pick them up.
        Path generateTo = annotationProcessingData.getGeneratedSourceFolderName();
        if (generateTo != null) {
            optionsBuilder.add("-s").add(generateTo.toString());
        }

        // Create a path relativizer that relativizes all processor paths, except for
        // AbiWritingAnnotationProcessingDataDecorator.ABI_PROCESSOR_CLASSPATH, which will already be
        // an absolute path.
        Function<Path, Path> pathRelativizerThatOmitsAbiProcessor = new Function<Path, Path>() {
            @Override
            public Path apply(Path searchPathElement) {
                if (AbiWritingAnnotationProcessingDataDecorator.ABI_PROCESSOR_CLASSPATH
                        .equals(searchPathElement)) {
                    return searchPathElement;
                } else {
                    return pathRelativizer.apply(searchPathElement);
                }
            }
        };

        // Specify processorpath to search for processors.
        optionsBuilder.add("-processorpath",
                Joiner.on(':')
                        .join(FluentIterable.from(annotationProcessingData.getSearchPathElements())
                                .transform(pathRelativizerThatOmitsAbiProcessor)
                                .transform(Functions.toStringFunction())));

        // Specify names of processors.
        if (!annotationProcessingData.getNames().isEmpty()) {
            optionsBuilder.add("-processor", Joiner.on(',').join(annotationProcessingData.getNames()));
        }

        // Add processor parameters.
        for (String parameter : annotationProcessingData.getParameters()) {
            optionsBuilder.add("-A" + parameter);
        }

        if (annotationProcessingData.getProcessOnly()) {
            optionsBuilder.add("-proc:only");
        }
    }
}