Example usage for com.google.common.base Strings repeat

List of usage examples for com.google.common.base Strings repeat

Introduction

In this page you can find the example usage for com.google.common.base Strings repeat.

Prototype

public static String repeat(String string, int count) 

Source Link

Document

Returns a string consisting of a specific number of concatenated copies of an input string.

Usage

From source file:org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.java

/**
 * @param text Content of tag description
 * @param nextLineIndent Number of spaces from left side default is 12
 * @return formatted description//  w  w  w.  j a v a  2  s .  c o  m
 */
private static String formatToParagraph(final String text, final int nextLineIndent) {
    if (Strings.isNullOrEmpty(text)) {
        return "";
    }
    boolean isFirstElementOnNewLineEmptyChar = false;
    final StringBuilder sb = new StringBuilder();
    final StringBuilder lineBuilder = new StringBuilder();
    final String lineIndent = Strings.repeat(" ", nextLineIndent);
    final String textToFormat = NEWLINE_OR_TAB.removeFrom(text);
    final String formattedText = textToFormat.replaceAll(" +", " ");
    final StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);

    while (tokenizer.hasMoreElements()) {
        final String nextElement = tokenizer.nextElement().toString();

        if (lineBuilder.length() + nextElement.length() > 80) {
            // Trim trailing whitespace
            for (int i = lineBuilder.length() - 1; i >= 0 && lineBuilder.charAt(i) != ' '; --i) {
                lineBuilder.setLength(i);
            }
            // Trim leading whitespace
            while (lineBuilder.charAt(0) == ' ') {
                lineBuilder.deleteCharAt(0);
            }
            sb.append(lineBuilder).append('\n');
            lineBuilder.setLength(0);

            if (nextLineIndent > 0) {
                sb.append(lineIndent);
            }

            if (" ".equals(nextElement)) {
                isFirstElementOnNewLineEmptyChar = true;
            }
        }
        if (isFirstElementOnNewLineEmptyChar) {
            isFirstElementOnNewLineEmptyChar = false;
        } else {
            lineBuilder.append(nextElement);
        }
    }
    return sb.append(lineBuilder).append('\n').toString();
}

From source file:org.rf.ide.core.executor.RobotCommandRpcExecutor.java

private static Object resultOrException(final Object rpcCallResult) {
    final Map<?, ?> result = (Map<?, ?>) rpcCallResult;
    Preconditions.checkArgument(result.size() == 2);
    Preconditions.checkArgument(result.containsKey("result"));
    Preconditions.checkArgument(result.containsKey("exception"));

    if (result.get("exception") != null) {
        final String exception = (String) result.get("exception");
        final String indent = Strings.repeat(" ", 12);
        final String indentedException = indent + exception.replaceAll("\n", "\n" + indent);
        throw new RobotEnvironmentException(
                "RED python session problem. Following exception has been thrown by " + "python service:\n"
                        + indentedException);
    }//from ww  w  .jav  a2s.  c o m
    return result.get("result");
}

From source file:com.squareup.wire.java.JavaGenerator.java

