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

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

Introduction

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

Prototype

public static String nullToEmpty(@Nullable String string) 

Source Link

Document

Returns the given string if it is non-null; the empty string otherwise.

Usage

From source file:org.gaul.s3proxy.AwsSignature.java

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 *//*ww w. j  a va 2 s  .  c  om*/
static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}

From source file:io.macgyver.core.cli.LoginCommand.java

public Optional<String> readUsername() {
    String username = getConfig().path("username").asText();
    if (Strings.isNullOrEmpty(username)) {
        username = System.getProperty("user.name", "");
    }//from   w w w . j a v  a 2 s  .com
    String usernameFromConsole = Strings.nullToEmpty(System.console().readLine("username [%s]: ", username))
            .trim();

    if (!Strings.isNullOrEmpty(usernameFromConsole)) {
        username = usernameFromConsole;
    }
    logger.info("username: " + username);
    return Optional.ofNullable(username);
}

From source file:com.google.gerrit.server.change.PutTopic.java

@Override
public Object apply(ChangeResource req, Input input)
        throws BadRequestException, AuthException, ResourceConflictException, Exception {
    if (input == null) {
        input = new Input();
    }/*from   w ww  .  j  a  va2  s . c om*/

    ChangeControl control = req.getControl();
    Change change = req.getChange();
    if (!control.canEditTopicName()) {
        throw new AuthException("changing topic not permitted");
    }

    ReviewDb db = dbProvider.get();
    final String newTopicName = Strings.nullToEmpty(input.topic);
    String oldTopicName = Strings.nullToEmpty(change.getTopic());
    if (!oldTopicName.equals(newTopicName)) {
        String summary;
        if (oldTopicName.isEmpty()) {
            summary = "Topic set to \"" + newTopicName + "\".";
        } else if (newTopicName.isEmpty()) {
            summary = "Topic \"" + oldTopicName + "\" removed.";
        } else {
            summary = String.format("Topic updated from \"%s\" to \"%s\".", oldTopicName, newTopicName);
        }

        ChangeMessage cmsg = new ChangeMessage(
                new ChangeMessage.Key(change.getId(), ChangeUtil.messageUUID(db)),
                ((IdentifiedUser) control.getCurrentUser()).getAccountId(), change.currentPatchSetId());
        StringBuilder msgBuf = new StringBuilder(summary);
        if (!Strings.isNullOrEmpty(input.message)) {
            msgBuf.append("\n\n");
            msgBuf.append(input.message);
        }
        cmsg.setMessage(msgBuf.toString());

        db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
            @Override
            public Change update(Change change) {
                change.setTopic(Strings.emptyToNull(newTopicName));
                return change;
            }
        });
        db.changeMessages().insert(Collections.singleton(cmsg));
    }
    return Strings.isNullOrEmpty(newTopicName) ? Response.none() : newTopicName;
}

From source file:com.google.gerrit.server.change.CherryPickCommit.java

