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.sonatype.nexus.jmx.internal.ManagedObjectRegistrar.java

/**
 * Determine object-name 'type' value.//from w ww .  j ava2 s. c  o m
 */
private String type(final ManagedObject descriptor, final BeanEntry<Annotation, Object> entry) {
    String type = Strings.emptyToNull(descriptor.type());
    if (type == null) {
        if (descriptor.typeClass() != null && descriptor.typeClass() != Void.class /*default*/) {
            type = descriptor.typeClass().getSimpleName();
        } else {
            // TODO: Consider inspecting @Typed?
            // TODO: It would really be nice if we could infer the proper intf type of simple components, but this may be too complex?
            type = entry.getImplementationClass().getSimpleName();
        }
    }
    return type;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*  w w w  . j  a va2 s. c om*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:org.eclipse.buildship.ui.launch.JavaHomeTab.java

@SuppressWarnings("Contract")
@Override/*from w ww . j ava2  s. c o  m*/
public boolean isValid(ILaunchConfiguration launchConfig) {
    String javaHomeExpression = Strings.emptyToNull(this.javaHomeText.getText());

    String javaHomeResolved;
    try {
        javaHomeResolved = ExpressionUtils.decode(javaHomeExpression);
    } catch (CoreException e) {
        setErrorMessage(NLS.bind(LaunchMessages.ErrorMessage_CannotResolveExpression_0, javaHomeExpression));
        return false;
    }

    File javaHome = FileUtils.getAbsoluteFile(javaHomeResolved).orNull();
    Optional<String> error = this.javaHomeValidator.validate(javaHome);
    setErrorMessage(error.orNull());
    return !error.isPresent();
}

From source file:org.zanata.service.impl.ProjectServiceImpl.java

@Transactional
@Override//  w  w w .  ja  va  2  s  .c om
public boolean addWebhook(HProject project, String url, String secret, String name, Set<WebhookType> types) {
    if (types.isEmpty()) {
        return false;
    }
    if (project == null) {
        return false;
    }
    secret = StringUtils.isBlank(secret) ? null : secret;
    WebHook webHook = new WebHook(project, url, Strings.emptyToNull(name), types, secret);
    project.getWebHooks().add(webHook);
    projectDAO.makePersistent(project);
    return true;
}

From source file:de.bund.bfr.knime.pmm.js.common.Indep.java

/**
 * Sets the category of this {@link Indep}.
 * //from w w w  .j  a va  2  s  .com
 * Empty strings are converted to null.
 * 
 * @param category
 *            the category to be set
 */
public void setCategory(String category) {
    this.category = Strings.emptyToNull(category);
}

From source file:org.killbill.billing.plugin.notification.generator.TemplateRenderer.java

private EmailContent getEmailContent(final TemplateType templateType, final AccountData account,
        @Nullable Subscription subscription, @Nullable final Invoice invoice,
        @Nullable final PaymentTransaction paymentTransaction, final TenantContext context)
        throws IOException, TenantApiException {

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

    final Map<String, Object> data = new HashMap<String, Object>();
    final Map<String, String> text = getTranslationMap(accountLocale,
            ResourceBundleFactory.ResourceBundleType.TEMPLATE_TRANSLATION, context);
    data.put("text", text);
    data.put("account", account);
    if (subscription != null) {
        data.put("subscription", subscription);
    }//  ww w . j a  v a 2  s  . c o  m
    if (invoice != null) {
        final InvoiceFormatter formattedInvoice = new DefaultInvoiceFormatter(text, invoice, locale);
        data.put("invoice", formattedInvoice);
    }
    if (paymentTransaction != null) {
        final PaymentFormatter formattedPayment = new PaymentFormatter(paymentTransaction, locale);
        data.put("payment", formattedPayment);
    }

    final String templateText = getTemplateText(locale, templateType, context);
    final String body = templateEngine.executeTemplateText(templateText, data);
    final String subject = new StringBuffer((String) text.get("merchantName")).append(": ")
            .append(text.get(templateType.getSubjectKeyName())).toString();
    return new EmailContent(subject, body);
}

From source file:com.google.gerrit.server.project.PutConfig.java

public ConfigInfo apply(ProjectControl ctrl, ConfigInput input)
        throws ResourceNotFoundException, BadRequestException, ResourceConflictException {
    Project.NameKey projectName = ctrl.getProject().getNameKey();
    if (input == null) {
        throw new BadRequestException("config is required");
    }//  w  ww  . j  av a  2s. c o m

    try (MetaDataUpdate md = metaDataUpdateFactory.get().create(projectName)) {
        ProjectConfig projectConfig = ProjectConfig.read(md);
        Project p = projectConfig.getProject();

        p.setDescription(Strings.emptyToNull(input.description));

        if (input.useContributorAgreements != null) {
            p.setUseContributorAgreements(input.useContributorAgreements);
        }
        if (input.useContentMerge != null) {
            p.setUseContentMerge(input.useContentMerge);
        }
        if (input.useSignedOffBy != null) {
            p.setUseSignedOffBy(input.useSignedOffBy);
        }

        if (input.createNewChangeForAllNotInTarget != null) {
            p.setCreateNewChangeForAllNotInTarget(input.createNewChangeForAllNotInTarget);
        }

        if (input.requireChangeId != null) {
            p.setRequireChangeID(input.requireChangeId);
        }

        if (serverEnableSignedPush) {
            if (input.enableSignedPush != null) {
                p.setEnableSignedPush(input.enableSignedPush);
            }
            if (input.requireSignedPush != null) {
                p.setRequireSignedPush(input.requireSignedPush);
            }
        }

        if (input.rejectImplicitMerges != null) {
            p.setRejectImplicitMerges(input.rejectImplicitMerges);
        }

        if (input.maxObjectSizeLimit != null) {
            p.setMaxObjectSizeLimit(input.maxObjectSizeLimit);
        }

        if (input.submitType != null) {
            p.setSubmitType(input.submitType);
        }

        if (input.state != null) {
            p.setState(input.state);
        }

        if (input.enableReviewerByEmail != null) {
            p.setEnableReviewerByEmail(input.enableReviewerByEmail);
        }

        if (input.pluginConfigValues != null) {
            setPluginConfigValues(ctrl.getProjectState(), projectConfig, input.pluginConfigValues);
        }

        md.setMessage("Modified project settings\n");
        try {
            projectConfig.commit(md);
            projectCache.evict(projectConfig.getProject());
            md.getRepository().setGitwebDescription(p.getDescription());
        } catch (IOException e) {
            if (e.getCause() instanceof ConfigInvalidException) {
                throw new ResourceConflictException(
                        "Cannot update " + projectName + ": " + e.getCause().getMessage());
            }
            log.warn(String.format("Failed to update config of project %s.", projectName), e);
            throw new ResourceConflictException("Cannot update " + projectName);
        }

        ProjectState state = projectStateFactory.create(projectConfig);
        return new ConfigInfoImpl(serverEnableSignedPush, state.controlFor(user.get()), config,
                pluginConfigEntries, cfgFactory, allProjects, views);
    } catch (RepositoryNotFoundException notFound) {
        throw new ResourceNotFoundException(projectName.get());
    } catch (ConfigInvalidException err) {
        throw new ResourceConflictException("Cannot read project " + projectName, err);
    } catch (IOException err) {
        throw new ResourceConflictException("Cannot update project " + projectName, err);
    }
}

From source file:com.google.gerrit.server.account.externalids.ExternalId.java

public static ExternalId create(Key key, Account.Id accountId, @Nullable String email,
        @Nullable String hashedPassword) {
    return new AutoValue_ExternalId(key, accountId, Strings.emptyToNull(email),
            Strings.emptyToNull(hashedPassword));
}

From source file:ratpack.server.internal.DefaultPublicAddress.java

private HostAndPort getHostData(Context context) {
    Headers headers = context.getRequest().getHeaders();
    String hostPortString = Strings.emptyToNull(headers.get(HOST.toString()));
    return hostPortString != null ? HostAndPort.fromString(hostPortString) : null;
}

From source file:org.zanata.action.LocaleSelectorAction.java

public void setLocale(Locale locale) {
    language = Strings.emptyToNull(locale.getLanguage());
    country = Strings.emptyToNull(locale.getCountry());
    variant = Strings.emptyToNull(locale.getVariant());
}