/** Returns the generated code for {@code type}, which may be a top-level or a nested type. */
public TypeSpec generateEnum(EnumType type) {
    ClassName javaType = (ClassName) typeName(type.type());

    TypeSpec.Builder builder = TypeSpec.enumBuilder(javaType.simpleName()).addModifiers(PUBLIC)
            .addSuperinterface(WireEnum.class);

    if (!type.documentation().isEmpty()) {
        builder.addJavadoc("$L\n", sanitizeJavadoc(type.documentation()));
    }//from   www  . jav a 2  s  .c  o  m

    // Output Private tag field
    builder.addField(TypeName.INT, "value", PRIVATE, FINAL);

    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
    constructorBuilder.addStatement("this.value = value");
    constructorBuilder.addParameter(TypeName.INT, "value");

    // Enum constant options, each of which requires a constructor parameter and a field.
    Set<ProtoMember> allOptionFieldsBuilder = new LinkedHashSet<>();
    for (EnumConstant constant : type.constants()) {
        for (ProtoMember protoMember : constant.options().map().keySet()) {
            Field optionField = schema.getField(protoMember);
            if (allOptionFieldsBuilder.add(protoMember)) {
                TypeName optionJavaType = typeName(optionField.type());
                builder.addField(optionJavaType, optionField.name(), PUBLIC, FINAL);
                constructorBuilder.addParameter(optionJavaType, optionField.name());
                constructorBuilder.addStatement("this.$L = $L", optionField.name(), optionField.name());
            }
        }
    }
    ImmutableList<ProtoMember> allOptionMembers = ImmutableList.copyOf(allOptionFieldsBuilder);
    String enumArgsFormat = "$L" + Strings.repeat(", $L", allOptionMembers.size());
    builder.addMethod(constructorBuilder.build());

    MethodSpec.Builder fromValueBuilder = MethodSpec.methodBuilder("fromValue")
            .addJavadoc("Return the constant for {@code value} or null.\n").addModifiers(PUBLIC, STATIC)
            .returns(javaType).addParameter(int.class, "value").beginControlFlow("switch (value)");

    Set<Integer> seenTags = new LinkedHashSet<>();
    for (EnumConstant constant : type.constants()) {
        Object[] enumArgs = new Object[allOptionMembers.size() + 1];
        enumArgs[0] = constant.tag();
        for (int i = 0; i < allOptionMembers.size(); i++) {
            ProtoMember protoMember = allOptionMembers.get(i);
            Field field = schema.getField(protoMember);
            Object value = constant.options().map().get(protoMember);
            enumArgs[i + 1] = value != null ? fieldInitializer(field.type(), value) : null;
        }

        TypeSpec.Builder constantBuilder = TypeSpec.anonymousClassBuilder(enumArgsFormat, enumArgs);
        if (!constant.documentation().isEmpty()) {
            constantBuilder.addJavadoc("$L\n", sanitizeJavadoc(constant.documentation()));
        }

        if ("true".equals(constant.options().get(ENUM_DEPRECATED))) {
            constantBuilder.addAnnotation(Deprecated.class);
        }

        builder.addEnumConstant(constant.name(), constantBuilder.build());

        // Ensure constant case tags are unique, which might not be the case if allow_alias is true.
        if (seenTags.add(constant.tag())) {
            fromValueBuilder.addStatement("case $L: return $L", constant.tag(), constant.name());
        }
    }

    builder.addMethod(fromValueBuilder.addStatement("default: return null").endControlFlow().build());

    builder.addField(FieldSpec.builder(adapterOf(javaType), "ADAPTER").addModifiers(PUBLIC, STATIC, FINAL)
            .initializer("$T.newEnumAdapter($T.class)", ProtoAdapter.class, javaType).build());

    // Enum type options.
    FieldSpec options = optionsField(ENUM_OPTIONS, "ENUM_OPTIONS", type.options());
    if (options != null) {
        builder.addField(options);
    }

    // Public Getter
    builder.addMethod(MethodSpec.methodBuilder("getValue").addAnnotation(Override.class).addModifiers(PUBLIC)
            .returns(TypeName.INT).addStatement("return value").build());

    return builder.build();
}

From source file:org.eclipse.elk.layered.JsonDebugUtil.java

/**
 * Writes the nodes edges as JSON formatted string to the given writer.
 * //w ww.j  a v a 2s .  c  om
 * @param writer
 *            the writer to write to.
 * @param nodes
 *            the nodes to write.
 * @param indentation
 *            the indentation level to use.
 * @param layerNumber
 *            the layer number. {@code -1} for layerless nodes.
 * @param offset
 *            the combined offset of the containing LGraph.
 * @throws IOException
 *             if anything goes wrong with the writer.
 */
private static void writeNodes(final Writer writer, final List<LNode> nodes, final int indentation,
        final int layerNumber, final KVector offset) throws IOException {

    String indent0 = Strings.repeat(INDENT, indentation);
    String indent1 = Strings.repeat(INDENT, indentation + 1);
    int nodeNumber = -1;
    Iterator<LNode> nodesIterator = nodes.iterator();
    while (nodesIterator.hasNext()) {
        nodeNumber++;
        LNode node = nodesIterator.next();
        final KVector position = new KVector(node.getPosition()).add(offset);
        writer.write("\n" + indent0 + "{\n" + indent1 + "\"id\": \"n" + node.hashCode() + "\",\n" + indent1
                + "\"labels\": [ { \"text\": \"" + getNodeName(node, layerNumber, nodeNumber) + "\" } ],\n"
                + indent1 + "\"width\": " + node.getSize().x + ",\n" + indent1 + "\"height\": "
                + node.getSize().y + ",\n" + indent1 + "\"x\": " + position.x + ",\n" + indent1 + "\"y\": "
                + position.y + ",\n");
        writeProperties(writer, node.getAllProperties(), indentation + 1);
        writer.write(",\n");
        writePorts(writer, node.getPorts(), indentation + 1);
        final LGraph nestedGraph = node.getProperty(InternalProperties.NESTED_LGRAPH);
        if (nestedGraph != null) {
            writeLgraph(nestedGraph, writer, indentation + 1);
        }
        writer.write("\n" + indent0 + "}");
        if (nodesIterator.hasNext()) {
            writer.write(",");
        }
    }
}

From source file:de.cau.cs.kieler.klay.layered.JsonDebugUtil.java

/**
 * Writes the given edges as JSON formatted string to the given
 * ConsoleWriter.//from   w ww. j  av  a  2s  .c  o  m
 *
 * @param ConsoleWriter
 *            the ConsoleWriter to write to.
 * @param edges
 *            the edges to write.
 * @param indentation
 *            the indentation level to use.
 * @throws IOException
 *             if anything goes wrong with the ConsoleWriter.
 */
