Example usage for org.apache.commons.lang StringUtils defaultString

List of usage examples for org.apache.commons.lang StringUtils defaultString

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultString.

Prototype

public static String defaultString(String str) 

Source Link

Document

Returns either the passed in String, or if the String is null, an empty String ("").

Usage

From source file:org.carewebframework.ui.ExceptionController.java

/**
 * Appends the stack trace for the specified exception to the display.
 * /*  ww w .  j a  v a2s .  co m*/
 * @param err Exception whose stack trace will be appended.
 */
private void appendStackTrace(final Throwable err) {
    if (err != null) {
        final Class<?> clazz = err.getClass();
        final String msg = err.getMessage();
        //final Throwable cause = err.getCause();//should be null

        this.txtStackTrace.setValue(StringUtils.defaultString(this.txtStackTrace.getValue())
                + StringUtils.trimToEmpty(clazz.getCanonicalName()) + ": " + StringUtils.trimToEmpty(msg)
                + "\n");

        for (final StackTraceElement element : err.getStackTrace()) {
            this.txtStackTrace.setValue(
                    StringUtils.defaultString(this.txtStackTrace.getValue()) + String.valueOf(element) + "\n");
        }
    }
}

From source file:org.carewebframework.ui.zk.AbstractRenderer.java

public String createLabelText(Object value, String prefix) {
    String text = StringUtils.trimToEmpty(value == null ? null
            : value instanceof Date ? DateUtil.formatDate((Date) value)
                    : value instanceof String ? StrUtil.formatMessage((String) value) : value.toString());
    return text.isEmpty() ? "" : StrUtil.formatMessage(StringUtils.defaultString(prefix)) + text;
}

From source file:org.cloudbees.literate.jenkins.LiterateBuilder.java

@DataBoundConstructor
public LiterateBuilder(String baseName, String environment) {
    this.baseName = Util.fixEmptyAndTrim(baseName);
    this.environment = new TreeSet<String>(
            Arrays.asList(StringUtils.split(StringUtils.defaultString(environment), ",")));
}

From source file:org.cobbler.CobblerObject.java

/**
 * @param keys the red hat activation keys in a set
 *//*from w  ww .java  2s  .com*/
public void setRedHatManagementKey(Set<String> keys) {
    modify(REDHAT_KEY, StringUtils.defaultString(StringUtil.join(",", keys)));
}

From source file:org.cobbler.CobblerObject.java

/**
 * get the redhate management key as a Set of keys
 * @return returns the red hat key as a string
 *///from  ww w. j  a va  2  s . com
public Set<String> getRedHatManagementKeySet() {
    String keys = StringUtils.defaultString(getRedHatManagementKey());
    String[] sets = (keys).split(",");
    Set set = new HashSet();
    set.addAll(Arrays.asList(sets));
    return set;
}

From source file:org.codehaus.grepo.statistics.collection.SimpleStatisticsCollectionPrinter.java

/**
 * @param entry The entry./*from ww w  . j  ava2  s .  c o  m*/
 * @param sb The string builder.
 * @param calcAverageDuration The flag.
 */
