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:com.google.devtools.build.xcode.plmerge.PlMerge.java

public static void main(String[] args) throws OptionsParsingException, IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    OptionsParser parser = OptionsParser.newOptionsParser(PlMergeOptions.class);
    parser.parse(args);//from ww  w .ja  v a  2  s . c om
    PlMergeOptions options = parser.getOptions(PlMergeOptions.class);

    if (options.controlPath == null) {
        missingArg("control");
    }

    InputStream in = Files.newInputStream(fileSystem.getPath(options.controlPath));
    Control control = Control.parseFrom(in);
    validateControl(control);

    PlistMerging merging = PlistMerging.from(control,
            new KeysToRemoveIfEmptyString("CFBundleIconFile", "NSPrincipalClass"));

    String primaryBundleId = Strings.emptyToNull(control.getPrimaryBundleId());
    String fallbackBundleId = Strings.emptyToNull(control.getFallbackBundleId());

    if (primaryBundleId != null || fallbackBundleId != null) {
        // Only set the bundle identifier if we were passed arguments to do so.
        // This prevents CFBundleIdentifiers being put into strings files.
        merging.setBundleIdentifier(primaryBundleId, fallbackBundleId);
    }

    Path outputPath = fileSystem.getPath(control.getOutFile());
    switch (control.getOutputFormat()) {
    case BINARY:
        merging.writePlist(outputPath);
        break;
    case XML:
        merging.writeXmlPlist(outputPath);
        break;
    default:
        throw new IllegalArgumentException(
                String.format("Unknown output format in the control file: %s", control.getOutputFormat()));
    }
}

From source file:org.attribyte.api.pubsub.impl.server.Server.java

/**
 * Starts the server./*  w ww. j a v a  2  s.  c o  m*/
 * @param args The startup args.
 * @throws Exception on startup error.
 */