@Override
public ChangeInfo apply(CommitResource rsrc, CherryPickInput input)
        throws OrmException, IOException, UpdateException, RestApiException {
    String message = Strings.nullToEmpty(input.message).trim();
    String destination = Strings.nullToEmpty(input.destination).trim();
    int parent = input.parent == null ? 1 : input.parent;

    if (destination.isEmpty()) {
        throw new BadRequestException("destination must be non-empty");
    }//from   ww  w .j  av a  2s . c  o m

    ProjectControl projectControl = rsrc.getProject();
    Capable capable = projectControl.canPushToAtLeastOneRef();
    if (capable != Capable.OK) {
        throw new AuthException(capable.getMessage());
    }

    RevCommit commit = rsrc.getCommit();
    String refName = RefNames.fullName(destination);
    RefControl refControl = projectControl.controlForRef(refName);
    if (!refControl.canUpload()) {
        throw new AuthException("Not allowed to cherry pick " + commit + " to " + destination);
    }

    Project.NameKey project = projectControl.getProject().getNameKey();
    try {
        Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(null, null, null, null, project, commit,
                message.isEmpty() ? commit.getFullMessage() : message, refName, refControl, parent);
        return json.noOptions().format(project, cherryPickedChangeId);
    } catch (InvalidChangeOperationException e) {
        throw new BadRequestException(e.getMessage());
    } catch (IntegrationException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}

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

public void _remotejobs(final CommandInterpreter interpreter) {

    try {/*from  w w  w  .j a v a 2  s.  c  o m*/

        final String cmd = Strings.nullToEmpty(interpreter.nextArgument()).toLowerCase();

        switch (cmd) {
        case "list":
            listJobs(interpreter);
            break;
        case "cancel":
            cancelJob(interpreter);
            break;
        default:
            interpreter.println(getHelp());
            break;
        }

    } catch (final Exception ex) {
        interpreter.println(ex.getMessage());
    }
}

From source file:org.cogroo.util.TextUtils.java

/**
 * @return the <code>String</code> to be printed
 *//*from w  w w . j  av a  2s. com*/
public static String nicePrint(Document document) {
    boolean printAdditionalContext = false;
    StringBuilder output = new StringBuilder();

    output.append("Document text: ").append(document.getText()).append("\n\n");

    if (document.getSentences() != null) {
        int cont = 0;
        for (Sentence sentence : document.getSentences()) {
            cont++;
            output.append("{Sentence ").append(cont).append(": ").append(sentence.getText()).append("\n");

            List<Token> tokens = sentence.getTokens();

            String format;

            Joiner joiner = Joiner.on(", ");

            if (tokens != null) {
                String[] lexemes = new String[tokens.size()];
                String[] posTags = new String[tokens.size()];
                String[] features = new String[tokens.size()];
                String[] lemmas = new String[tokens.size()];
                String[] chunks = new String[tokens.size()];
                String[] schunks = new String[tokens.size()];

                output.append("   (token, class tag, feature tag, lexeme, chunks, function)\n");
                for (int i = 0; i < tokens.size(); i++) {
                    Token t = tokens.get(i);

                    lexemes[i] = Strings.nullToEmpty(t.getLexeme());
                    posTags[i] = Strings.nullToEmpty(t.getPOSTag());
                    features[i] = Strings.nullToEmpty(t.getFeatures());

                    if (t.getLemmas() != null)
                        lemmas[i] = joiner.join(t.getLemmas());
                    else
                        lemmas[i] = "";

                    String head = "";
                    if (t.isChunkHead()) {
                        head = "*";
                    }
                    chunks[i] = t.getChunkTag() + head;

                    schunks[i] = t.getSyntacticTag();
                }

                format = "   | %-" + maxSize(lexemes) + "s | %-" + maxSize(posTags) + "s | %-"
                        + maxSize(features) + "s | %-" + maxSize(lemmas) + "s | %-" + maxSize(chunks) + "s | %-"
                        + maxSize(schunks) + "s |\n";

                for (int i = 0; i < tokens.size(); i++) {

                    output.append(String.format(format, lexemes[i], posTags[i], features[i], lemmas[i],
                            chunks[i], schunks[i]));

                }
                output.append("\n");

                if (printAdditionalContext) {
                    String[][] addcontext = TextUtils.additionalContext(tokens,
                            Arrays.asList(Analyzers.CONTRACTION_FINDER, Analyzers.NAME_FINDER));
                    for (String[] line : addcontext) {
                        for (String col : line) {
                            output.append("[");
                            if (col == null) {
                                output.append("-");
                            } else {
                                output.append(col);
                            }
                            output.append("]");
                        }
                        output.append("\n");
                    }
                }

            }

            output.append("   Syntax tree: \n   ");
            output.append(sentence.asTree().toSyntaxTree());

            output.append("\n}\n");
        }
    }
    return output.toString();
}

From source file:com.facebook.buck.plugin.intellij.ui.TargetsTreeRenderer.java

@Override
protected void initComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf,
        int row, boolean hasFocus) {
    if (value instanceof TargetNode) {
        TargetNode node = (TargetNode) value;
        String[] text = new String[] { node.getName() };
        Icon icon;/*from  w ww  .  j a v  a 2 s  . com*/
        switch (node.getType()) {
        case DIRECTORY:
            icon = AllIcons.Hierarchy.Base;
            break;
        case JAVA_LIBRARY:
            icon = AllIcons.Modules.Library;
            break;
        case JAVA_BINARY:
            icon = AllIcons.RunConfigurations.Application;
            break;
        case JAVA_TEST:
            icon = AllIcons.RunConfigurations.Junit;
            break;
        case OTHER:
            icon = AllIcons.General.ExternalTools;
            break;
        default:
            icon = AllIcons.General.Error;
        }
        setText(text, "");
        setIcon(icon);
    } else {
        String[] text = new String[] { value == null ? "" : value.toString() };
        text[0] = Strings.nullToEmpty(text[0]);
        setText(text, null);
        setIcon(null);
    }
}

From source file:org.activityinfo.ui.client.component.formdesigner.container.SectionWidgetContainer.java

public void syncWithModel() {
    widgetContainer.getLabel().setHTML("<h3>"
            + SafeHtmlUtils.fromString(Strings.nullToEmpty(formSection.getLabel())).asString() + "</h3>");
}

From source file:br.edu.utfpr.cm.JGitMinerWeb.services.metric.social.NumberOfMentionsMetric.java

private Integer calculateNumberOfMentions(EntityIssue issue) throws Exception {
    Integer numberOfMentions = 0;

    numberOfMentions += MentionsValidator.mentionInString(Strings.nullToEmpty(issue.getBody()));

    for (EntityComment entityComment : issue.getComments()) {

        numberOfMentions += MentionsValidator.mentionInString(Strings.nullToEmpty(entityComment.getBody()));

    }/*from   www.ja  va2s  .  co  m*/

    return numberOfMentions;
}

From source file:uk.org.ngo.squeezer.model.Album.java

public Album(Map<String, String> record) {
    setId(record.containsKey("album_id") ? record.get("album_id") : record.get("id"));
    setName(record.get("album"));
    setArtist(record.get("artist"));
    setYear(Util.parseDecimalIntOrZero(record.get("year")));
    setArtwork_track_id(record.get("artwork_track_id"));
    mArtworkUrl = Uri.parse(Strings.nullToEmpty(record.get("artwork_url")));
}