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

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

Introduction

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

Prototype

public static String padEnd(String string, int minLength, char padChar) 

Source Link

Document

Returns a string, of length at least minLength , consisting of string appended with as many copies of padChar as are necessary to reach that length.

Usage

From source file:org.geogit.cli.porcelain.Show.java

public void printFormatted(GeogitCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIT geogit = cli.getGeogit();//w w  w. j  a  va 2  s .  c om
    for (String ref : refs) {
        Optional<RevObject> obj = geogit.command(RevObjectParse.class).setRefSpec(ref).call();
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            RevFeatureType ft = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call().get();
            ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
            RevFeature feature = (RevFeature) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline()
                    .newline();
            ansi.a("ATTRIBUTES  ").newline();
            ansi.a("----------  ").newline();
            ImmutableList<Optional<Object>> values = feature.getValues();
            int i = 0;
            for (Optional<Object> value : values) {
                ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                ansi.a(value.or("[NULL]").toString()).newline();
                i++;
            }
            console.println(ansi.toString());

        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());

            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset()
                    .a(Integer.toString(tree.numTrees()).toString()).newline();

            printFeatureType(ansi, ft, true);

            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset()
                    .newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ")
                    .a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getCommitter().getTimestamp())).reset()
                    .a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException(
                    "Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }

}

From source file:com.comphenix.protocol.utility.ChatExtensions.java

/**
 * Print a flower box around a given message.
 * @param message - the message to print.
 * @param marginChar - the character to use as margin.
 * @param marginWidth - the width (in characters) of the left and right margin.
 * @param marginHeight - the height (in characters) of the top and buttom margin.
 * @return Flowerboxed message//from   w ww . j  av a 2s  .  c  o  m
 */
public static String[] toFlowerBox(String[] message, String marginChar, int marginWidth, int marginHeight) {
    String[] output = new String[message.length + marginHeight * 2];
    int width = getMaximumLength(message);

    // Margins
    String topButtomMargin = Strings.repeat(marginChar, width + marginWidth * 2);
    String leftRightMargin = Strings.repeat(marginChar, marginWidth);

    // Add left and right margin
    for (int i = 0; i < message.length; i++) {
        output[i + marginHeight] = leftRightMargin + Strings.padEnd(message[i], width, ' ') + leftRightMargin;
    }

    // Insert top and bottom margin
    for (int i = 0; i < marginHeight; i++) {
        output[i] = topButtomMargin;
        output[output.length - i - 1] = topButtomMargin;
    }
    return output;
}

From source file:org.robotframework.ide.eclipse.main.plugin.tableeditor.source.SuiteSourceFormattingStrategy.java

private String formatWithDynamicSeparator(final String content, final String delimiter,
        final FormatterProperties properties) {
    String tabsFreeContent;//from   w w w . j a  va2  s  . c o m
    try (BufferedReader reader = new BufferedReader(new StringReader(content))) {
        final StringBuilder contentWithoutTabs = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            contentWithoutTabs.append(line.replaceAll("\t", "  "));
            contentWithoutTabs.append(delimiter);
            line = reader.readLine();
        }
        tabsFreeContent = contentWithoutTabs.toString();
    } catch (final IOException e) {
        return content;
    }

    final Map<Integer, Integer> columnsLength = Maps.newHashMap();
    try (BufferedReader reader = new BufferedReader(new StringReader(tabsFreeContent))) {
        String line = reader.readLine();
        while (line != null) {
            updateCellLengths(line, columnsLength);

            line = reader.readLine();
        }
    } catch (final IOException e) {
        return content;
    }

    try (BufferedReader reader = new BufferedReader(new StringReader(tabsFreeContent))) {
        final StringBuilder formattedContent = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            int column = 0;
            final StringBuilder formattedLine = new StringBuilder();
            for (final String cell : Splitter.onPattern("  +").splitToList(line)) {
                formattedLine.append(Strings.padEnd(cell, columnsLength.get(column), ' '));
                formattedLine.append(Strings.repeat(" ", properties.separatorLength));
                column++;
            }
            formattedContent.append(formattedLine.toString().replaceAll(" +$", ""));
            formattedContent.append(delimiter);

            line = reader.readLine();
        }
        return formattedContent.toString();

    } catch (final IOException e) {
        return content;
    }
}