public static void main(String[] args) throws Exception {

    if (args.length < 1) {
        System.err.println("Start-up error: Expecting <config file> [allowed topics file]");
        System.exit(1);
    }

    Properties commandLineOverrides = new Properties();
    args = InitUtil.fromCommandLine(args, commandLineOverrides);

    Properties props = new Properties();
    Properties logProps = new Properties();
    CLI.loadProperties(args, props, logProps);

    props.putAll(commandLineOverrides);
    logProps.putAll(commandLineOverrides);

    final Logger logger = initLogger(props, logProps);

    logger.info("Applied command line overrides: " + commandLineOverrides.toString());

    //Buffer and log hub events for logging and debug...

    final int MAX_STORED_SUBSCRIPTION_REQUESTS = 200;

    final ArrayBlockingQueue<SubscriptionEvent> recentSubscriptionRequests = new ArrayBlockingQueue<>(
            MAX_STORED_SUBSCRIPTION_REQUESTS);

    final HubEndpoint.EventHandler hubEventHandler = new HubEndpoint.EventHandler() {
        private synchronized void offer(SubscriptionEvent record) {
            if (!recentSubscriptionRequests.offer(record)) {
                List<SubscriptionEvent> drain = Lists
                        .newArrayListWithCapacity(MAX_STORED_SUBSCRIPTION_REQUESTS / 2);
                recentSubscriptionRequests.drainTo(drain, drain.size());
                recentSubscriptionRequests.offer(record);
            }
        }

        @Override
        public void subscriptionRequestAccepted(final Request request, final Response response,
                final Subscriber subscriber) {
            final SubscriptionEvent record;
            try {
                record = new SubscriptionRequestRecord(request, response, subscriber);
            } catch (IOException ioe) {
                return;
            }

            logger.info(record.toString());
            offer(record);
        }

        @Override
        public void subscriptionRequestRejected(final Request request, final Response response,
                final Subscriber subscriber) {

            final SubscriptionEvent record;
            try {
                record = new SubscriptionRequestRecord(request, response, subscriber);
            } catch (IOException ioe) {
                return;
            }

            logger.warn(record.toString());
            offer(record);
        }

        @Override
        public void subscriptionVerifyFailure(String callbackURL, int callbackResponseCode, String reason,
                int attempts, boolean abandoned) {
            final SubscriptionEvent record = new SubscriptionVerifyRecord(callbackURL, callbackResponseCode,
                    reason, attempts, abandoned);
            logger.warn(record.toString());
            offer(record);
        }

        @Override
        public void subscriptionVerified(Subscription subscription) {
            final SubscriptionEvent record = new SubscriptionVerifyRecord(subscription);
            logger.info(record.toString());
            offer(record);
        }
    };

    /**
     * A source for subscription request records (for console, etc).
     */
    final SubscriptionEvent.Source subscriptionEventSource = new SubscriptionEvent.Source() {
        public List<SubscriptionEvent> latestEvents(int limit) {
            List<SubscriptionEvent> records = Lists.newArrayList(recentSubscriptionRequests);
            Collections.sort(records);
            return records.size() < limit ? records : records.subList(0, limit);
        }
    };

    /**
     * A queue to which new topics are added as reported by the datastore event handler.
     */
    final BlockingQueue<Topic> newTopicQueue = new LinkedBlockingDeque<>();

    /**
     * A datastore event handler that offers new topics to a queue.
     */
    final HubDatastore.EventHandler topicEventHandler = new HubDatastore.EventHandler() {

        @Override
        public void newTopic(final Topic topic) throws DatastoreException {
            newTopicQueue.offer(topic);
        }

        @Override
        public void newSubscription(final Subscription subscription) throws DatastoreException {
            //Ignore
        }

        @Override
        public void exception(final Throwable t) {
            //Ignore
        }

        @Override
        public void setNext(final HubDatastore.EventHandler next) {
            //Ignore
        }
    };

    final HubEndpoint endpoint = new HubEndpoint("endpoint.", props, logger, hubEventHandler,
            topicEventHandler);

    final String topicAddedTopicURL = Strings.emptyToNull(props.getProperty("endpoint.topicAddedTopic", ""));
    final Topic topicAddedTopic = topicAddedTopicURL != null
            ? endpoint.getDatastore().getTopic(topicAddedTopicURL, true)
            : null;
    final Thread topicAddedNotifier = topicAddedTopic != null
            ? new Thread(new TopicAddedNotifier(newTopicQueue, endpoint, topicAddedTopic))
            : null;
    if (topicAddedNotifier != null) {
        topicAddedNotifier.setName("topic-added-notifier");
        topicAddedNotifier.start();
    }

    if (props.getProperty("endpoint.topics") != null) { //Add supported topics...
        for (String topicURL : Splitter.on(",").omitEmptyStrings().trimResults()
                .split(props.getProperty("endpoint.topics"))) {
            Topic topic = endpoint.getDatastore().getTopic(topicURL, true);
            System.out.println("Added topic, '" + topicURL + "' (" + topic.getId() + ")");
        }
    }

    final MetricRegistry registry = props.getProperty("endpoint.instrumentJVM", "true").equalsIgnoreCase("true")
            ? instrumentJVM(new MetricRegistry())
            : new MetricRegistry();

    if (props.getProperty("endpoint.instrumentSystem", "true").equalsIgnoreCase("true")) {
        instrumentSystem(registry);
    }

    registry.registerAll(endpoint);

    final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); //TODO

    final Reporting reporting = new Reporting("metrics-reporting.", props, registry, null); //No filter...

    String httpAddress = props.getProperty("http.address", "127.0.0.1");
    int httpPort = Integer.parseInt(props.getProperty("http.port", "8086"));

    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server();

    server.addLifeCycleListener(new LifeCycle.Listener() {

        public void lifeCycleFailure(LifeCycle event, Throwable cause) {
            System.out.println("Failure " + cause.toString());
        }

        public void lifeCycleStarted(LifeCycle event) {
            System.out.println("Started...");
        }

        public void lifeCycleStarting(LifeCycle event) {
            System.out.println("Server Starting...");
        }

        public void lifeCycleStopped(LifeCycle event) {
            System.out.println("Server Stopped...");
        }

        public void lifeCycleStopping(LifeCycle event) {
            System.out.println("Shutting down metrics reporting...");
            reporting.stop();
            if (topicAddedNotifier != null) {
                System.out.println("Shutting down new topic notifier...");
                topicAddedNotifier.interrupt();
            }
            System.out.println("Shutting down endpoint...");
            endpoint.shutdown();
            System.out.println("Shutdown endpoint...");
        }
    });

    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);
    ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    httpConnector.setHost(httpAddress);
    httpConnector.setPort(httpPort);
    httpConnector.setIdleTimeout(30000L);
    server.addConnector(httpConnector);
    HandlerCollection serverHandlers = new HandlerCollection();
    server.setHandler(serverHandlers);

    ServletContextHandler rootContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    rootContext.setContextPath("/");

    final AdminConsole adminConsole;
    final List<String> allowedAssetPaths;

    if (props.getProperty("admin.enabled", "false").equalsIgnoreCase("true")) {

        File assetDirFile = getSystemFile("admin.assetDirectory", props);

        if (assetDirFile == null) {
            System.err.println("The 'admin.assetDirectory' must be configured");
            System.exit(1);
        }

        if (!assetDirFile.exists()) {
            System.err.println("The 'admin.assetDirectory'" + assetDirFile.getAbsolutePath() + "' must exist");
            System.exit(1);
        }

        if (!assetDirFile.isDirectory()) {
            System.err.println(
                    "The 'admin.assetDirectory'" + assetDirFile.getAbsolutePath() + "' must be a directory");
            System.exit(1);
        }

        if (!assetDirFile.canRead()) {
            System.err.println(
                    "The 'admin.assetDirectory'" + assetDirFile.getAbsolutePath() + "' must be readable");
            System.exit(1);
        }

        char[] adminUsername = props.getProperty("admin.username", "").toCharArray();
        char[] adminPassword = props.getProperty("admin.password", "").toCharArray();
        String adminRealm = props.getProperty("admin.realm", "pubsubhub");

        if (adminUsername.length == 0 || adminPassword.length == 0) {
            System.err.println("The 'admin.username' and 'admin.password' must be specified");
            System.exit(1);
        }

        File templateDirFile = getSystemFile("admin.templateDirectory", props);

        if (templateDirFile == null) {
            System.err.println("The 'admin.templateDirectory' must be specified");
            System.exit(1);
        }

        if (!templateDirFile.exists()) {
            System.err
                    .println("The 'admin.templateDirectory'" + assetDirFile.getAbsolutePath() + "' must exist");
            System.exit(1);
        }

        if (!templateDirFile.isDirectory()) {
            System.err.println(
                    "The 'admin.templateDirectory'" + assetDirFile.getAbsolutePath() + "' must be a directory");
            System.exit(1);
        }

        if (!templateDirFile.canRead()) {
            System.err.println(
                    "The 'admin.templateDirectory'" + assetDirFile.getAbsolutePath() + "' must be readable");
            System.exit(1);
        }

        adminConsole = new AdminConsole(rootContext, assetDirFile.getAbsolutePath(), endpoint,
                new AdminAuth(adminRealm, adminUsername, adminPassword), templateDirFile.getAbsolutePath(),
                logger);

        allowedAssetPaths = Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults()
                .split(props.getProperty("admin.assetPaths", "")));
        System.out.println("Admin console is enabled...");
    } else {
        adminConsole = null;
        allowedAssetPaths = ImmutableList.of();
    }

    serverHandlers.addHandler(rootContext);

    //TODO: Introduces incompatible dependency...
    /*
    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(registry);
    instrumentedHandler.setName("http-server");
    instrumentedHandler.setHandler(rootContext);
    serverHandlers.addHandler(instrumentedHandler);
    */

    File requestLogPathFile = getSystemFile("http.log.path", props);
    if (requestLogPathFile != null) {

        if (!requestLogPathFile.exists()) {
            System.err
                    .println("The 'http.log.path', '" + requestLogPathFile.getAbsolutePath() + "' must exist");
            System.exit(1);
        }

        if (!requestLogPathFile.isDirectory()) {
            System.err.println(
                    "The 'http.log.path', '" + requestLogPathFile.getAbsolutePath() + "' must be a directory");
            System.exit(1);
        }

        if (!requestLogPathFile.canWrite()) {
            System.err.println(
                    "The 'http.log.path', '" + requestLogPathFile.getAbsolutePath() + "' is not writable");
            System.exit(1);
        }

        int requestLogRetainDays = Integer.parseInt(props.getProperty("http.log.retainDays", "14"));
        boolean requestLogExtendedFormat = props.getProperty("http.log.extendedFormat", "true")
                .equalsIgnoreCase("true");
        String requestLogTimeZone = props.getProperty("http.log.timeZone", TimeZone.getDefault().getID());
        String requestLogPrefix = props.getProperty("http.log.prefix", "requests");
        String requestLogPath = requestLogPathFile.getAbsolutePath();
        if (!requestLogPath.endsWith("/")) {
            requestLogPath = requestLogPath + "/";
        }

        NCSARequestLog requestLog = new NCSARequestLog(requestLogPath + requestLogPrefix + "-yyyy_mm_dd.log");
        requestLog.setRetainDays(requestLogRetainDays);
        requestLog.setAppend(true);
        requestLog.setExtended(requestLogExtendedFormat);
        requestLog.setLogTimeZone(requestLogTimeZone);
        requestLog.setLogCookies(false);
        requestLog.setPreferProxiedForAddress(true);

        RequestLogHandler requestLogHandler = new RequestLogHandler();
        requestLogHandler.setRequestLog(requestLog);
        serverHandlers.addHandler(requestLogHandler);
    }

    HubServlet hubServlet = new HubServlet(endpoint, logger);
    rootContext.addServlet(new ServletHolder(hubServlet), "/subscribe/*");

    InitUtil filterInit = new InitUtil("publish.", props);
    List<BasicAuthFilter> publishURLFilters = Lists.newArrayList();
    List<Object> publishURLFilterObjects = filterInit.initClassList("topicURLFilters", BasicAuthFilter.class);
    for (Object o : publishURLFilterObjects) {
        BasicAuthFilter filter = (BasicAuthFilter) o;
        filter.init(filterInit.getProperties());
        publishURLFilters.add(filter);
    }

    final long topicCacheMaxAgeSeconds = Long
            .parseLong(props.getProperty("endpoint.topicCache.maxAgeSeconds", "0"));
    final Cache<String, Topic> topicCache;
    if (topicCacheMaxAgeSeconds > 0) {
        topicCache = CacheBuilder.newBuilder().concurrencyLevel(16)
                .expireAfterWrite(topicCacheMaxAgeSeconds, TimeUnit.SECONDS).maximumSize(4096).build();
    } else {
        topicCache = null;
    }

    final String replicationTopicURL = Strings.emptyToNull(props.getProperty("endpoint.replicationTopic", ""));
    //Get or create replication topic, if configured.
    final Topic replicationTopic = replicationTopicURL != null
            ? endpoint.getDatastore().getTopic(replicationTopicURL, true)
            : null;

    int maxBodySizeBytes = filterInit.getIntProperty("maxBodySizeBytes",
            BroadcastServlet.DEFAULT_MAX_BODY_BYTES);
    boolean autocreateTopics = filterInit.getProperty("autocreateTopics", "false").equalsIgnoreCase("true");

    int maxSavedNotifications = filterInit.getIntProperty("maxSavedNotifications", 0);

    boolean jsonEnabled = filterInit.getProperty("jsonEnabled", "false").equalsIgnoreCase("true");

    final BroadcastServlet broadcastServlet = new BroadcastServlet(endpoint, maxBodySizeBytes, autocreateTopics,
            logger, publishURLFilters, topicCache, replicationTopic, maxSavedNotifications, jsonEnabled);
    rootContext.addServlet(new ServletHolder(broadcastServlet), "/notify/*");

    CallbackMetricsServlet callbackMetricsServlet = new CallbackMetricsServlet(endpoint);
    ServletHolder callbackMetricsServletHolder = new ServletHolder(callbackMetricsServlet);
    rootContext.addServlet(callbackMetricsServletHolder, "/metrics/callback/*");

    NotificationMetricsServlet notificationMetricsServlet = new NotificationMetricsServlet(endpoint);
    ServletHolder notificationMetricsServletHolder = new ServletHolder(notificationMetricsServlet);
    rootContext.addServlet(notificationMetricsServletHolder, "/metrics/notification/*");

    MetricsServlet metricsServlet = new MetricsServlet(registry);
    ServletHolder metricsServletHolder = new ServletHolder(metricsServlet);
    rootContext.setInitParameter(MetricsServlet.RATE_UNIT, "SECONDS");
    rootContext.setInitParameter(MetricsServlet.DURATION_UNIT, "MILLISECONDS");
    rootContext.setInitParameter(MetricsServlet.SHOW_SAMPLES, "false");
    rootContext.addServlet(metricsServletHolder, "/metrics/*");

    boolean outputHostAddys = props.getProperty("ping.outputHostAddresses", "false").equalsIgnoreCase("true");
    PingServlet pingServlet = new PingServlet(props.getProperty("http.instanceName", ""), outputHostAddys);
    rootContext.addServlet(new ServletHolder(pingServlet), "/ping/*");

    HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry);
    for (Map.Entry<String, HealthCheck> healthCheck : endpoint.getDatastore().getHealthChecks().entrySet()) {
        healthCheckRegistry.register(healthCheck.getKey(), healthCheck.getValue());
    }
    healthCheckRegistry.register("no-deadlocked-threads", new ThreadDeadlockHealthCheck());

    rootContext.addServlet(new ServletHolder(healthCheckServlet), "/health/*");

    ThreadDumpServlet threadDumpServlet = new ThreadDumpServlet();
    rootContext.addServlet(new ServletHolder(threadDumpServlet), "/threads/*");

    if (adminConsole != null && allowedAssetPaths.size() > 0) {
        String adminPath = props.getProperty("admin.path", "/admin/");
        List<Invalidatable> invalidatables = Collections.<Invalidatable>singletonList(new Invalidatable() {
            @Override
            public void invalidate() {
                broadcastServlet.invalidateCaches();
                if (topicCache != null) {
                    topicCache.invalidateAll();
                }
            }
        });
        adminConsole.initServlets(rootContext, adminPath, allowedAssetPaths, invalidatables,
                subscriptionEventSource, broadcastServlet);
    }

    int numReporters = reporting.start();
    logger.info("Started " + numReporters + " metrics reporters");

    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.start();
    server.join();
}

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

