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:iop.org.iop_contributors_app.utils.CrashReporter.java

public static void appendDeviceInfo(final Appendable report, final Context context) throws IOException {
    final Resources res = context.getResources();
    final android.content.res.Configuration config = res.getConfiguration();
    final ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    final DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context
            .getSystemService(Context.DEVICE_POLICY_SERVICE);

    report.append("Device Model: " + Build.MODEL + "\n");
    report.append("Android Version: " + Build.VERSION.RELEASE + "\n");
    report.append("ABIs: ").append(Joiner.on(", ").skipNulls().join(Strings.emptyToNull(Build.CPU_ABI),
            Strings.emptyToNull(Build.CPU_ABI2))).append("\n");
    report.append("Board: " + Build.BOARD + "\n");
    report.append("Brand: " + Build.BRAND + "\n");
    report.append("Device: " + Build.DEVICE + "\n");
    report.append("Display: " + Build.DISPLAY + "\n");
    report.append("Finger Print: " + Build.FINGERPRINT + "\n");
    report.append("Host: " + Build.HOST + "\n");
    report.append("ID: " + Build.ID + "\n");
    report.append("Product: " + Build.PRODUCT + "\n");
    report.append("Tags: " + Build.TAGS + "\n");
    report.append("Time: " + Build.TIME + "\n");
    report.append("Type: " + Build.TYPE + "\n");
    report.append("User: " + Build.USER + "\n");
    report.append("Configuration: " + config + "\n");
    report.append("Screen Layout: size "
            + (config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_SIZE_MASK) + " long "
            + (config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_LONG_MASK) + "\n");
    report.append("Display Metrics: " + res.getDisplayMetrics() + "\n");
    report.append("Memory Class: " + activityManager.getMemoryClass() + "/" + largeMemoryClass(activityManager)
            + "\n");
    report.append("Storage Encryption Status: " + devicePolicyManager.getStorageEncryptionStatus() + "\n");
    //      report.append("Bluetooth MAC: " + bluetoothMac() + "\n");
}

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

@Override
public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException {
    if (input == null) {
        input = new TagInput();
    }/*from   w  w  w .  j a v  a 2  s .c  o  m*/
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }

    ref = RefUtil.normalizeTagRef(ref);

    RefControl refControl = resource.getControl().controlForRef(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated && !refControl.canPerform(Permission.CREATE_TAG)) {
            throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
        } else if (!refControl.canPerform(Permission.CREATE)) {
            throw new AuthException("Cannot create tag \"" + ref + "\"");
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }

        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length()))
                    .setAnnotated(isAnnotated).setSigned(isSigned);

            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(
                        identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
            }

            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(),
                    identifiedUser.get().getAccount());
            try (RevWalk w = new RevWalk(repo)) {
                return ListTags.createTagInfo(result, w, refControl);
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision");
    } catch (GitAPIException e) {
        log.error("Cannot create tag \"" + ref + "\"", e);
        throw new IOException(e);
    }
}

From source file:fathom.rest.security.FormAuthenticationHandler.java

protected void redirectRequest(Context context) {
    String originalDestination = context.getSession(AuthConstants.DESTINATION_ATTRIBUTE);
    String redirectPath = Optional.fromNullable(Strings.emptyToNull(originalDestination)).or("/");
    context.redirect(redirectPath);//  ww  w  .j  av a 2s.c  o m
}

From source file:org.killbill.billing.plugin.analytics.reports.ReportSpecification.java