private void printCollectionEntryRow(StatisticsCollectionEntry entry, StringBuilder sb,
        boolean calcAverageDuration) {
    if (entry != null) {
        String minDurationMillis = "";
        String minDurationDate = "";
        String identifier = "";
        DurationAwareStatisticsEntry minEntry = entry.getMinDurationStatisticsEntry();
        if (minEntry != null) {
            identifier = StringUtils.defaultString(minEntry.getIdentifier());
            if (minEntry.hasDurationMillis()) {
                minDurationMillis = String.valueOf(minEntry.getDurationMillis());
            }
            minDurationDate = formatDate(minEntry.getCreationDate());
        }

        String maxDurationMillis = "";
        String maxDurationDate = "";
        DurationAwareStatisticsEntry maxEntry = entry.getMaxDurationStatisticsEntry();
        if (maxEntry != null) {
            if (maxEntry.hasDurationMillis()) {
                maxDurationMillis = String.valueOf(maxEntry.getDurationMillis());
            }
            maxDurationDate = formatDate(maxEntry.getCreationDate());
        }

        // calculate average duration millis
        String avgDuration = "";
        if (calcAverageDuration) {
            Long avgDurationValue = StatisticsCollectionUtils
                    .getAverageDuration(entry.getRecentStatisticsEntriesReadOnly());
            if (avgDuration != null) {
                avgDuration = String.valueOf(avgDurationValue);
            }
        }

        if (isHtml()) {
            sb.append("<tr>");
            sb.append("<td>" + identifier + "</td>");
            sb.append("<td>" + entry.getNumberOfInvocations() + "</td>");
            sb.append("<td>" + minDurationMillis + " (" + minDurationDate + ")" + "</td>");
            sb.append("<td>" + maxDurationMillis + " (" + maxDurationDate + ")" + "</td>");
            if (calcAverageDuration) {
                sb.append("<td>" + avgDuration + "</td>");
            }
            sb.append("</tr>");
        } else {
            sb.append(identifier).append(":");
            sb.append(" invocations=" + entry.getNumberOfInvocations());
            sb.append(" minDuration=" + minDurationMillis + " (" + minDurationDate + ")");
            sb.append(" maxDuration=" + maxDurationMillis + " (" + maxDurationDate + ")");
            if (calcAverageDuration) {
                sb.append(" avgDuration=" + avgDuration);
            }
            sb.append(nl());
        }
    }
}

From source file:org.codehaus.grepo.statistics.collection.SimpleStatisticsCollectionPrinter.java

/**
 * @param entry The entry.//  w w w.j  a v  a 2 s  .  c o  m
 * @param sb The string builder.
 */
private void printStatisticsEntryRow(StatisticsEntry entry, StringBuilder sb) {
    if (entry != null) {
        String duration = "";
        Long durationValue = StatisticsCollectionUtils.getDurationMillis(entry);
        if (durationValue != null) {
            duration = durationValue.toString();
        }

        String creationDate = formatDate(entry.getCreationDate());
        String completionDate = formatDate(StatisticsCollectionUtils.getCompletionDate(entry));

        String origin = StringUtils.defaultString(entry.getOrigin());

        if (isHtml()) {
            sb.append("<tr>");
            sb.append("<td>" + (StringUtils.isEmpty(duration) ? NBSP : duration) + "</td>");
            sb.append("<td>" + (StringUtils.isEmpty(creationDate) ? NBSP : creationDate) + "</td>");
            sb.append("<td>" + (StringUtils.isEmpty(completionDate) ? NBSP : completionDate) + "</td>");
            sb.append("<td>" + (StringUtils.isEmpty(origin) ? NBSP : origin) + "</td>");
            sb.append("</tr>");
        } else {
            sb.append(" duration: " + duration);
            sb.append(" creation: " + creationDate);
            sb.append(" completion: " + completionDate);
            sb.append(" origin: " + origin + nl());
        }
    }
}

From source file:org.codice.ddf.security.filter.authorization.AuthorizationFilter.java

