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.google.devtools.build.lib.rules.android.AarGeneratorBuilder.java

private static String convertRoots(ResourceContainer container, ResourceType resourceType) {
    return Joiner.on("#").join(
            Iterators.transform(container.getRoots(resourceType).iterator(), Functions.toStringFunction()));
}

From source file:com.davidbracewell.data.DataFrame.java

public static DataFrame read(StructuredReader reader, boolean hasHeaders) throws IOException {
    Preconditions.checkNotNull(reader);//from w  ww.  j  a  va 2 s  . c om
    DataFrame dataFrame;
    reader.beginDocument();
    if (hasHeaders) {
        dataFrame = new DataFrame(Collections2.transform(reader.nextArray(), Functions.toStringFunction()));
    } else {
        dataFrame = new DataFrame();
    }
    int row = 0;
    while (reader.peek() != ElementType.END_DOCUMENT) {
        if (reader.peek() == ElementType.BEGIN_OBJECT) {
            dataFrame.addRow(Lists.<String>newArrayList());
            reader.beginObject();
            for (Map.Entry<String, Val> entry : reader.readObjectToMap().entrySet()) {
                dataFrame.set(row, entry.getKey(), entry.getValue().asString());
            }
            reader.endObject();
            row++;
        } else if (reader.peek() == ElementType.BEGIN_ARRAY) {
            dataFrame.addRow(Lists.<String>newArrayList());
            reader.beginArray();
            int col = 0;
            while (reader.peek() != ElementType.END_ARRAY) {
                dataFrame.set(row, col, reader.nextValue().asString());
                col++;
            }
            reader.endArray();
            row++;
        } else {
            throw new IOException("Could not parse input file [" + reader.peek() + "]");
        }
    }
    reader.endDocument();
    return dataFrame;
}

From source file:ei.ne.ke.cassandra.cql3.template.InsertStatementBuilder.java

/**
 * {@inheritDoc}//from  w  w  w  .j  a v  a 2  s .  c  o  m
 */
@Override
public String build() {
    Preconditions.checkNotNull(table, "You must set the name of a table");
    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO ");
    sb.append(table);
    if (!selection.isEmpty()) {
        sb.append(" (");
        sb.append(StringUtils.join(Collections2.transform(selection, Functions.toStringFunction()), ", "));
        sb.append(") VALUES (");
        while (values.size() < selection.size()) {
            values.add(Term.VARIABLE);
        }
        sb.append(StringUtils.join(Collections2.transform(values, Functions.toStringFunction()), ", "));
        sb.append(")");
    }
    if (!options.isEmpty()) {
        sb.append(" USING ");
        sb.append(StringUtils.join(Collections2.transform(options, Functions.toStringFunction()), " AND "));
    }
    sb.append(";");
    return sb.toString();
}

From source file:org.killbill.billing.jaxrs.resources.SecurityResource.java

@TimedResource
@GET//from  w  ww .j  ava2  s  .c  o  m
@Path("/permissions")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "List user permissions", response = String.class, responseContainer = "List")
@ApiResponses(value = {})
public Response getCurrentUserPermissions(@javax.ws.rs.core.Context final HttpServletRequest request) {
    // The getCurrentUserPermissions takes a TenantContext which is not used because permissions are cross tenants (at this point)
    final TenantContext nullTenantContext = null;
    final Set<Permission> permissions = securityApi.getCurrentUserPermissions(nullTenantContext);
    final List<String> json = ImmutableList
            .<String>copyOf(Iterables.<Permission, String>transform(permissions, Functions.toStringFunction()));
    return Response.status(Status.OK).entity(json).build();
}

From source file:com.google.gerrit.metrics.Field.java

@SuppressWarnings("unchecked")
private static <T> Function<T, String> initFormatter(Class<T> keyType) {
    if (keyType == String.class) {
        return (Function<T, String>) Functions.<String>identity();
    } else if (keyType == Integer.class || keyType == Boolean.class) {
        return (Function<T, String>) Functions.toStringFunction();
    } else if (Enum.class.isAssignableFrom(keyType)) {
        return in -> ((Enum<?>) in).name();
    }/*w  w w . j  ava 2s .com*/
    throw new IllegalStateException("unsupported type " + keyType.getName());
}

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

