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.attribyte.api.pubsub.impl.server.NotificationMetricsServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String joinString = Strings.nullToEmpty(request.getParameter("joinWith")).trim();
    if (joinString.isEmpty())
        joinString = "_";
    boolean allowSlashInPrefix = true;
    if (request.getParameter("allowSlash") != null) {
        allowSlashInPrefix = request.getParameter("allowSlash").trim().equalsIgnoreCase("true");
    }/*from www  . j av a 2  s. c  o  m*/

    List<String> path = splitPath(request);
    String obj = path.size() > 0 ? path.get(0) : null;
    String[] topics = request.getParameterValues("name");

    if (obj == null) {
        MetricRegistry registry = new MetricRegistry();
        registry.register("", endpoint.getGlobalNotificationMetrics());

        String json = mapper.writer().writeValueAsString(registry);
        response.setContentType("application/json");
        response.getWriter().print(json);
        response.getWriter().flush();
    } else if (obj.equals("topic")) {
        final List<NotificationMetrics> metrics;
        if (topics != null && topics.length > 0) {
            metrics = Lists.newArrayListWithExpectedSize(topics.length);
            for (String topicName : topics) {
                Topic topic = resolveTopic(topicName);
                if (topic != null) {
                    NotificationMetrics topicMetrics = endpoint.getNotificationMetrics(topic.getId());
                    if (topicMetrics != null)
                        metrics.add(topicMetrics);
                }
            }
        } else {
            String sortStr = request.getParameter("sort");
            if (sortStr == null)
                sortStr = "";
            NotificationMetrics.Sort sort = sortMap.get(sortStr);
            if (sort == null)
                sort = NotificationMetrics.Sort.THROUGHPUT_DESC;
            String limitStr = request.getParameter("limit");
            int limit = 25;
            if (limitStr != null) {
                try {
                    limit = Integer.parseInt(limitStr);
                } catch (NumberFormatException nfe) {
                    limit = 25;
                }
            }
            metrics = endpoint.getNotificationMetrics(sort, limit);
        }

        MetricRegistry registry = new MetricRegistry();
        for (NotificationMetrics callbackMetrics : metrics) {
            String prefix = getTopicPrefix(callbackMetrics.topicId, joinString, allowSlashInPrefix);
            if (prefix != null) {
                registry.register(prefix, callbackMetrics);
            }
        }

        String json = mapper.writer().writeValueAsString(registry);
        response.setContentType("application/json");
        response.getWriter().print(json);
        response.getWriter().flush();
    } else {
        response.sendError(404);
    }
}

From source file:de.gesundkrank.wikipedia.hadoop.WikiRevisionWritable.java

public String getComment() {
    return Strings.nullToEmpty(comment);
}

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

/**
 * Method used for storing a template file.
 *
 * @param context//from w  w w .  j a  v a2  s. c o m
 *        The context of the servlet calling the {@link TemplateManager} used to determine the
 *        path to store the file.
 * @param stream
 *        The inputs stream from which the template to be store is read.
 * @param name
 *        The name of the template to store. The template will be stored as:
 *        [subFolder]/name.xml
 * @param subFolder
 *        The sub-folder from the template directory defined in the properties, to store the
 *        template file in. If you specify a subFolder you need to provide a trailing slash.
 * @throws IOException
 *         If an I/O error occurs while reading from the stream.
 * @throws UnsupportedEncodingException
 *         If the encoding of the stream is not supported.
 */