From source file:com.facebook.buck.cxx.platform.ObjectFileScrubbers.java

private static void putSpaceRightPaddedString(ByteBuffer buffer, int len, String value) {
    Preconditions.checkState(value.length() <= len);
    value = Strings.padEnd(value, len, ' ');
    buffer.put(value.getBytes(Charsets.US_ASCII));
}

From source file:fathom.Server.java

protected void logSetting(Settings.Setting setting, Object value) {
    log.debug("{}{}", Strings.padEnd(setting.toString(), 32, '.'), value);
}

From source file:com.facebook.buck.android.resources.ResourcesXml.java

private static int dumpNode(PrintStream out, StringPool strings, Optional<RefMap> refMap, int indent,
        Map<String, String> nsMap, ByteBuffer buf) {
    int type = buf.getShort(0);
    Preconditions.checkState(type >= XML_FIRST_TYPE && type <= XML_LAST_TYPE);
    switch (type) {
    case XML_START_NS: {
        // start namespace
        int prefixId = buf.getInt(16);
        String prefix = prefixId == -1 ? "" : strings.getString(prefixId);
        int uriId = buf.getInt(20);
        String uri = strings.getString(uriId);
        out.format("%sN: %s=%s\n", Strings.padEnd("", indent * 2, ' '), prefix, uri);
        indent++;//from  w  w  w .  j  a va  2 s  .  c o  m
        nsMap.put(uri, prefix);
        break;
    }
    case XML_END_NS:
        indent--;
        break;
    case XML_START_ELEMENT: {
        // start element
        int lineNumber = buf.getInt(8);
        int nameId = buf.getInt(20);
        String name = strings.getString(nameId);
        int attrCount = buf.getShort(28);
        ByteBuffer attrExt = slice(buf, 36);
        out.format("%sE: %s (line=%d)\n", Strings.padEnd("", indent * 2, ' '), name, lineNumber);
        indent++;
        for (int i = 0; i < attrCount; i++) {
            dumpAttribute(out, strings, refMap, slice(attrExt, attrExt.position()), indent, nsMap);
            attrExt.position(attrExt.position() + 20);
        }
        break;
    }
    case XML_END_ELEMENT:
        indent--;
        break;
    case XML_CDATA:
        throw new UnsupportedOperationException();
    }
    return indent;
}

From source file:com.b2international.snowowl.server.console.MaintenanceCommandProvider.java

private void repositories(CommandInterpreter interpreter) {
    final String repositoryId = interpreter.nextArgument();
    RepositorySearchRequestBuilder req = RepositoryRequests.prepareSearch();
    if (!Strings.isNullOrEmpty(repositoryId)) {
        req.one().filterById(repositoryId);
    } else {//www .  j a  v  a2  s .com
        req.all();
    }
    final Repositories repositories = req.buildAsync().execute(getBus()).getSync();

    final int maxDiagLength = ImmutableList.copyOf(repositories).stream().map(RepositoryInfo::diagnosis)
            .map(Strings::nullToEmpty).map(diag -> diag.length()).max(Ints::compare).orElse(16);

    final int maxLength = Math.max(maxDiagLength + 36, 52);

    printSeparator(interpreter, maxLength);
    printHeader(interpreter, "id", "health", Strings.padEnd("diagnosis", maxDiagLength, ' '));
    printSeparator(interpreter, maxLength);
    repositories.forEach(repository -> {
        printLine(interpreter, repository, RepositoryInfo::id, RepositoryInfo::health,
                repo -> Strings.isNullOrEmpty(repo.diagnosis()) ? "-" : null);
        printSeparator(interpreter, maxLength);
    });
}

From source file:fathom.rest.RestService.java