private void parseRawReportName() {
    // rawReportName is in the form: payments_per_day(Currency report)^filter:currency=AUD^filter:currency=EUR^dimension:currency^dimension:state^metric:amount^metric:fee
    final Iterator<String> reportIterator = REPORT_SPECIFICATIONS_SPLITTER.split(rawReportName).iterator();

    boolean isFirst = true;
    while (reportIterator.hasNext()) {
        // rawSpecification is in the form: dimension:currency
        final String rawSpecification = reportIterator.next();

        // The report name should be the first token
        if (isFirst) {
            isFirst = false;/*from w w w.  j a v a  2 s  . c om*/

            // Extract the alias, if present: payments_per_day(Currency report)
            final Matcher matcher = LEGEND_PATTERN.matcher(rawSpecification);
            if (!matcher.find()) {
                reportName = rawSpecification;
                legend = null;
            } else {
                reportName = matcher.group(1);
                legend = Strings.emptyToNull(matcher.group(3));
            }

            continue;
        }

        final List<String> specification = ImmutableList
                .<String>copyOf(REPORT_SPECIFICATION_SPLITTER.split(rawSpecification).iterator());
        if (specification.size() != 2) {
            // Be lenient
            continue;
        }
        final String keywordString = specification.get(0);
        final String value = specification.get(1);

        final ValidKeywords keyword;
        try {
            keyword = ValidKeywords.valueOf(keywordString.toUpperCase());
        } catch (final IllegalArgumentException e) {
            // Be lenient
            continue;
        }

        switch (keyword) {
        case DIMENSION:
            dimensions.add(REPORT_GROUPING_SPECIFICATION_SPLITTER.split(value).iterator().next());
            // value is something like: currency(USD|EUR)
            dimensionsWithGrouping.add(value);
            break;
        case METRIC:
            metrics.add(value);
            break;
        case FILTER:
            // value is something like: (currency=USD&state!=ERRORED)|(currency=EUR&currency=PROCESSED)
            final Expression<String> thisFilterExpression = FilterExpressionParser.parse(value);
            if (filterExpression == null) {
                filterExpression = thisFilterExpression;
            } else {
                // Multiple filter expressions are OR'ed by default
                filterExpression = Or.of(filterExpression, thisFilterExpression);
            }
            break;
        }
    }
}

From source file:org.impressivecode.depress.scm.git.GitOfflineAdapterNodeModel.java

@Override
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec)
        throws Exception {

    try {//www.ja  va  2  s  .co  m
        logger.info("Reading git logs from file " + this.gitFileName.getStringValue());
        ArrayList<String> userExtensions = SCMExtensionsParser.parseExtensions(extensions.getStringValue());
        String packageNameToFilter = Strings.emptyToNull(gitPackageName.getStringValue());
        SCMParserOptions parserOptions = options(packageNameToFilter, userExtensions);
        GitOfflineLogParser parser = new GitOfflineLogParser(parserOptions);
        List<GitCommit> commits = parser.parseEntries(this.gitFileName.getStringValue());
        logger.info("Reading git logs finished");
        BufferedDataTable out = transform(commits, exec);
        logger.info("Transforming git logs finished.");
        return new BufferedDataTable[] { out };
    } catch (Exception ex) {
        logger.error("Unable to parse git entries", ex);
        throw ex;
    }
}

From source file:com.google.api.explorer.client.base.ApiRequest.java

/**
 * Add the trace parameter to requests when it has been specified by the user.
 *//*from w ww.  j ava 2  s.co m*/
@VisibleForTesting
void maybeSetTraceParameter() {
    String traceParameter = Config.getTraceParameter();
    if (Strings.emptyToNull(traceParameter) != null) {
        setTraceParameter(traceParameter);
    }
}

From source file:eu.arkitech.logback.common.RandomGenerator.java

public Logger resolveLogger() {
    final Logger configuredLogger = this.logger;
    final String configuredLoggerName = Strings.emptyToNull(this.loggerName);
    final Logger logger;
    if (configuredLogger != null)
        logger = configuredLogger;/*from ww w . j  a  v  a2  s  .  c  o m*/
    else if (configuredLoggerName != null)
        logger = (Logger) LoggerFactory.getLogger(configuredLoggerName);
    else
        logger = (Logger) LoggerFactory.getLogger(RandomGenerator.class);
    if (logger == null)
        throw (new IllegalStateException());
    return (logger);
}

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

