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.lendingclub.mercator.demo.Main.java

public static void main(String[] args) {
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();//from  w  w w  .  j  a va  2  s .c  o m
    Projector projector = new Projector.Builder().build();

    Runnable awsTask = new Runnable() {

        public void run() {
            try {
                List<String> regionList = Splitter.on(",").omitEmptyStrings().trimResults()
                        .splitToList(Strings.nullToEmpty(System.getenv("AWS_REGIONS")));

                if (regionList == null || regionList.isEmpty()) {
                    regionList = Lists.newArrayList();
                    regionList.add("us-west-2");
                    regionList.add("us-east-1");
                }
                LoggerFactory.getLogger(Main.class).info("scanning regions: {}", regionList);
                regionList.forEach(it -> {
                    try {
                        org.slf4j.LoggerFactory.getLogger(Main.class).info("scanning region: {}", it);
                        Regions region = Regions.fromName(it);
                        projector.createBuilder(AWSScannerBuilder.class).withRegion(region)
                                .build(AllEntityScanner.class).scan();
                    } catch (Exception e) {
                        LoggerFactory.getLogger(Main.class).warn("problem scanning " + it, e);
                    }
                });
            } catch (Exception e) {
                LoggerFactory.getLogger(Main.class).warn("problem", e);
            }
        }

    };

    Runnable dockerTask = new Runnable() {
        public void run() {

            projector.createBuilder(DockerScannerBuilder.class).withLocalDockerDaemon().build().scan();
        }
    };

    ScheduledExecutorService exec = Executors.newScheduledThreadPool(5);
    exec.scheduleWithFixedDelay(awsTask, 0, 1, TimeUnit.MINUTES);
    exec.scheduleWithFixedDelay(dockerTask, 0, 10, TimeUnit.SECONDS);

    while (true == true) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
    }
}