public static GitParserOptions options(final String packageString,
        final ArrayList<String> extensionsNamesToFilter, final String branch) {
    GitParserOptions options = new GitParserOptions();
    options.packageString = Strings.emptyToNull(packageString);
    options.extensionsNamesToFilter = extensionsNamesToFilter;
    options.branch = Strings.emptyToNull(branch);
    return options;
}

From source file:org.teknux.dropbitz.util.I18nUtil.java

public static Locale getLocaleFromString(String name) throws I18nServiceException {
    String parts[] = Objects.requireNonNull(Strings.emptyToNull(name), "Name can not be null or empty")
            .split(LOCALE_STRING_SEPARATOR);
    Locale locale = null;/*from  w w  w  . ja  v  a 2 s. c  om*/
    switch (parts.length) {
    case 1:
        locale = new Locale(name);
        break;
    case 2:
        locale = new Locale(parts[0], parts[1]);
        break;
    case 3:
        locale = new Locale(parts[0], parts[1], parts[2]);
        break;
    default:
        throw new I18nServiceException("Bad Lang format");
    }

    try {
        //Check validity
        locale.getISO3Language();
        locale.getISO3Country();

        return locale;
    } catch (MissingResourceException e) {
        throw new I18nServiceException(e);
    }
}

From source file:org.killbill.CreatorName.java