@SuppressWarnings("PackageAccessibility")
@Override/* w  ww . ja va  2  s .c om*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Subject subject = null;

    if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
        LOGGER.debug("NO_AUTH_POLICY header was found, skipping authorization filter.");
        chain.doFilter(request, response);
    } else {
        try {
            subject = SecurityUtils.getSubject();
        } catch (Exception e) {
            LOGGER.debug("Unable to retrieve user from request.", e);
        }

        boolean permitted = true;

        String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
                : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());
        if (StringUtils.isEmpty(path)) {
            path = httpRequest.getRequestURI();
        }

        ContextPolicy policy = contextPolicyManager.getContextPolicy(path);

        if (policy != null && subject != null) {
            CollectionPermission permissions = policy.getAllowedAttributePermissions();
            if (!permissions.isEmpty()) {
                permitted = subject.isPermitted(permissions);
            }
        } else {
            LOGGER.warn(
                    "Unable to determine policy for path {}. User is not permitted to continue. Check policy configuration!",
                    path);
            permitted = false;
        }

        if (!permitted) {
            LOGGER.debug("Subject not authorized.");
            returnNotAuthorized(httpResponse);
        } else {
            LOGGER.debug("Subject is authorized!");
            chain.doFilter(request, response);
        }
    }
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

/**
 * Validates an attached SAML assertion, or exchanges any other incoming
 * token for a SAML assertion via the STS.
 *
 * @param request//from w w  w .ja v  a  2 s.  c  o m
 * @param response
 * @param chain
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    LOGGER.debug("Performing doFilter() on LoginFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
            : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());

    if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
        LOGGER.debug("NO_AUTH_POLICY header was found, skipping login filter.");
        chain.doFilter(request, response);
    } else {
        // perform validation
        final Subject subject = validateRequest(httpRequest);
        if (subject != null) {
            httpRequest.setAttribute(SecurityConstants.SECURITY_SUBJECT, subject);
            LOGGER.debug("Now performing request as user {} for {}", subject.getPrincipal(),
                    StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
                            : httpRequest.getServletPath());
            SecurityLogger.audit("Executing request {} on {} as user.", subject, httpRequest.getMethod(), path);
            subject.execute(() -> {
                PrivilegedExceptionAction<Void> action = () -> {
                    chain.doFilter(request, response);
                    return null;
                };
                SecurityAssertion securityAssertion = subject.getPrincipals()
                        .oneByType(SecurityAssertion.class);
                if (null != securityAssertion) {
                    HashSet emptySet = new HashSet();
                    javax.security.auth.Subject javaSubject = new javax.security.auth.Subject(true,
                            securityAssertion.getPrincipals(), emptySet, emptySet);
                    javax.security.auth.Subject.doAs(javaSubject, action);
                } else {
                    LOGGER.debug("Subject had no security assertion.");
                }
                return null;
            });

        } else {
            LOGGER.debug("Could not attach subject to http request.");
        }
    }

}

From source file:org.codice.ddf.security.filter.websso.WebSSOFilter.java

/**
 * Provides filtering for every registered http context. Checks for an
 * existing session (via the SAML assertion included as a cookie). If it
 * doesn't exist, it then looks up the current context and determines the
 * proper handlers to include in the chain. Each handler is given the
 * opportunity to locate their specific tokens if they exist or to go off
 * and obtain them. Once a token has been received that we know how to
 * convert to a SAML assertion, we attach them to the request and continue
 * down the chain./*from  ww  w .  j  a  v a2  s. c  om*/
 *
 * @param servletRequest  incoming http request
 * @param servletResponse response stream for returning the response
 * @param filterChain     chain of filters to be invoked following this filter
 * @throws IOException
 * @throws ServletException
 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    LOGGER.debug("Performing doFilter() on WebSSOFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
            : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());

    if (StringUtils.isEmpty(path)) {
        path = httpRequest.getRequestURI();
    }

    LOGGER.debug("Handling request for path {}", path);

    String realm = BaseAuthenticationToken.DEFAULT_REALM;
    boolean isWhiteListed = false;

    if (contextPolicyManager != null) {
        ContextPolicy policy = contextPolicyManager.getContextPolicy(path);
        if (policy != null) {
            realm = policy.getRealm();
        }

        isWhiteListed = contextPolicyManager.isWhiteListed(path);
    }

    // set this so the login filter can easily determine the realm
    servletRequest.setAttribute(ContextPolicy.ACTIVE_REALM, realm);

    if (isWhiteListed) {
        LOGGER.debug("Context of {} has been whitelisted, adding a NO_AUTH_POLICY attribute to the header.",
                path);
        servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, true);
        filterChain.doFilter(httpRequest, httpResponse);
    } else {
        // make sure request didn't come in with NO_AUTH_POLICY set
        servletRequest.setAttribute(ContextPolicy.NO_AUTH_POLICY, null);

        // now handle the request and set the authentication token
        LOGGER.debug("Handling request for {} in security realm {}.", path, realm);
        handleRequest(httpRequest, httpResponse, filterChain, getHandlerList(path));
    }

}