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:com.heartbleed.HeartbleedScanner.java

/**
 * see https://tools.ietf.org/html/rfc6520#section-2
 *///from  www. java 2 s  .c om
private static byte[] buildHeartbeatMessage(TlsVersion version, ScanMode mode) {
    Preconditions.checkNotNull(version);

    // https://tools.ietf.org/html/rfc6520#section-6
    final byte TLS_HEARTBEAT_CONTENT_TYPE = 0x18;

    String payload = null;
    byte[] payloadBytes = null;
    byte[] paddingBytes = null;

    if (mode.equals(ScanMode.INTRUSIVE)) {
        payload = "foo";
        payloadBytes = payload.getBytes();
        paddingBytes = mode.getPaddingString().getBytes();
    } else {
        // This sends a large message, but without the requisite 16 bytes of padding.
        payload = Strings.repeat("A", 5000);
        payloadBytes = payload.getBytes();
        paddingBytes = "".getBytes();
    }

    int heartbeatLength = 1 + /* message type */
            2 + /* uint16 length */
            payloadBytes.length + paddingBytes.length;

    ByteBuffer heartbeatMessage = ByteBuffer.allocate(heartbeatLength);
    heartbeatMessage.put((byte) 0x01); // heartbeat request
    if (mode.equals(ScanMode.INTRUSIVE)) {
        // Claim a length of 2^14 -1 to trigger an overread.
        heartbeatMessage.put(intToUint16(0x3FFF));
    } else {
        // Do not include the message type or int16 length.
        heartbeatMessage.put(intToUint16(heartbeatLength - 3));
    }
    heartbeatMessage.put(payloadBytes);
    heartbeatMessage.put(paddingBytes);

    int tlsRecordLength = 1 + /* content type */
            2 + /* protocol version */
            2 + /* length */
            heartbeatLength; /* fragment */

    ByteBuffer tlsRecord = ByteBuffer.allocate(tlsRecordLength);
    tlsRecord.put(TLS_HEARTBEAT_CONTENT_TYPE);
    tlsRecord.put(version.getBytes());
    tlsRecord.put(intToUint16(heartbeatLength));
    tlsRecord.put(heartbeatMessage.array());
    return tlsRecord.array();
}

From source file:ezbake.deployer.cli.EzDeployerCli.java