public static String get() {
    if (creatorName == null) {
        synchronized (CreatorName.class) {
            String tmpCreatorName = System.getProperty(QUEUE_CREATOR_NAME);
            if (Strings.emptyToNull(tmpCreatorName) == null) {
                try {
                    final InetAddress addr = InetAddress.getLocalHost();
                    tmpCreatorName = addr.getHostName();
                } catch (final UnknownHostException e) {
                    tmpCreatorName = "creatorName-unknown";
                }/*from  w  ww  .  j a  va 2s.com*/
            }
            creatorName = tmpCreatorName.length() > 45 ? tmpCreatorName.substring(0, 45) : tmpCreatorName;
        }
    }
    return creatorName;
}

From source file:com.google.gitiles.doc.MarkdownUtil.java

/** Combine child nodes as string; this must be escaped for HTML. */
static String getInnerText(Node node) {
    if (node == null || node.getChildren().isEmpty()) {
        return null;
    }/*ww  w.  ja v  a2  s .  c  o  m*/

    StringBuilder b = new StringBuilder();
    appendTextFromChildren(b, node);
    return Strings.emptyToNull(b.toString().trim());
}

From source file:org.apache.isis.core.metamodel.facets.members.hidden.HiddenFacetFromLayoutPropertiesAbstract.java