From source file:com.google.devtools.build.android.LibraryRClassGeneratorAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);
    logger.fine(String.format("Option parsing finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_generated")) {
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter.createWith(
                aaptConfigOptions.androidJar, scopedTmp.getPath(), Strings.nullToEmpty(options.packageForR));
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);
        final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        final ParsedAndroidData data = resourceProcessor.deserializeSymbolsToData(options.symbols);
        logger.fine(String.format("Deserialization finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        data.writeResourcesTo(resourceClassWriter);
        resourceClassWriter.flush();//from   w w  w .ja v  a 2 s  . co m
        logger.fine(String.format("R writing finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        resourceProcessor.createClassJar(scopedTmp.getPath(), options.classJarOutput);
        logger.fine(String.format("Creating class jar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (IOException | MergingException | DeserializationException e) {
        logger.log(Level.SEVERE, "Errors during R generation.", e);
        throw e;
    }
}

From source file:com.google.devtools.build.android.AndroidCompiledResourceMergingAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.enableParamsFileSupport(new ShellQuotedParamsFilePreProcessor(FileSystems.getDefault()));
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.primaryManifest);
    Preconditions.checkNotNull(options.manifestOutput);
    Preconditions.checkNotNull(options.classJarOutput);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp");
            ExecutorServiceCloser executorService = ExecutorServiceCloser.createWithFixedPoolOf(15)) {
        Path tmp = scopedTmp.getPath();
        Path generatedSources = tmp.resolve("generated_resources");
        Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml");

        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        String packageForR = options.packageForR;
        if (packageForR == null) {
            packageForR = Strings
                    .nullToEmpty(VariantConfiguration.getManifestPackage(options.primaryManifest.toFile()));
        }/*  w  w w.  j  av a  2 s .c o  m*/
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter
                .createWith(aaptConfigOptions.androidJar, generatedSources, packageForR);
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);

        AndroidResourceMerger.mergeCompiledData(options.primaryData, options.primaryManifest,
                options.directData, options.transitiveData, resourceClassWriter,
                options.throwOnResourceConflict, executorService);
        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        AndroidResourceOutputs.createClassJar(generatedSources, options.classJarOutput, options.targetLabel,
                options.injectingRuleKind);
        logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        // Until enough users with manifest placeholders migrate to the new manifest merger,
        // we need to replace ${applicationId} and ${packageName} with options.packageForR to make
        // the manifests compatible with the old manifest merger.
        processedManifest = AndroidManifestProcessor.with(stdLogger).processLibraryManifest(options.packageForR,
                options.primaryManifest, processedManifest);

        Files.createDirectories(options.manifestOutput.getParent());
        Files.copy(processedManifest, options.manifestOutput);
    } catch (MergeConflictException e) {
        logger.log(Level.SEVERE, e.getMessage());
        System.exit(1);
    } catch (MergingException e) {
        logger.log(Level.SEVERE, "Error during merging resources", e);
        throw e;
    } catch (AndroidManifestProcessor.ManifestProcessingException e) {
        System.exit(1);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected", e);
        throw e;
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:com.google.devtools.build.android.AndroidResourceMergingAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    AaptConfigOptions aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    Options options = optionsParser.getOptions(Options.class);

    final AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);

    Preconditions.checkNotNull(options.primaryData);
    Preconditions.checkNotNull(options.primaryManifest);
    Preconditions.checkNotNull(options.classJarOutput);

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("android_resource_merge_tmp")) {
        Path tmp = scopedTmp.getPath();
        Path mergedAssets = tmp.resolve("merged_assets");
        Path mergedResources = tmp.resolve("merged_resources");
        Path generatedSources = tmp.resolve("generated_resources");
        Path processedManifest = tmp.resolve("manifest-processed/AndroidManifest.xml");

        logger.fine(String.format("Setup finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        VariantType packageType = VariantType.LIBRARY;
        AndroidResourceClassWriter resourceClassWriter = AndroidResourceClassWriter.createWith(
                aaptConfigOptions.androidJar, generatedSources, Strings.nullToEmpty(options.packageForR));
        resourceClassWriter.setIncludeClassFile(true);
        resourceClassWriter.setIncludeJavaFile(false);

        final MergedAndroidData mergedData = resourceProcessor.mergeData(options.primaryData,
                options.primaryManifest, options.directData, options.transitiveData, mergedResources,
                mergedAssets, new StubPngCruncher(), packageType, options.symbolsBinOut, resourceClassWriter);

        logger.fine(String.format("Merging finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        // Until enough users with manifest placeholders migrate to the new manifest merger,
        // we need to replace ${applicationId} and ${packageName} with options.packageForR to make
        // the manifests compatible with the old manifest merger.
        if (options.manifestOutput != null) {
            MergedAndroidData processedData = resourceProcessor.processManifest(packageType,
                    options.packageForR, null, /* applicationId */
                    -1, /* versionCode */
                    null, /* versionName */
                    mergedData, processedManifest);
            resourceProcessor.copyManifestToOutput(processedData, options.manifestOutput);
        }/*from w w w .  java  2 s.  co m*/

        resourceProcessor.createClassJar(generatedSources, options.classJarOutput);

        logger.fine(String.format("Create classJar finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        if (options.resourcesOutput != null) {
            // For now, try compressing the library resources that we pass to the validator. This takes
            // extra CPU resources to pack and unpack (~2x), but can reduce the zip size (~4x).
            resourceProcessor.createResourcesZip(mergedData.getResourceDir(), mergedData.getAssetDir(),
                    options.resourcesOutput, true /* compress */);
            logger.fine(String.format("Create resources.zip finished at %sms",
                    timer.elapsed(TimeUnit.MILLISECONDS)));
        }
    } catch (MergingException e) {
        logger.log(Level.SEVERE, "Error during merging resources", e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Unexpected", e);
        throw e;
    } finally {
        resourceProcessor.shutdown();
    }
    logger.fine(String.format("Resources merged in %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:iterator.util.Platform.java

public static Platform getPlatform() {
    String osName = Strings.nullToEmpty(System.getProperty(OS_NAME_PROPERTY)).toUpperCase(Locale.UK)
            .replace(' ', '_');
    try {//from w w w. j  a  va  2s .  c om
        // TODO Check behaviour on Windows variants
        return Platform.valueOf(osName);
    } catch (IllegalArgumentException iee) {
        // TODO Add other operating systems
        return UNKNOWN;
    }
}

From source file:com.facebook.swift.thrift.generator.util.SwiftInternalStringUtils.java

public static boolean isBlank(final String str) {
    return CharMatcher.WHITESPACE.removeFrom(Strings.nullToEmpty(str)).length() == 0;
}

From source file:io.macgyver.core.util.HashUtils.java

public static String calculateCompositeId(String... args) {

    try {/* ww  w  .  j a v a 2 s.c o  m*/
        MessageDigest md = MessageDigest.getInstance("sha1");
        StringBuffer sb = new StringBuffer();
        for (String s : args) {
            sb.append("/");
            sb.append(Strings.nullToEmpty(s));

        }
        md.update(sb.toString().getBytes("UTF-8"));
        return BaseEncoding.base16().lowerCase().encode(md.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new MacGyverException(e);
    } catch (UnsupportedEncodingException e) {
        throw new MacGyverException(e);
    }

}

From source file:com.google.gitiles.PathUtil.java

static String simplifyPathUpToRoot(String path, String root) {
    if (path.startsWith("/")) {
        return null;
    }/*  w  w  w .ja  v a 2s  .  c  o  m*/

    root = Strings.nullToEmpty(root);
    // simplifyPath() normalizes "a/../../" to "a", so manually check whether
    // the path leads above the root.
    int depth = new StringTokenizer(root, "/").countTokens();
    for (String part : SPLITTER.split(path)) {
        if (part.equals("..")) {
            depth--;
            if (depth < 0) {
                return null;
            }
        } else if (!part.isEmpty() && !part.equals(".")) {
            depth++;
        }
    }

    String result = Files.simplifyPath(!root.isEmpty() ? root + "/" + path : path);
    return !result.equals(".") ? result : "";
}

From source file:com.streamsets.lib.security.http.SSOPrincipalUtils.java

public static String getClientIpAddress(HttpServletRequest request) {
    String xff = request.getHeader(CLIENT_IP_HEADER);

    List<String> ipList = xffSplitter.splitToList(Strings.nullToEmpty(xff));

    String ip;/*  ww  w.  java2s.c om*/
    if (ipList.size() == 0 || UNKNOWN_IP.equalsIgnoreCase(ipList.get(0))) {
        ip = request.getRemoteAddr();
        if (Strings.isNullOrEmpty(ip)) {
            ip = UNKNOWN_IP;
        }
    } else {
        ip = ipList.get(0);
    }
    return ip;
}

From source file:org.activityinfo.model.form.FormInstanceLabeler.java

public static String getLabel(FormInstance instance) {
    return Strings.nullToEmpty(instance.getString(getFormInstanceLabelCuid(instance)));
}