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:org.jasig.cas.authentication.LdapAuthenticationHandler.java

/**
 * Sets the mapping of additional principal attributes where the key and value is the LDAP attribute
 * name. Note that the principal ID attribute
 * should not be listed among these attributes.
 *
 * @param attributeList List of LDAP attribute names
 *//*from  w  ww .  ja  v a 2  s. c  o  m*/
public void setPrincipalAttributeList(final List<String> attributeList) {
    this.principalAttributeMap = Maps.uniqueIndex(attributeList, Functions.toStringFunction());
}

From source file:file.PredictionFileReader.java

public boolean readTensorFile(String filename, int k, int trainSize, BookmarkReader bookmarkReader,
        Integer minBookmarks, Integer maxBookmarks, Integer minResBookmarks, Integer maxResBookmarks,
        CatDescFiltering categorizer) {// w w  w .  ja v a  2 s. c om
    this.filename = filename;
    List<Bookmark> testLines = bookmarkReader.getBookmarks().subList(trainSize,
            bookmarkReader.getBookmarks().size());

    FileReader reader;
    try {
        reader = new FileReader(new File("./data/results/" + filename + ".txt"));
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        String userID = null, resID = null;
        Map<Integer, Double> tensorTags = new LinkedHashMap<Integer, Double>();
        int count = 0;
        while ((line = br.readLine()) != null) {
            String[] lineParts = line.split(" ");
            if (userID != null && resID != null
                    && (!userID.equals(lineParts[0]) || !resID.equals(lineParts[1]))) {
                // new testline
                List<Integer> realData = testLines.get(count++).getTags();
                List<Integer> predictionData = new ArrayList<Integer>();
                Map<Integer, Double> sortedTensorTags = new TreeMap<Integer, Double>(
                        new DoubleMapComparator(tensorTags));
                sortedTensorTags.putAll(tensorTags);
                for (Integer tag : sortedTensorTags.keySet()) {
                    predictionData.add(tag);
                }

                PredictionData data = new PredictionData(Integer.parseInt(userID), Integer.parseInt(resID),
                        Lists.transform(realData, Functions.toStringFunction()),
                        Lists.transform(predictionData, Functions.toStringFunction()), k);
                this.predictions.add(data);
                this.predictionCount++;
                tensorTags.clear();
            }
            userID = lineParts[0];
            resID = lineParts[1];
            tensorTags.put(Integer.parseInt(lineParts[2]), Double.parseDouble(lineParts[3]));
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

From source file:org.spongepowered.asm.mixin.transformer.MixinInfo.java

/**
 * Internal ctor, called by {@link MixinConfig}
 * /* w  w w  .  j av  a2  s .  co m*/
 * @param parent
 * @param mixinName
 * @param runTransformers
 * @param plugin 
 * @param suppressPlugin 
 * @throws ClassNotFoundException 
 */
MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers, IMixinConfigPlugin plugin,
        boolean suppressPlugin) throws ClassNotFoundException {
    this.parent = parent;
    this.name = mixinName;
    this.className = parent.getMixinPackage() + mixinName;
    this.plugin = plugin;

    // Read the class bytes and transform
    this.mixinBytes = this.loadMixinClass(this.className, runTransformers);

    ClassNode classNode = this.getClassNode(0);
    this.classInfo = ClassInfo.fromClassNode(classNode);
    this.priority = this.readPriority(classNode);
    this.targetClasses = this.readTargetClasses(classNode, suppressPlugin);
    this.targetClassNames = Collections
            .unmodifiableList(Lists.transform(this.targetClasses, Functions.toStringFunction()));
    this.validationClassNode = classNode;
}

From source file:io.bazel.rules.closure.webfiles.Webset.java

/**
 * Mutates graph to remove web files not reachable from set of entry points.
 *
 * <p>This method fully prunes {@link #webfiles()}. Entries might be removed from {@link #links()}
 * on a best effort basis./*from w  w  w.j  a  va 2 s.c o m*/
 *
 * @param entryPoints set of paths that should be considered tree tips
 * @throws IllegalArgumentException if {@code entryPoints} aren't defined by {@code manifests}
 * @return {@code this}
 */
public final Webset removeWebfilesNotReachableFrom(Iterable<Webpath> entryPoints) {
    Deque<Webpath> bfs = new ArrayDeque<>();
    Set<Webpath> visited = Sets.newIdentityHashSet();
    for (Webpath entryPoint : Iterables
            .transform(Iterables.transform(entryPoints, Functions.toStringFunction()), interner())) {
        checkArgument(webfiles().containsKey(entryPoint), "Not found: %s", entryPoint);
        bfs.add(entryPoint);
    }
    while (!bfs.isEmpty()) {
        Webpath path = bfs.removeLast();
        if (visited.add(path)) {
            for (Webpath dest : links().get(path)) {
                if (webfiles().containsKey(dest)) {
                    bfs.addFirst(dest);
                }
            }
        }
    }
    Iterator<Webpath> webfilesIterator = webfiles().keySet().iterator();
    while (webfilesIterator.hasNext()) {
        Webpath key = webfilesIterator.next();
        if (!visited.contains(key)) {
            webfilesIterator.remove();
            links().removeAll(key);
        }
    }
    return this;
}

From source file:com.google.devtools.build.lib.rules.android.ResourceContainerConverter.java

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

From source file:com.android.monkeyrunner.MonkeyRunner.java

@MonkeyRunnerExported(doc = "Display a choice dialog that allows the user to select a single "
        + "item from a list of items.", args = { "message", "choices", "title" }, argDocs = {
                "The prompt message to display in the dialog.",
                "An iterable Python type containing a list of choices to display",
                "The dialog's title. The default is 'Input'" }, returns = "The 0-based numeric offset of the selected item in the iterable.")
public static int choice(PyObject[] args, String kws[]) {
    ArgParser ap = JythonUtils.createArgParser(args, kws);
    Preconditions.checkNotNull(ap);/*from   w  w w . j  a va2s.co  m*/

    String message = ap.getString(0);
    Collection<String> choices = Collections2.transform(JythonUtils.getList(ap, 1),
            Functions.toStringFunction());
    String title = ap.getString(2, "Input");

    return choice(message, title, choices);
}

From source file:com.facebook.buck.java.ExternalJavac.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)
        throws InterruptedException {
    ImmutableList.Builder<String> command = ImmutableList.builder();
    command.add(pathToJavac.toString());
    command.addAll(options);/*from www  .ja v  a 2  s.  c o  m*/

    ImmutableList<Path> expandedSources;
    try {
        expandedSources = getExpandedSourcePaths(filesystem, invokingRule, javaSourceFilePaths,
                workingDirectory);
    } catch (IOException e) {
        throw new HumanReadableException("Unable to expand sources for %s into %s", invokingRule,
                workingDirectory);
    }
    if (pathToSrcsList.isPresent()) {
        try {
            filesystem.writeLinesToPath(FluentIterable.from(expandedSources)
                    .transform(Functions.toStringFunction()).transform(ARGFILES_ESCAPER), 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());

    // Set environment to client environment and add additional information.
    Map<String, String> env = processBuilder.environment();
    env.clear();
    env.putAll(context.getEnvironment());
    env.put("BUCK_INVOKING_RULE", invokingRule.toString());
    env.put("BUCK_TARGET", invokingRule.toString());
    env.put("BUCK_DIRECTORY_ROOT", filesystem.getRootPath().toAbsolutePath().toString());

    processBuilder.directory(filesystem.getRootPath().toAbsolutePath().toFile());
    // 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;
    }

    return exitCode;
}

From source file:com.nesscomputing.httpclient.testing.JaxRsResponseHttpResponseGenerator.java

@Override
public HttpClientResponse respondTo(final HttpClientRequest<Object> request) {
    return new HttpClientResponse() {
        @Override/* w  w  w  .  ja v  a2 s . c  om*/
        public int getStatusCode() {
            return response.getStatus();
        }

        @Override
        public String getStatusText() {
            return Status.fromStatusCode(getStatusCode()).getReasonPhrase();
        }

        @Override
        public InputStream getResponseBodyAsStream() throws IOException {
            return responseBody;
        }

        @Override
        public URI getUri() {
            return request.getUri();
        }

        @Override
        public String getContentType() {
            return ObjectUtils.toString(contentType, null);
        }

        @Override
        public Long getContentLength() {
            return contentLength;
        }

        @Override
        public String getCharset() {
            return charset;
        }

        @Override
        public String getHeader(String name) {
            List<Object> headers = response.getMetadata().get(name);
            if (headers == null || headers.isEmpty()) {
                return null;
            }
            return headers.get(0).toString();
        }

        @Override
        public List<String> getHeaders(String name) {
            List<Object> headers = response.getMetadata().get(name);
            if (headers == null) {
                return null;
            }
            return ImmutableList.copyOf(Collections2.transform(headers, Functions.toStringFunction()));
        }

        @Override
        public Map<String, List<String>> getAllHeaders() {
            ImmutableMap.Builder<String, List<String>> result = ImmutableMap.builder();
            for (Entry<String, List<Object>> e : response.getMetadata().entrySet()) {
                result.put(e.getKey(), ImmutableList
                        .copyOf(Collections2.transform(e.getValue(), Functions.toStringFunction())));
            }
            return result.build();
        }

        @Override
        public boolean isRedirected() {
            return false;
        }
    };
}

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

/**
 *
 *
 * @return this builder.//from   w  w  w .  ja  v  a 2  s  .  c o  m
 */
@Override
public String build() {
    Preconditions.checkNotNull(selection);
    Preconditions.checkArgument(selection.size() > 0, "You must select at least one column");
    Preconditions.checkNotNull(table, "You must set the name of a table");
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ");
    sb.append(StringUtils.join(selection, ", "));
    sb.append(" FROM ");
    sb.append(table);
    if (relations.size() > 0) {
        sb.append(" WHERE ");
        sb.append(StringUtils.join(Collections2.transform(relations, Functions.toStringFunction()), " AND "));
    }
    if (orderings.size() > 0) {
        sb.append(" ORDER BY ");
        sb.append(StringUtils.join(Collections2.transform(orderings, Functions.toStringFunction()), ", "));
    }
    if (limit > VALUE_NOT_SET) {
        sb.append(" LIMIT ");
        sb.append(limit);
    }
    if (allowFiltering) {
        sb.append(" ALLOW FILTERING");
    }
    sb.append(";");
    return sb.toString();
}

From source file:org.geogit.storage.mongo.MongoObjectDatabase.java

private long deleteChunk(List<ObjectId> ids) {
    List<String> idStrings = Lists.transform(ids, Functions.toStringFunction());
    DBObject query = BasicDBObjectBuilder.start().push("oid").add("$in", idStrings).pop().get();
    WriteResult result = collection.remove(query);
    return result.getN();
}