protected static Where hidden(final Properties properties) {
    if (properties == null) {
        return null;
    }/* ww  w  . j  a v  a2  s .c  om*/
    final String hidden = Strings.emptyToNull(properties.getProperty("hidden"));
    if (hidden == null) {
        return null;
    }
    return Where.valueOf(hidden);
}

From source file:org.apache.isis.core.metamodel.facets.actions.layout.NamedFacetForActionLayoutAnnotation.java

public static NamedFacet create(final ActionLayout actionLayout, final FacetHolder holder) {
    if (actionLayout == null) {
        return null;
    }/*from   w  w  w .  j  ava  2s  . c o m*/
    final String named = Strings.emptyToNull(actionLayout.named());
    return named != null ? new NamedFacetForActionLayoutAnnotation(named, holder) : null;
}

From source file:org.apache.isis.core.metamodel.facets.actions.layout.NamedFacetForActionXml.java

public static NamedFacet create(final ActionLayoutData actionLayout, final FacetHolder holder) {
    if (actionLayout == null) {
        return null;
    }//  ww  w .  j a  va2  s  . c om
    final String named = Strings.emptyToNull(actionLayout.getNamed());
    Boolean escaped = actionLayout.getNamedEscaped();
    return named != null ? new NamedFacetForActionXml(named, (escaped == null || escaped), holder) : null;
}

From source file:org.apache.isis.core.metamodel.facets.properties.layout.NamedFacetForPropertyLayoutAnnotation.java

public static NamedFacet create(PropertyLayout propertyLayout, FacetHolder holder) {
    if (propertyLayout == null) {
        return null;
    }/*www . j av a 2  s .c  om*/
    final String named = Strings.emptyToNull(propertyLayout.named());
    return named != null
            ? new NamedFacetForPropertyLayoutAnnotation(named, propertyLayout.namedEscaped(), holder)
            : null;
}