private void logRoutes(Router router) {
    if (!settings.getBoolean(SETTING_ROUTES_LOG, true)) {
        return;/*from   w  w w .  ja va  2  s.co  m*/
    }

    // determine the width of the columns
    int maxMethodLen = 0;
    int maxPathLen = 0;
    int maxControllerLen = 0;

    if (router.getRoutes().isEmpty()) {
        log.info("no routes found");
        return;
    }

    for (Route route : router.getRoutes()) {

        maxMethodLen = Math.max(maxMethodLen, route.getRequestMethod().length());
        maxPathLen = Math.max(maxPathLen, route.getUriPattern().length());

        if (route.getRouteHandler() instanceof ControllerHandler) {

            ControllerHandler handler = (ControllerHandler) route.getRouteHandler();
            int controllerLen = Util.toString(handler.getControllerMethod()).length();
            maxControllerLen = Math.max(maxControllerLen, controllerLen);

        } else if (route.getName() != null) {
            maxControllerLen = Math.max(maxControllerLen, route.getName().length());
        }

    }

    // log the routing table
    final int maxLineLength = settings.getInteger(SETTING_ROUTES_MAX_LINE_LENGTH, 120);
    final boolean logHandlers = settings.getBoolean(REST_ROUTES_LOG_HANDLERS, true);
    final boolean oneLine = (maxMethodLen + maxPathLen + maxControllerLen
            + 11 /* whitespace */) <= maxLineLength;
    if (!oneLine || !logHandlers) {
        maxPathLen = 0;
    }

    for (Route route : router.getRoutes()) {
        if (route.getRouteHandler() instanceof ControllerHandler) {

            ControllerHandler handler = (ControllerHandler) route.getRouteHandler();
            if (oneLine) {
                if (logHandlers) {
                    log.info("{} {}  =>  {}()", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                            Strings.padEnd(route.getUriPattern(), maxPathLen, ' '),
                            Util.toString(handler.getControllerMethod()));
                } else {
                    log.info("{} {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                            Strings.padEnd(route.getUriPattern(), maxPathLen, ' '));
                }
            } else {
                log.info("{} {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                        Strings.padEnd(route.getUriPattern(), maxPathLen, ' '));
                if (logHandlers) {
                    log.info("{} {}()", Strings.padEnd("", maxMethodLen, ' '),
                            Util.toString(handler.getControllerMethod()));
                }
            }

        } else if (route.getName() != null) {
            if (oneLine) {
                if (logHandlers) {
                    log.info("{} {}  =>  {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                            Strings.padEnd(route.getUriPattern(), maxPathLen, ' '), route.getName());
                } else {
                    log.info("{} {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                            Strings.padEnd(route.getUriPattern(), maxPathLen, ' '));
                }
            } else {
                log.info("{} {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                        Strings.padEnd(route.getUriPattern(), maxPathLen, ' '));
                if (logHandlers) {
                    log.info("{} {}", Strings.padEnd("", maxMethodLen, ' '), route.getName());
                }
            }
        } else {
            log.info("{} {}", Strings.padEnd(route.getRequestMethod(), maxMethodLen, ' '),
                    route.getUriPattern());
        }
    }

}

From source file:org.locationtech.geogig.cli.porcelain.Show.java

public void printFormatted(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();/*ww  w .  ja va2 s. c o m*/
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline();
                ansi.fg(Color.YELLOW).a("FEATURE TYPE ID:  ").reset().a(ft.getId().toString()).newline()
                        .newline();
                ansi.a("ATTRIBUTES  ").newline();
                ansi.a("----------  ").newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject))
                        .call();
                console.println(s);
            }

        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());

            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset()
                    .a(Integer.toString(tree.numTrees()).toString()).newline();

            printFeatureType(ansi, ft, true);

            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset()
                    .newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogig.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ")
                    .a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogig.getPlatform(), commit.getCommitter().getTimestamp())).reset()
                    .a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException(
                    "Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }

}

From source file:org.mla.cbox.shibboleth.idp.authn.impl.ProcessRedirectFromGoogle.java

