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

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

Introduction

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

Prototype

@Nullable
public static String emptyToNull(@Nullable String string) 

Source Link

Document

Returns the given string if it is nonempty; null otherwise.

Usage

From source file:org.jenkinsci.plugins.zanata.cli.service.impl.ZanataSyncServiceImpl.java

@VisibleForTesting
protected ZanataSyncServiceImpl(PullService pullService, PushService pushService, HasSyncJobDetail jobDetail) {
    this.pullService = pullService;
    this.pushService = pushService;
    zanataUrl = jobDetail.getZanataURL();
    String syncToZanataOption = jobDetail.getSyncOption();
    pushToZanataOption = Strings.emptyToNull(syncToZanataOption);
    username = jobDetail.getZanataUsername();
    apiKey = jobDetail.getZanataSecret();
    projectConfigs = getProjectConfigs(jobDetail.getZanataProjectConfigs());

    localeId = jobDetail.getZanataLocaleIds();

    // if project id is given from webhook, only handle this project
    // String projectId = jobDetail.getProject();
    // if (!Strings.isNullOrEmpty(projectId)) {
    // pullOptions.setProj(projectId);
    // pushOptions.setProj(projectId);
    // }//from   w  ww .j a  va 2  s .c  o m
}

From source file:org.eclipse.buildship.core.launch.RunGradleBuildLaunchRequestJob.java

@Override
protected void writeExtraConfigInfo(OutputStreamWriter writer) throws IOException {
    String taskNames = Strings
            .emptyToNull(CollectionsUtils.joinWithSpace(this.configurationAttributes.getTasks()));
    taskNames = taskNames != null ? taskNames : CoreMessages.RunConfiguration_Value_RunDefaultTasks;
    writer.write(String.format("%s: %s%n", CoreMessages.RunConfiguration_Label_GradleTasks, taskNames));
}

From source file:com.google.gerrit.server.mail.receive.RawMailParser.java

/**
 * Parses a MailMessage from a string.//from w w w .  j a  v a2s  .c  o  m
 *
 * @param raw String as received over the wire
 * @return Parsed MailMessage
 * @throws MailParsingException
 */