@Override
protected int buildWithClasspath(ExecutionContext context, Set<Path> buildClasspathEntries) {
    ImmutableList.Builder<String> command = ImmutableList.builder();
    command.add(pathToJavac.toString());
    command.addAll(getOptions(context, buildClasspathEntries));

    ImmutableList<Path> expandedSources;
    try {//from w  ww.  jav  a2 s .c  o m
        expandedSources = getExpandedSourcePaths(context);
    } catch (IOException e) {
        throw new HumanReadableException("Unable to expand sources for %s into %s", target, workingDirectory);
    }
    if (pathToSrcsList.isPresent()) {
        try {
            context.getProjectFilesystem().writeLinesToPath(
                    Iterables.transform(expandedSources, Functions.toStringFunction()), pathToSrcsList.get());
            command.add("@" + 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;
        }
    } else {
        for (Path source : expandedSources) {
            command.add(source.toString());
        }
    }

    ProcessBuilder processBuilder = new ProcessBuilder(command.build());

    // Add additional information to the environment
    Map<String, String> env = processBuilder.environment();
    env.put("BUCK_INVOKING_RULE", invokingRule.or(""));
    env.put("BUCK_TARGET", target.toString());
    env.put("BUCK_DIRECTORY_ROOT", context.getProjectDirectoryRoot().toString());
    env.put("BUCK_OUTPUT_ABI_FILE", pathToOutputAbiFile.or(new File("").toPath()).toString());

    processBuilder.directory(context.getProjectDirectoryRoot());
    // Run the command
    int exitCode = -1;
    try {
        ProcessExecutor.Result result = context.getProcessExecutor().execute(processBuilder.start());
        exitCode = result.getExitCode();
    } catch (IOException e) {
        e.printStackTrace(context.getStdErr());
        return exitCode;
    }

    if (exitCode != 0) {
        return exitCode;
    }

    // Read ABI key
    if (abiKeyFile != null) {
        try {
            String firstLine = Files.readFirstLine(abiKeyFile, Charsets.UTF_8);
            if (firstLine != null) {
                // TODO(user) make sure command is considered in hash
                abiKey = new Sha1HashCode(firstLine);
            }
        } catch (IOException e) {
            e.printStackTrace(context.getStdErr());
            return 1;
        }
    }
    return 0;
}

From source file:com.facebook.buck.distributed.DistributedBuildTargetGraphCodec.java

public static BuildJobStateBuildTarget encodeBuildTarget(BuildTarget buildTarget) {
    BuildJobStateBuildTarget remoteTarget = new BuildJobStateBuildTarget();
    remoteTarget.setShortName(buildTarget.getShortName());
    remoteTarget.setBaseName(buildTarget.getBaseName());
    if (buildTarget.getCell().isPresent()) {
        remoteTarget.setCellName(buildTarget.getCell().get());
    }/*  w ww. java2s. c o  m*/
    remoteTarget.setFlavors(
            FluentIterable.from(buildTarget.getFlavors()).transform(Functions.toStringFunction()).toSet());
    return remoteTarget;
}

From source file:com.googlecode.blaisemath.graph.test.GraphTestFrame.java

/** Creates new form TestPlaneVisometry */
public GraphTestFrame() {
    EditorRegistration.registerEditors();
    initComponents();/*from   w  w w .j  a  v  a2  s . com*/

    // BASIC ELEMENTS

    final Graph<Integer> graph = new EdgeLikelihoodGenerator()
            .apply(new EdgeLikelihoodParameters(false, 50, .05f));
    plot.setGraph(graph);
    plot.getAdapter().getViewGraph().setPointSelectionEnabled(true);
    plot.getAdapter().getViewGraph().setDragEnabled(true);
    plot.getLayoutManager().applyLayout(CircleLayout.getInstance(), null, new CircleLayoutParameters(100.0));
    PanAndZoomHandler.zoomBoxAnimated(plot,
            Points.boundingBox(plot.getLayoutManager().getNodeLocationCopy().values(), 5));
    plot.getAdapter().getNodeStyler().setStyleDelegate(new Function<Object, AttributeSet>() {
        public AttributeSet apply(Object o) {
            Integer i = (Integer) o;
            return Styles.DEFAULT_POINT_STYLE.copy().and(Styles.FILL, Color.lightGray)
                    .and(Styles.STROKE, Color.gray).and(Styles.STROKE_WIDTH, .5f)
                    .and(Styles.MARKER_RADIUS, 2 + Math.sqrt(i));
        }
    });

    plot.getAdapter().getNodeStyler().setLabelDelegate(Functions.toStringFunction());

    plot.addContextMenuInitializer("Graph", new ContextMenuInitializer<Graphic>() {
        public void initContextMenu(JPopupMenu menu, Graphic src, Point2D point, Object focus, Set selection) {
            if (menu.getComponentCount() > 0) {
                menu.addSeparator();
            }
            if (focus != null) {
                menu.add("Graph Focus: " + focus);
            }
            menu.add("Selection: " + (selection == null ? 0 : selection.size()) + " selected items");
        }
    });
    plot.addContextMenuInitializer("Node", new ContextMenuInitializer<Graphic>() {
        public void initContextMenu(JPopupMenu menu, Graphic src, Point2D point, Object focus, Set selection) {
            if (menu.getComponentCount() > 0) {
                menu.addSeparator();
            }
            if (focus != null) {
                menu.add("Node: " + focus);
            }
        }
    });
    plot.addContextMenuInitializer("Link", new ContextMenuInitializer<Graphic>() {
        public void initContextMenu(JPopupMenu menu, Graphic src, Point2D point, Object focus, Set selection) {
            if (menu.getComponentCount() > 0) {
                menu.addSeparator();
            }
            if (focus != null) {
                menu.add("Link: " + focus);
            }
        }
    });

    // PANELS

    energyLayout = new SpringLayout();
    layoutParams = energyLayout.createParameters();
    rollupPanel1.add("Energy Layout", PropertySheet.forBean(layoutParams));
    for (Graphic p : plot.getGraphicRoot().getGraphics()) {
        rollupPanel1.add(p.toString(), PropertySheet.forBean(p));
    }

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            GAInstrument.print(System.out, 50);
        }
    });

    // OVERLAY

    plot.getOverlays().add(new CanvasPainter<Graphics2D>() {
        public void paint(Component component, Graphics2D canvas) {
            canvas.setColor(Color.black);
            canvas.drawLine(50, 50, 150, 50);
            canvas.drawLine(50, 40, 50, 60);
            canvas.drawLine(150, 40, 150, 60);
        }
    });

    plot.getSelectionModel().addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            selectionL.setText(String.format("<html><b>Selection:</b> %s", evt.getNewValue()));
        }
    });
}

From source file:com.android.tools.idea.wizard.ASGallery.java

public ASGallery() {
    this(new DefaultListModel(), Functions.<Image>constant(null), Functions.toStringFunction(),
            new Dimension(0, 0));
}

From source file:co.cask.cdap.app.runtime.spark.distributed.SparkExecutionClient.java

/**
 * Writes the workflow tokens modified by this program to the given URL connection.
 *///ww  w.  j a  v  a2s . com
private void writeWorkflowToken(@Nullable BasicWorkflowToken workflowToken, HttpURLConnection urlConn)
        throws IOException {
    try (Writer writer = new OutputStreamWriter(urlConn.getOutputStream(), Charsets.UTF_8)) {
        if (workflowToken != null) {
            GSON.toJson(
                    Maps.transformValues(workflowToken.getAllFromCurrentNode(), Functions.toStringFunction()),
                    TOKEN_TYPE, writer);
        }
    }
}