private static void writeEdges(final ConsoleWriter ConsoleWriter, final List<LEdge> edges,
        final int indentation) throws IOException {

    final String indent0 = Strings.repeat(INDENT, indentation);
    final String indent1 = Strings.repeat(INDENT, indentation + 1);
    final String indent2 = Strings.repeat(INDENT, indentation + 2);
    ConsoleWriter.write(indent0 + "\"edges\": [");
    final Iterator<LEdge> edgesIterator = edges.iterator();
    while (edgesIterator.hasNext()) {
        final LEdge edge = edgesIterator.next();
        ConsoleWriter.write("\n" + indent1 + "{\n" + indent2 + "\"id\": \"e" + edge.hashCode() + "\",\n"
                + indent2 + "\"source\": \"n" + edge.getSource().getNode().hashCode() + "\",\n" + indent2
                + "\"target\": \"n" + edge.getTarget().getNode().hashCode() + "\",\n" + indent2
                + "\"sourcePort\": \"p" + edge.getSource().hashCode() + "\",\n" + indent2
                + "\"targetPort\": \"p" + edge.getTarget().hashCode() + "\",\n" + indent2
                + "\"sourcePoint\": { \"x\": " + edge.getSource().getAbsoluteAnchor().x + ", \"y\": "
                + edge.getSource().getAbsoluteAnchor().y + " },\n" + indent2 + "\"targetPoint\": { \"x\": "
                + edge.getTarget().getAbsoluteAnchor().x + ", \"y\": " + edge.getTarget().getAbsoluteAnchor().y
                + " },\n");
        // + indent2 + "\"bendPoints\": \"" +
        // edge.getBendPoints().toString() + "\",\n");
        writeBendPoints(ConsoleWriter, edge.getBendPoints(), indentation + 2);
        ConsoleWriter.write(",\n");
        writeProperties(ConsoleWriter, edge.getAllProperties(), indentation + 2);
        ConsoleWriter.write("\n" + indent1 + "}");
        if (edgesIterator.hasNext()) {
            ConsoleWriter.write(",");
        }
    }
    ConsoleWriter.write("\n" + indent0 + "]");
}

From source file:kr.debop4j.core.tools.StringTool.java

/**
 * Replicate string.//w ww  . java 2 s .  c  o  m
 *
 * @param str ?
 * @param n   the n
 * @return the string
 */
public static String replicate(final String str, int n) {
    return Strings.repeat(str, n);
}

From source file:com.google.caliper.ConsoleReport.java

/**
 * Returns a string containing a bar of proportional width to the specified
 * value./*from   w  w  w  .  j  av  a  2s  .c  o m*/
 */
private String barGraph(double value) {
    int graphLength = floor(value / maxValue * barGraphWidth);
    graphLength = Math.max(1, graphLength);
    graphLength = Math.min(barGraphWidth, graphLength);
    return Strings.repeat("=", graphLength);
}

From source file:com.facebook.presto.byteCode.DumpByteCodeVisitor.java

private String indent(int level) {
    return Strings.repeat("    ", level);
}

From source file:com.spotify.helios.system.SystemTestBase.java

private void listThreads() {
    final Set<Thread> threads = Thread.getAllStackTraces().keySet();
    final Map<String, Thread> sorted = Maps.newTreeMap();
    for (final Thread t : threads) {
        final ThreadGroup tg = t.getThreadGroup();
        if (t.isAlive() && (tg == null || !tg.getName().equals("system"))) {
            sorted.put(t.getName(), t);// ww  w .j  av  a  2s . c o m
        }
    }
    log.info("= THREADS " + Strings.repeat("=", 70));
    for (final Thread t : sorted.values()) {
        final ThreadGroup tg = t.getThreadGroup();
        log.info("{}: \"{}\" ({}{})", t.getId(), t.getName(), (tg == null ? "" : tg.getName() + " "),
                (t.isDaemon() ? "daemon" : ""));
    }
    log.info(Strings.repeat("=", 80));
}

From source file:org.fabrician.enabler.DockerContainer.java

private void logDockerInspectMetadata(final String dockerContainerId) throws Exception {
    getEngineLogger().info(Strings.repeat("-", 10) + "inspect metadata for [" + dockerContainerId + "]"
            + Strings.repeat("-", 10));
    String command = "docker inspect " + dockerContainerId;
    if (useSudo) {
        command = "sudo " + command;
    }//  ww w.  j a  v a 2s  .  com
    File workDir = new File(getWorkDir());
    ProcessWrapper p = null;
    try {
        String engineOS = getEngineProperty(EngineProperties.OS);
        p = getProcessWrapper(command, workDir, engineOS + "_inspect.pid");
        Object lock = p.getLock();
        p.exec();
        synchronized (lock) {
            try {
                if (p.isRunning()) {
                    lock.wait(3000); // 3 secs
                    if (p.isRunning()) {
                        p.destroy();
                    }
                }
            } catch (InterruptedException e) {
                getEngineLogger().warning("logDockerInspectMetadata() thread was interrupted");
            }
        }
    } catch (Exception ex) {
        getEngineLogger().log(Level.SEVERE, "while inspecting docker container [" + dockerContainerId + "]",
                ex);
    }
}