public static MailMessage parse(String raw) throws MailParsingException {
    MailMessage.Builder messageBuilder = MailMessage.builder();
    messageBuilder.rawContentUTF(raw);
    Message mimeMessage;
    try {
        MessageBuilder builder = new DefaultMessageBuilder();
        mimeMessage = builder.parseMessage(new ByteArrayInputStream(raw.getBytes(UTF_8)));
    } catch (IOException | MimeException e) {
        throw new MailParsingException("Can't parse email", e);
    }
    // Add general headers
    if (mimeMessage.getMessageId() != null) {
        messageBuilder.id(mimeMessage.getMessageId());
    }
    if (mimeMessage.getSubject() != null) {
        messageBuilder.subject(mimeMessage.getSubject());
    }
    messageBuilder.dateReceived(new DateTime(mimeMessage.getDate()));

    // Add From, To and Cc
    if (mimeMessage.getFrom() != null && mimeMessage.getFrom().size() > 0) {
        Mailbox from = mimeMessage.getFrom().get(0);
        messageBuilder.from(new Address(from.getName(), from.getAddress()));
    }
    if (mimeMessage.getTo() != null) {
        for (Mailbox m : mimeMessage.getTo().flatten()) {
            messageBuilder.addTo(new Address(m.getName(), m.getAddress()));
        }
    }
    if (mimeMessage.getCc() != null) {
        for (Mailbox m : mimeMessage.getCc().flatten()) {
            messageBuilder.addCc(new Address(m.getName(), m.getAddress()));
        }
    }

    // Add additional headers
    mimeMessage.getHeader().getFields().stream().filter(f -> !MAIN_HEADERS.contains(f.getName().toLowerCase()))
            .forEach(f -> messageBuilder.addAdditionalHeader(f.getName() + ": " + f.getBody()));

    // Add text and html body parts
    StringBuilder textBuilder = new StringBuilder();
    StringBuilder htmlBuilder = new StringBuilder();
    try {
        handleMimePart(mimeMessage, textBuilder, htmlBuilder);
    } catch (IOException e) {
        throw new MailParsingException("Can't parse email", e);
    }
    messageBuilder.textContent(Strings.emptyToNull(textBuilder.toString()));
    messageBuilder.htmlContent(Strings.emptyToNull(htmlBuilder.toString()));

    try {
        // build() will only succeed if all required attributes were set. We wrap
        // the IllegalStateException in a MailParsingException indicating that
        // required attributes are missing, so that the caller doesn't fall over.
        return messageBuilder.build();
    } catch (IllegalStateException e) {
        throw new MailParsingException("Missing required attributes after email was parsed", e);
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.ui.GerritReviewBehavior.java

@Override
public IStatus addComment(IReviewItem item, IComment comment, IProgressMonitor monitor) {
    short side = RIGHT_SIDE;
    String id = item.getId();/*ww  w.  j  ava  2s .  c o  m*/
    if (id.startsWith(BASE)) {
        // base revision
        id = id.substring(BASE.length());
        side = LEFT_SIDE;
    }
    Patch.Key key = Patch.Key.parse(id);
    for (ILocation location : comment.getLocations()) {
        if (location instanceof ILineLocation) {
            ILineLocation lineLocation = (ILineLocation) location;
            SaveDraftRequest request = new SaveDraftRequest(key, lineLocation.getRangeMin(), side, null,
                    Strings.emptyToNull(comment.getId()));
            request.setMessage(comment.getDescription());

            GerritOperation<PatchLineComment> operation = getOperationFactory().createOperation(getTask(),
                    request);
            IStatus status = operation.run(monitor);
            PatchLineComment patchLineComment = operation.getOperationResult();
            // save the value of uuid, and keep it with the comment
            if (patchLineComment != null && patchLineComment.getKey() != null) {
                comment.setId(patchLineComment.getKey().get());
            }
            return status;
        }
    }
    //We'll only get here if there is something really broken in calling code or model. Gerrit has one and only one comment per location.
    throw new RuntimeException(NLS.bind(Messages.GerritReviewBehavior_Internal_Exception, comment.getId()));
}

From source file:org.killbill.billing.invoice.template.HtmlInvoiceGenerator.java

public HtmlInvoice generateInvoice(final Account account, @Nullable final Invoice invoice,
        final boolean manualPay, final InternalTenantContext context) throws IOException {
    // Don't do anything if the invoice is null
    if (invoice == null) {
        return null;
    }/*from  w w w  . j  ava2  s. c  o  m*/

    final String accountLocale = Strings.emptyToNull(account.getLocale());
    final Locale locale = accountLocale == null ? Locale.getDefault() : LocaleUtils.toLocale(accountLocale);

    final HtmlInvoice invoiceData = new HtmlInvoice();
    final Map<String, Object> data = new HashMap<String, Object>();

    final ResourceBundle invoiceBundle = accountLocale != null
            ? bundleFactory.createBundle(LocaleUtils.toLocale(accountLocale),
                    config.getInvoiceTemplateBundlePath(), ResourceBundleType.INVOICE_TRANSLATION, context)
            : null;
    final ResourceBundle defaultInvoiceBundle = bundleFactory.createBundle(Locale.getDefault(),
            config.getInvoiceTemplateBundlePath(), ResourceBundleType.INVOICE_TRANSLATION, context);
    final DefaultInvoiceTranslator invoiceTranslator = new DefaultInvoiceTranslator(invoiceBundle,
            defaultInvoiceBundle);

    data.put("text", invoiceTranslator);
    data.put("account", account);

    final InvoiceFormatter formattedInvoice = factory.createInvoiceFormatter(config, invoice, locale,
            currencyConversionApi, bundleFactory, context);
    data.put("invoice", formattedInvoice);

    invoiceData.setSubject(invoiceTranslator.getInvoiceEmailSubject());
    final String templateText = getTemplateText(locale, manualPay, context);
    invoiceData.setBody(templateEngine.executeTemplateText(templateText, data));
    return invoiceData;
}

From source file:org.n52.shetland.w3c.xlink.Reference.java

public Reference setRemoteSchema(String remoteSchema) {
    this.remoteSchema = Optional.ofNullable(Strings.emptyToNull(remoteSchema));
    return this;
}

From source file:fathom.xmlrpc.XmlRpcMethodInvoker.java

Method findMethod(String methodName, List<Object> methodParameters) throws NoSuchMethodException {
    Class[] argClasses = null;//  w w w  .  ja v a 2  s. c o m
    if (methodParameters != null) {
        argClasses = new Class[methodParameters.size()];
        for (int i = 0; i < methodParameters.size(); i++) {
            Object value = methodParameters.get(i);
            if (value instanceof Integer) {
                argClasses[i] = Integer.TYPE;
            } else if (value instanceof Double) {
                argClasses[i] = Double.TYPE;
            } else if (value instanceof Boolean) {
                argClasses[i] = Boolean.TYPE;
            } else {
                argClasses[i] = value.getClass();
            }
        }
    }

    final String argsTypeList = Arrays.toString(argClasses);
    final String methodKey = methodName + argsTypeList;
    if (methodCache.containsKey(methodKey)) {
        return methodCache.get(methodKey);
    }

    final String xmlrpcMethod;
    if (Strings.isNullOrEmpty(methodGroup)) {
        xmlrpcMethod = methodName;
    } else {
        xmlrpcMethod = methodGroup + '.' + methodName;
    }

    log.debug("Locating @XmlRpc '{}' {}", xmlrpcMethod, argsTypeList);
    for (Method method : targetClass.getMethods()) {
        if (method.isAnnotationPresent(XmlRpc.class)) {
            XmlRpc xmlRpc = ClassUtil.getAnnotation(method, XmlRpc.class);
            String name = Optional.fromNullable(Strings.emptyToNull(xmlRpc.value())).or(method.getName());
            if (methodName.equals(name) && Arrays.equals(argClasses, method.getParameterTypes())) {
                methodCache.put(methodKey, method);
                return method;
            }
        }
    }

    log.warn("Failed to find @XmlRpc '{}' {}", xmlrpcMethod, argsTypeList);
    return null;
}

From source file:com.sk89q.eduardo.plugin.irc.PircBotXClient.java

@Inject
public PircBotXClient(Config config, EventBus eventBus) {
    eventBus.register(this);

    Config irc = config.getConfig("irc");

    Builder<IRCBot> base = new Configuration.Builder<IRCBot>().setVersion(irc.getString("version", "Eduardo"))
            .setAutoSplitMessage(true).setIdentServerEnabled(false).setAutoNickChange(true);

    for (Config server : irc.getList("servers", Config.class)) {
        Builder<IRCBot> builder = new Builder<>(base).setServer(server.getString("host", "localhost"),
                server.getInt("port", 6667), server.getString("password", ""));

        builder.setName(server.getString("name", "MyNewBot")).setLogin(server.getString("name", "MyNewBot"))
                .setFinger(server.getString("name", "MyNewBot"))
                .setRealName(server.getString("name", "MyNewBot"));

        if (server.getBoolean("ssl", false)) {
            builder.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates());
        }/* w  w  w  .ja v a  2  s .c o  m*/

        builder.setNickservPassword(Strings.emptyToNull(server.getString("nickserv.password", "")));

        for (String channel : server.getList("auto-join", String.class)) {
            log.info("Auto-joining channel {}", channel);
            builder.addAutoJoinChannel(channel);
        }

        builders.put(server.getString("id", "noname-" + System.currentTimeMillis()), builder);
    }
}

From source file:com.tinspx.util.net.CofigURLConnection.java

@Override
public String getHeaderField(String name) {
    return headers != null ? Strings.emptyToNull(headers.last(name)) : null;
}

From source file:org.eclipse.che.ide.ext.svn.client.export.ExportPresenter.java

/** {@inheritDoc} */
@Override/*from w  w  w. j  a  v a2 s  .co  m*/
public void onExportClicked() {
    final String projectPath = getCurrentProjectPath();

    if (projectPath == null) {
        return;
    }

    final String exportPath = MoreObjects.firstNonNull(
            Strings.emptyToNull(relPath(projectPath, ((StorableNode) selectedNode).getPath())), ".");
    final String revision = view.isRevisionSpecified() ? view.getRevision() : null;

    final Notification notification = new Notification(constants.exportStarted(exportPath), PROGRESS);
    notificationManager.showNotification(notification);

    view.onClose();

    char prefix = '?';
    StringBuilder url = new StringBuilder(baseHttpUrl + "/export" + projectPath);

    if (!Strings.isNullOrEmpty(exportPath)) {
        url.append(prefix).append("path").append('=').append(exportPath);
        prefix = '&';
    }

    if (!Strings.isNullOrEmpty(revision)) {
        url.append(prefix).append("revision").append('=').append(revision);
    }

    Window.open(url.toString(), "_self", "");
}