/** {@inheritDoc} */
@Override//www.  ja va2  s  . c o  m
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {

    /* Ensure we were passed the incoming HTTP request */
    final HttpServletRequest servletRequest = getHttpServletRequest();
    if (servletRequest == null) {
        log.debug("{} Profile action does not contain an HttpServletRequest", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    /* Check the anti forgery state token returned by Google against the saved version in GoogleContext */
    final String antiForgeryStateToken = servletRequest.getParameter("state");
    if (antiForgeryStateToken == null || antiForgeryStateToken.isEmpty()) {
        log.debug("{} No anti forgery state token in request", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    log.debug("{} Google returned anti forgery state token {}", getLogPrefix(), antiForgeryStateToken);

    if (!antiForgeryStateToken.equals(googleContext.getAntiForgeryStateToken())) {
        log.debug("{} Anti forgery state token in request is not equal to token from Google Context",
                getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    /* Parse the one-time authorization code returned by Google */
    final String authorizationCode = servletRequest.getParameter("code");
    if (authorizationCode == null || authorizationCode.isEmpty()) {
        log.debug("{} No one-time authorization code in request", getLogPrefix());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    log.debug("{} Google one-time authorization code is {}", getLogPrefix(), authorizationCode);

    /* Query Google token endpoint using the one-time authorization code for an ID token */
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
            /* Set default parser as a JSON parser to make casting to class instance easier */
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });

    GenericUrl tokenEndpoint = new GenericUrl(googleContext.getGoogleIntegration().getTokenEndpoint());

    /* Prepare the POST body required at the token endpoint */
    Map<String, String> params = new HashMap<String, String>(5);
    params.put("code", authorizationCode);
    params.put("grant_type", "authorization_code");
    params.put("client_id", googleContext.getGoogleIntegration().getOauth2ClientId());
    params.put("client_secret", googleContext.getGoogleIntegration().getOauth2ClientSecret());
    params.put("redirect_uri", googleContext.getRedirectUri());

    HttpContent httpContent = new UrlEncodedContent(params);
    log.debug("{} computed token endpoint payload is {}", getLogPrefix(), httpContent.toString());

    try {
        HttpRequest request = requestFactory.buildPostRequest(tokenEndpoint, httpContent);

        log.debug("{} executing POST to Google token endpoint", getLogPrefix());
        HttpResponse response = request.execute();
        log.debug("{} done executing POST to Google token endpoint", getLogPrefix());

        /* Cast the response to a TokenResponse class instance */
        TokenResponse tokenResponse = response.parseAs(TokenResponse.class);
        log.debug("{} received token response {}", getLogPrefix(), tokenResponse.toPrettyString());

        /* Close the HTTP connection */
        response.disconnect();

        /* We do not validate the ID token since we just received it over a secure channel
         * and we are not going to pass it around. We just grab the payload
         * and pad it as necessary so we can then decode the base64 encoding.
         */
        String idTokenPayloadString = tokenResponse.getIdTokenString().split("\\.")[1];
        String idTokenPayloadStringPadded = Strings.padEnd(idTokenPayloadString,
                idTokenPayloadString.length() + (4 - (idTokenPayloadString.length() % 4)), '=');
        String idTokenPayloadStringDecoded = new String(
                DatatypeConverter.parseBase64Binary(idTokenPayloadStringPadded));

        /* Cast the ID token as instance of OidcIdToken class */
        JsonObjectParser jsonParser = new JsonObjectParser(JSON_FACTORY);
        OidcIdToken idToken = jsonParser.parseAndClose(new StringReader(idTokenPayloadStringDecoded),
                OidcIdToken.class);
        log.debug("{} id token is {}", getLogPrefix(), idToken.toPrettyString());

        /* Attach the ID token to the GoogleContext */
        googleContext.setIdToken(idToken);
    } catch (IOException e) {
        log.warn("{} exception exchanging authorization code for id token : {}", getLogPrefix(),
                e.getMessage());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    log.info("{} Login by '{}' succeeded", getLogPrefix(), googleContext.getIdToken().getSub());

    /* Complete the authentication flow by building the authentication result */
    buildAuthenticationResult(profileRequestContext, authenticationContext);
    ActionSupport.buildProceedEvent(profileRequestContext);
}