public int run() throws TException, IOException, EzConfigurationLoaderException {
    if (globalParameters.isVersion()) {
        System.out.println("EzDeployCli version " + getCliVersion());
        return 0;
    }//from  w  w  w  . ja  v a 2s .c om
    if (globalParameters.isHelp()) {
        displayHelp();
        return 0;
    }

    String configurationDir = Preconditions.checkNotNull(globalParameters.getConfigurationDir(),
            "Must specify the cli configuration dir");
    File confDir = new File(configurationDir);
    if (!confDir.exists() || !confDir.isDirectory()) {
        throw new RuntimeException(configurationDir + " does not exist or is not a directory!");
    }
    configuration = new EzConfiguration(new DirectoryConfigurationLoader(confDir.toPath()),
            new DirectoryConfigurationLoader());

    Supplier<EzBakeServiceDeployer.Client> clientSupplier = Suppliers
            .memoize(new Supplier<EzBakeServiceDeployer.Client>() {
                @Override
                public EzBakeServiceDeployer.Client get() {
                    try {
                        return connectClient();
                    } catch (TException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
    EzbakeSecurityClient securityClient = new EzbakeSecurityClient(configuration.getProperties());
    for (Command cmd : allCommands) {
        cmd.setGlobalParameters(globalParameters).setClientSupplier(clientSupplier)
                .setSecurityClient(securityClient).setConfiguration(configuration);
    }

    this.client = connectClient();
    try {
        getOperation(globalParameters.operation).call();
        return 0;
    } catch (InvalidOperation e) {
        System.out.println(Strings.repeat("\n", 3));
        System.out.println(e.getMessage());
        globalParameters.operation = "";
        displayHelp();
        System.out.println(Strings.repeat("\n", 3));
        return 1;
    } catch (UsageException usage) {
        System.out.println(Strings.repeat("\n", 3));
        usage.cmd.displayHelp();
        System.err.println(usage.errorMessage);
        System.out.println(Strings.repeat("\n", 3));
        return 1;
    }
}

From source file:com.google.api.server.spi.tools.EndpointsToolAction.java

@Override
protected List<String> getHelpLines() {
    ImmutableList.Builder<String> helpLines = ImmutableList.builder();
    helpLines.add(getNameString());/*from   w  w  w .jav  a2s. co m*/
    helpLines.add("");
    helpLines.addAll(wrap(getShortDescription(), MAX_WIDTH, 0));
    helpLines.add("");
    helpLines.add("Usage: <Endpoints tool> " + getUsageString());
    if (getOptions().size() > 0) {
        helpLines.add("");
        helpLines.add("Options:");
        for (Option option : getOptions()) {
            for (String optionHelpLine : option.getHelpLines()) {
                helpLines.add(Strings.repeat(" ", OPTION_INDENT) + optionHelpLine);
            }
        }
    }
    helpLines.add("");
    if (!Strings.isNullOrEmpty(exampleString)) {
        helpLines.add("Example:");
        helpLines.add("  " + exampleString);
        helpLines.add("");
    }
    return helpLines.build();
}

From source file:com.netflix.niws.client.URLSslContextFactory.java

@Override
public String toString() {
    final StringBuilder builder = new StringBuilder();

    builder.append("ClientSslSocketFactory [trustStoreUrl=").append(trustStoreUrl);
    if (trustStoreUrl != null) {
        builder.append(", trustStorePassword=");
        builder.append(Strings.repeat("*", this.getTrustStorePasswordLength()));
    }/* w ww .  j a  v  a 2 s. c o m*/
    builder.append(", keyStoreUrl=").append(keyStoreUrl);
    if (keyStoreUrl != null) {
        builder.append(", keystorePassword = ");
        builder.append(Strings.repeat("*", this.getKeyStorePasswordLength()));
    }
    builder.append(']');

    return builder.toString();
}

From source file:org.opendaylight.infrautils.utils.TablePrinter.java

private static void printSeparator(String separator, StringBuilder sb, int integer) {
    if (integer == 0) {
        sb.append(Strings.repeat(" ", SPACE_BETWEEN_COLUMNS));
    } else {/*from  w  ww  . ja v a2s . c  o m*/
        sb.append(separator);
    }
}

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

/**
 * Writes a debug graph for the given list of hypernodes.
 *
 * @param layeredGraph//from ww w .  j  a v a  2s.c  o  m
 *            the layered graph
 * @param layerIndex
 *            the currently processed layer's index
 * @param hypernodes
 *            a list of hypernodes
 * @param debugPrefix
 *            prefix of debug output files
 * @param label
 *            a label to append to the output files
 */
public static void writeDebugGraph(final LGraph layeredGraph, final int layerIndex,
        final List<HyperNode> hypernodes, final String debugPrefix, final String label) {

    try {
        final ConsoleWriter ConsoleWriter = createConsoleWriter(layeredGraph, layerIndex, debugPrefix, label);
        beginGraph(ConsoleWriter, layeredGraph);

        final String indent1 = Strings.repeat(INDENT, 2);
        final String indent2 = Strings.repeat(INDENT, 3); // SUPPRESS
        // CHECKSTYLE
        // MagicNumber
        int edgeId = 0;

        final Iterator<HyperNode> hypernodeIterator = hypernodes.iterator();

        final StringBuffer edges = new StringBuffer();

        while (hypernodeIterator.hasNext()) {
            final HyperNode hypernode = hypernodeIterator.next();
            ConsoleWriter.write("\n" + indent1 + "{\n" + indent2 + "\"id\": \"n"
                    + System.identityHashCode(hypernode) + "\",\n" + indent2 + "\"labels\": [ { \"text\": \""
                    + hypernode.toString() + "\" } ],\n" + indent2 + "\"width\": 50,\n" + indent2
                    + "\"height\": 25\n" + indent1 + "}");
            if (hypernodeIterator.hasNext()) {
                ConsoleWriter.write(",");
            }

            final Iterator<Dependency> dependencyIterator = hypernode.getOutgoing().iterator();

            while (dependencyIterator.hasNext()) {
                final Dependency dependency = dependencyIterator.next();
                edges.append("\n" + indent1 + "{\n" + indent2 + "\"id\": \"e" + edgeId++ + "\",\n" + indent2
                        + "\"source\": \"n" + System.identityHashCode(hypernode) + "\",\n" + indent2
                        + "\"target\": \"n" + System.identityHashCode(dependency.getTarget()) + "\"\n" + indent1
                        + "},");
            }
        }

        endChildNodeList(ConsoleWriter);

        if (edges.length() > 0) {
            edges.deleteCharAt(edges.length() - 1);
        }
        ConsoleWriter.write(INDENT + "\"edges\": [" + edges + "\n" + INDENT + "]");

        endGraph(ConsoleWriter);
    } catch (final Exception exception) {
        exception.printStackTrace();
    }
}

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

private TypeSpec toTypeSpec(EnumType type) {
    ClassName typeName = (ClassName) javaGenerator.typeName(type.name());

    TypeSpec.Builder builder = TypeSpec.enumBuilder(typeName.simpleName()).addModifiers(PUBLIC)
            .addSuperinterface(ProtoEnum.class);

    if (!type.documentation().isEmpty()) {
        builder.addJavadoc("$L\n", JavaGenerator.sanitizeJavadoc(type.documentation()));
    }//from  w  w  w. j a  va  2  s  . co  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<Field> allOptionFieldsBuilder = new LinkedHashSet<>();
    for (EnumConstant constant : type.constants()) {
        for (Field optionField : constant.options().map().keySet()) {
            String fullyQualifiedName = optionField.packageName() + "." + optionField.name();
            if (!enumOptions.contains(fullyQualifiedName)) {
                continue;
            }

            if (allOptionFieldsBuilder.add(optionField)) {
                TypeName javaType = javaGenerator.typeName(optionField.type());
                builder.addField(javaType, optionField.name(), PUBLIC, FINAL);
                constructorBuilder.addParameter(javaType, optionField.name());
                constructorBuilder.addStatement("this.$L = $L", optionField.name(), optionField.name());
            }
        }
    }
    ImmutableList<Field> allOptionFields = ImmutableList.copyOf(allOptionFieldsBuilder);
    String enumArgsFormat = "$L" + Strings.repeat(", $L", allOptionFields.size());
    builder.addMethod(constructorBuilder.build());

    for (EnumConstant constant : type.constants()) {
        Object[] enumArgs = new Object[allOptionFields.size() + 1];
        enumArgs[0] = constant.tag();
        for (int i = 0; i < allOptionFields.size(); i++) {
            Field key = allOptionFields.get(i);
            Object value = constant.options().map().get(key);
            enumArgs[i + 1] = value != null ? fieldInitializer(key.type(), value) : null;
        }

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

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

    // Enum type options.
    if (emitOptions) {
        FieldSpec options = optionsField(JavaGenerator.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:parquet.tools.util.MetadataUtils.java

private static void showDetails(PrettyPrintWriter out, PrimitiveType type, int depth, MessageType container,
        List<String> cpath) {
    String name = Strings.repeat(".", depth) + type.getName();
    OriginalType otype = type.getOriginalType();
    Repetition rep = type.getRepetition();
    PrimitiveTypeName ptype = type.getPrimitiveTypeName();

    out.format("%s: %s %s", name, rep, ptype);
    if (otype != null)
        out.format(" O:%s", otype);

    if (container != null) {
        cpath.add(type.getName());//from  ww  w .ja  v  a2  s  . c o m
        String[] paths = cpath.toArray(new String[cpath.size()]);
        cpath.remove(cpath.size() - 1);

        ColumnDescriptor desc = container.getColumnDescription(paths);

        int defl = desc.getMaxDefinitionLevel();
        int repl = desc.getMaxRepetitionLevel();
        out.format(" R:%d D:%d", repl, defl);
    }
    out.println();
}

From source file:com.google.javascript.jscomp.deps.PathUtil.java

/**
 * Returns targetPath relative to basePath.
 *
 * <p>basePath and targetPath must either both be relative, or both be
 * absolute paths.</p>//from ww w .  j a  va2  s  .com
 *
 * <p>This function is different from makeRelative
 * in that it is able to add in ../ components and collapse existing ones as well.</p>
 *
 * Examples:
 *   base="some/relative/path" target="some/relative/path/foo" return="foo"
 *   base="some/relative/path" target="some/relative" return=".."
 *   base="some/relative/path" target="foo/bar" return="../../../foo/bar"
 *   base="/some/abs/path" target="/foo/bar" return="../../../foo/bar"
 *
 * @param basePath The path to make targetPath relative to.
 * @param targetPath The path to make relative.
 * @return A path relative to targetPath. The returned value will never start
 *     with a slash.
 */
public static String makeRelative(String basePath, String targetPath) {
    // Ensure the paths are both absolute or both relative.
    if (isAbsolute(basePath) != isAbsolute(targetPath)) {
        throw new IllegalArgumentException("Paths must both be relative or both absolute.\n" + "  basePath: "
                + basePath + "\n" + "  targetPath: " + targetPath);
    }

    basePath = collapseDots(basePath);
    targetPath = collapseDots(targetPath);
    String[] baseFragments = basePath.split("/");
    String[] targetFragments = targetPath.split("/");

    int i = -1;
    do {
        i += 1;
        if (i == baseFragments.length && i == targetFragments.length) {
            // Eg) base: /java/com/google
            //   target: /java/com/google
            //   result: .  <-- . is better than "" since "" + "/path" = "/path"
            return ".";
        } else if (i == baseFragments.length) {
            // Eg) base: /java/com/google
            //   target: /java/com/google/c/ui
            //   result: c/ui
            return Joiner.on("/").join(Lists.newArrayList(Arrays.asList(targetFragments).listIterator(i)));
        } else if (i == targetFragments.length) {
            // Eg) base: /java/com/google/c/ui
            //   target: /java/com/google
            //   result: ../..
            return Strings.repeat("../", baseFragments.length - i - 1) + "..";
        }

    } while (baseFragments[i].equals(targetFragments[i]));

    // Eg) base: /java/com/google/c
    //   target: /java/com/google/common/base
    //   result: ../common/base
    return Strings.repeat("../", baseFragments.length - i)
            + Joiner.on("/").join(Lists.newArrayList(Arrays.asList(targetFragments).listIterator(i)));
}

From source file:com.synflow.models.node.Node.java

private String toString(int indent) {
    StringBuilder builder = new StringBuilder(Strings.repeat("|  ", indent));
    builder.append(content);//from  www.  java 2s. c om
    builder.append('\n');
    for (Node child : getChildren()) {
        builder.append(child.toString(indent + 1));
    }
    return builder.toString();
}