@Override
public String getUsageName() {
    return MoreObjects.firstNonNull(Strings.emptyToNull(translator.get(item.getUsageName())),
            Strings.nullToEmpty(item.getUsageName()));
}

From source file:org.sonar.plugins.issuesdensity.batch.WeightedIssuesDecorator.java

@Override
public void decorate(Resource resource, DecoratorContext context) {
    double value = 0.0;
    Multiset<String> distribution = LinkedHashMultiset.create();

    for (String severity : Severity.ALL) {
        Measure measure = context.getMeasure(severityToIssueMetric(severity));
        if (measure != null && MeasureUtils.hasValue(measure)) {
            distribution.add(severity, measure.getIntValue());
            double add = weightsBySeverity.get(severity) * measure.getIntValue();
            value += add;//from w w  w .  j a  v  a  2s . c  o  m
        }
    }

    String distributionFormatted = KeyValueFormat.format(distribution);
    // SONAR-4987 We should store an empty string for the distribution value
    Measure measure = new Measure(IssuesDensityMetrics.WEIGHTED_ISSUES, value,
            Strings.emptyToNull(distributionFormatted));
    context.saveMeasure(measure);
}

From source file:org.killbill.commons.skeleton.modules.JerseyBaseServerModule.java

public JerseyBaseServerModule(
        final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filters,
        final Map<String, ArrayList<Entry<Class<? extends Filter>, Map<String, String>>>> filtersRegex,
        final Map<String, Class<? extends HttpServlet>> servlets,
        final Map<String, Class<? extends HttpServlet>> servletsRegex,
        final Map<String, Class<? extends HttpServlet>> jaxrsServlets,
        final Map<String, Class<? extends HttpServlet>> jaxrsServletsRegex, final String jaxrsUriPattern,
        final Collection<String> jaxrsResources, final List<String> jerseyFilters,
        final Map<String, String> jerseyParams) {
    super(filters, filtersRegex, servlets, servletsRegex, jaxrsServlets, jaxrsServletsRegex, jaxrsUriPattern,
            jaxrsResources);//from  w ww . j ava  2s  .com

    String manuallySpecifiedRequestFilters = Strings
            .nullToEmpty(jerseyParams.remove(JERSEY_CONTAINER_REQUEST_FILTERS));
    String manuallySpecifiedResponseFilters = Strings
            .nullToEmpty(jerseyParams.remove(JERSEY_CONTAINER_RESPONSE_FILTERS));
    if (!jerseyFilters.isEmpty()) {
        if (!manuallySpecifiedRequestFilters.isEmpty()) {
            manuallySpecifiedRequestFilters += ";";
        }
        if (!manuallySpecifiedResponseFilters.isEmpty()) {
            manuallySpecifiedResponseFilters += ";";
        }
    }
    final String containerRequestFilters = manuallySpecifiedRequestFilters + joiner.join(jerseyFilters);
    final String containerResponseFilters = manuallySpecifiedResponseFilters
            + joiner.join(Lists.reverse(jerseyFilters));

    this.jerseyParams = new ImmutableMap.Builder<String, String>();
    if (!containerRequestFilters.isEmpty()) {
        this.jerseyParams.put(JERSEY_CONTAINER_REQUEST_FILTERS, containerRequestFilters);
    }
    if (!containerResponseFilters.isEmpty()) {
        this.jerseyParams.put(JERSEY_CONTAINER_RESPONSE_FILTERS, containerResponseFilters);
    }

    // The LoggingFilter will log the body by default, which breaks StreamingOutput
    final String disableEntityLogging = Objects
            .firstNonNull(Strings.emptyToNull(jerseyParams.remove(JERSEY_DISABLE_ENTITYLOGGING)), "true");
    this.jerseyParams.put(JERSEY_DISABLE_ENTITYLOGGING, disableEntityLogging).putAll(jerseyParams);
}