public static void store(final ServletContext context, final InputStream stream, final String name,
        @Nullable final String subFolder) throws UnsupportedEncodingException, IOException {
    final File template = new File(context.getRealPath("/"), Strings.nullToEmpty(subFolder) + name + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
    if (!template.exists()) {
        template.getParentFile().mkdirs();
        template.createNewFile();
    }

    try (PrintWriter writer = new PrintWriter(
            new OutputStreamWriter(new FileOutputStream(template), "UTF-8"))) { //$NON-NLS-1$
        final String stringFromStream = CharStreams.toString(new InputStreamReader(stream, "UTF-8")); //$NON-NLS-1$
        writer.println(stringFromStream);
    }
}

From source file:com.googlecode.android_scripting.ConvertUtils.java

/**
 * Returns toString() or an empty string if {@code obj} or result is null.
 * @param obj The object to call toString() on.
 * @param <T> The type of the object.
 * @return A string guaranteed not to be null.
 *//*from www.ja  v  a  2  s . co m*/
public static <T> String toNonNullString(T obj) {
    if (obj == null) {
        return "";
    } else {
        return Strings.nullToEmpty(obj.toString());
    }
}

From source file:org.splevo.diffing.util.NormalizationUtil.java

/**
 * Load the remove normalization pattern configuration from a provided configuration string.
 *
 * @param configString//from   ww w  .  j  ava 2s.  c  om
 *            The configuration string containing the normalization definitions.
 * @param suffix
 *            The (file extension) suffix to be ignored and preserved by the normalization.
 * @return The prepared normalization pattern map.
 */
public static LinkedHashMap<Pattern, String> loadRemoveNormalizations(String configString, String suffix) {

    suffix = Strings.nullToEmpty(suffix);
    configString = Strings.nullToEmpty(configString);

    LinkedHashMap<Pattern, String> normalizations = Maps.newLinkedHashMap();
    Iterable<String> entries = Splitter.on(LINE_SEPARATOR).omitEmptyStrings().trimResults().split(configString);
    for (String entry : entries) {
        if (entry.startsWith("*")) {
            String patternString = "(.*)" + entry.substring(1) + suffix;
            Pattern pattern = Pattern.compile(patternString);
            normalizations.put(pattern, "$1" + suffix);
        } else if (entry.endsWith("*")) {
            String patternString = entry.substring(0, entry.length()) + "(.*)" + suffix;
            Pattern pattern = Pattern.compile(patternString);
            normalizations.put(pattern, "$1" + suffix);
        } else {
            logger.warn("Classifier normalization config without * wildcard: " + entry);
            continue;
        }
    }
    return normalizations;
}

From source file:com.indeed.imhotep.metadata.MetricMetadata.java

public void toJSON(ObjectNode jsonNode) {
    jsonNode.put("name", getName());
    final String description = Strings.nullToEmpty(getDescription());
    jsonNode.put("description", description);
    String unit = getUnit();/*from   w w  w  .j ava2 s . c o m*/
    if (unit != null) {
        jsonNode.put("unit", unit);
    }
    final String expression = getExpression();
    if (expression != null) {
        jsonNode.put("expression", expression);
    }
}

From source file:org.gradle.api.publish.ivy.internal.artifact.AbstractIvyArtifact.java

@Override
public void setExtension(String extension) {
    this.extension = Strings.nullToEmpty(extension);
}

From source file:com.android.tools.idea.ui.TooltipLabel.java

public TooltipLabel() {
    final PropertyChangeListener focusListener = new PropertyChangeListener() {
        @Override/*from   ww w .  j a v a  2  s. c om*/
        public void propertyChange(PropertyChangeEvent evt) {
            if ((evt.getNewValue() instanceof Component)) {
                Component component = (Component) evt.getNewValue();
                TooltipLabel.super.setText(Strings.nullToEmpty(getTooltip(component)));
            }
        }
    };

    addHierarchyListener(new HierarchyListener() {
        @Override
        public void hierarchyChanged(HierarchyEvent e) {
            if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == 0) {
                return;
            }

            if (isShowing()) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager()
                        .addPropertyChangeListener(PROPERTY_FOCUS_OWNER, focusListener);
            } else {
                KeyboardFocusManager.getCurrentKeyboardFocusManager()
                        .removePropertyChangeListener(PROPERTY_FOCUS_OWNER, focusListener);
            }
        }
    });
}

From source file:org.richfaces.resource.mapping.ResourceServletMapping.java

static String getResourcePath(Resource resource) {
    final StringBuffer buffer = new StringBuffer();

    String ln = Strings.nullToEmpty(resource.getLibraryName());
    if (!ln.isEmpty()) {
        buffer.append(ln).append("/");
    }//w  w w  .jav  a  2 s.com

    buffer.append(resource.getResourceName());

    try {
        URI originalRequestPath = new URI("path://" + resource.getRequestPath());
        String query = originalRequestPath.getQuery();
        Matcher matcher = LN_PATTERN.matcher(query);
        if (matcher.matches()) {
            ln = matcher.group(2);
            query = matcher.replaceFirst("$1$3");
            matcher = AMP_CLEANUP_PATTERN.matcher(query);
            if (matcher.matches()) {
                query = matcher.replaceAll("$1$2$3");
            }
        }
        if (!query.isEmpty()) {
            buffer.append("?").append(query);
        }
        return buffer.toString();
    } catch (URISyntaxException e) {
        throw new IllegalStateException(String.format("Failed to parse requestPath '%s' for resource '%s': %s",
                resource.getRequestPath(), ResourceKey.create(resource), e.getMessage()), e);
    }
}

From source file:org.apache.sentry.policy.db.DBWildcardPermission.java

public DBWildcardPermission(String wildcardString) {
    wildcardString = Strings.nullToEmpty(wildcardString).trim();
    if (wildcardString.isEmpty()) {
        throw new IllegalArgumentException("Wildcard string cannot be null or empty.");
    }/*  w  w  w . j  a  va2 s .co  m*/
    List<KeyValue> parts = Lists.newArrayList();
    for (String authorizable : AUTHORIZABLE_SPLITTER.trimResults().split(wildcardString)) {
        if (authorizable.isEmpty()) {
            throw new IllegalArgumentException("Privilege '" + wildcardString + "' has an empty section");
        }
        parts.add(new KeyValue(authorizable));
    }
    if (parts.isEmpty()) {
        throw new AssertionError("Should never occur: " + wildcardString);
    }
    this.parts = ImmutableList.copyOf(parts);
}