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, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is null, the value of defaultStr.

Usage

From source file:org.apache.archiva.proxy.DefaultRepositoryProxyConnectors.java

private void validatePolicies(Map<String, DownloadErrorPolicy> policies, Map<String, String> settings,
        Properties request, ArtifactReference artifact, RemoteRepositoryContent content, File localFile,
        Exception exception, Map<String, Exception> previousExceptions) throws ProxyDownloadException {
    boolean process = true;
    for (Entry<String, ? extends DownloadErrorPolicy> entry : policies.entrySet()) {

        // olamy with spring rolehint is now downloadPolicy#hint
        // so substring after last # to get the hint as with plexus
        String key = StringUtils.substringAfterLast(entry.getKey(), "#");
        DownloadErrorPolicy policy = entry.getValue();
        String defaultSetting = policy.getDefaultOption();
        String setting = StringUtils.defaultString(settings.get(key), defaultSetting);

        log.debug("Applying [{}] policy with [{}]", key, setting);
        try {//from ww  w.ja va 2s  .c om
            // all policies must approve the exception, any can cancel
            process = policy.applyPolicy(setting, request, localFile, exception, previousExceptions);
            if (!process) {
                break;
            }
        } catch (PolicyConfigurationException e) {
            log.error(e.getMessage(), e);
        }
    }

    if (process) {
        // if the exception was queued, don't throw it
        if (!previousExceptions.containsKey(content.getId())) {
            throw new ProxyDownloadException(
                    "An error occurred in downloading from the remote repository, and the policy is to fail immediately",
                    content.getId(), exception);
        }
    } else {
        // if the exception was queued, but cancelled, remove it
        previousExceptions.remove(content.getId());
    }

    log.warn(
            "Transfer error from repository {} for artifact {} , continuing to next repository. Error message: {}",
            content.getRepository().getId(), Keys.toKey(artifact), exception.getMessage());
    log.debug("Full stack trace", exception);
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get the value of the node./*from ww  w.ja va 2  s  .c  om*/
 * The value of the node is the content of the first text node.
 * If the node has no text nodes the <CODE>defaultValue</CODE> is
 * returned.
 */
public static String getValueOfNode(Node node, String defaultValue) {
    return StringUtils.defaultString(getValueOfNode(node), defaultValue);
}

From source file:org.apache.jackrabbit.oak.fixture.DocumentRdbFixture.java

@Override
public String toString() {
    return "DocumentNodeStore[RDB] on " + StringUtils.defaultString(this.jdbcUrl, this.pUrl);
}

From source file:org.apache.jetspeed.portlets.spaces.PageNavigator.java

@Override
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortletException, IOException {
    String name = actionRequest.getParameter("name");
    String type = actionRequest.getParameter("type");
    String templatePage = StringUtils.defaultString(actionRequest.getParameter("templatePage"), null);

    SpaceBean space = (SpaceBean) actionRequest.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE,
            PortletSession.APPLICATION_SCOPE);

    if (space == null) {
        log.warn("Space not found in session.");
        return;/*from   www  .  j  av a  2  s . c o m*/
    }

    if (StringUtils.isBlank(name)) {
        log.warn("Blank name to create a node of type " + type);
        return;
    }

    if (StringUtils.isBlank(type)) {
        throw new PortletException("Blank node type: " + type);
    }

    if ((Page.DOCUMENT_TYPE.equals(type) || (Folder.FOLDER_TYPE.equals(type)))
            && StringUtils.isBlank(templatePage)) {
        templatePage = actionRequest.getPreferences().getValue("defaultTemplatePage", null);

        if (StringUtils.isBlank(templatePage)) {
            throw new PortletException("Invalid template page: " + templatePage);
        }
    }

    try {
        RequestContext requestContext = (RequestContext) actionRequest
                .getAttribute(RequestContext.REQUEST_PORTALENV);
        ContentPage contentPage = requestContext.getPage();

        String spacePath = space.getPath();
        String contentPagePath = contentPage.getPath();
        String contentFolderPath = StringUtils
                .defaultIfEmpty(StringUtils.substringBeforeLast(contentPagePath, "/"), "/");
        String nodeName = name.replace(' ', '_');
        String nodePath = null;

        if (contentFolderPath.startsWith(spacePath)) {
            nodePath = StringUtils.removeEnd(contentFolderPath, "/") + "/"
                    + StringUtils.removeStart(nodeName, "/");
        } else {
            nodePath = StringUtils.removeEnd(spacePath, "/") + "/" + StringUtils.removeStart(nodeName, "/");
        }

        if (Page.DOCUMENT_TYPE.equals(type)) {
            String path = nodePath + Page.DOCUMENT_TYPE;
            Page source = pageManager.getPage(templatePage);
            Page newPage = pageManager.copyPage(source, path, false);
            newPage.setTitle(name);
            pageManager.updatePage(newPage);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);

            String redirect = admin.getPortalURL(actionRequest, actionResponse, path);
            actionResponse.sendRedirect(redirect);
        } else if (Folder.FOLDER_TYPE.equals(type)) {
            String path = nodePath;
            Folder folder = pageManager.newFolder(path);
            folder.setTitle(name);
            pageManager.updateFolder(folder);

            String defaultPagePath = folder.getPath() + "/" + Folder.FALLBACK_DEFAULT_PAGE;
            Page source = pageManager.getPage(templatePage);
            Page newPage = pageManager.copyPage(source, defaultPagePath, false);
            pageManager.updatePage(newPage);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);
        } else if (Link.DOCUMENT_TYPE.equals(type)) {
            String path = nodePath + Link.DOCUMENT_TYPE;
            Link link = pageManager.newLink(path);
            link.setTitle(name);
            pageManager.updateLink(link);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);
        }
    } catch (Exception e) {
        log.error("Failed to update page.", e);
    }
}

From source file:org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    String tagsStr = StringUtils.defaultIfEmpty(StringUtils.substringBeforeLast(request.getPathInfo(), "."), "")
            .replace("/", "");
    if (StringUtils.isBlank(tagsStr)) {
        // if not provided via path use parameter or default
        tagsStr = StringUtils.defaultIfEmpty(request.getParameter(PARAM_TAGS.name), "");
    }// w  ww .jav  a2s  .  com
    final String[] tags = tagsStr.split("[, ;]+");

    String format = StringUtils.substringAfterLast(request.getPathInfo(), ".");
    if (StringUtils.isBlank(format)) {
        // if not provided via extension use parameter or default
        format = StringUtils.defaultIfEmpty(request.getParameter(PARAM_FORMAT.name), FORMAT_HTML);
    }

    final Boolean includeDebug = Boolean.valueOf(request.getParameter(PARAM_INCLUDE_DEBUG.name));
    final Map<Result.Status, Integer> statusMapping = request.getParameter(PARAM_HTTP_STATUS.name) != null
            ? getStatusMapping(request.getParameter(PARAM_HTTP_STATUS.name))
            : null;

    HealthCheckExecutionOptions options = new HealthCheckExecutionOptions();
    options.setCombineTagsWithOr(Boolean
            .valueOf(StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_WITH_OR.name), "true")));
    options.setForceInstantExecution(Boolean.valueOf(request.getParameter(PARAM_FORCE_INSTANT_EXECUTION.name)));
    String overrideGlobalTimeoutVal = request.getParameter(PARAM_OVERRIDE_GLOBAL_TIMEOUT.name);
    if (StringUtils.isNumeric(overrideGlobalTimeoutVal)) {
        options.setOverrideGlobalTimeout(Integer.valueOf(overrideGlobalTimeoutVal));
    }

    List<HealthCheckExecutionResult> executionResults = this.healthCheckExecutor.execute(options, tags);

    Result.Status mostSevereStatus = Result.Status.DEBUG;
    for (HealthCheckExecutionResult executionResult : executionResults) {
        Status status = executionResult.getHealthCheckResult().getStatus();
        if (status.ordinal() > mostSevereStatus.ordinal()) {
            mostSevereStatus = status;
        }
    }
    Result overallResult = new Result(mostSevereStatus, "Overall status " + mostSevereStatus);

    sendNoCacheHeaders(response);

    if (statusMapping != null) {
        Integer httpStatus = statusMapping.get(overallResult.getStatus());
        response.setStatus(httpStatus);
    }

    if (FORMAT_HTML.equals(format)) {
        sendHtmlResponse(overallResult, executionResults, request, response, includeDebug);
    } else if (FORMAT_JSON.equals(format)) {
        sendJsonResponse(overallResult, executionResults, null, response, includeDebug);
    } else if (FORMAT_JSONP.equals(format)) {
        String jsonpCallback = StringUtils.defaultIfEmpty(request.getParameter(PARAM_JSONP_CALLBACK.name),
                JSONP_CALLBACK_DEFAULT);
        sendJsonResponse(overallResult, executionResults, jsonpCallback, response, includeDebug);
    } else if (FORMAT_TXT.equals(format)) {
        sendTxtResponse(overallResult, response);
    } else {
        response.setContentType("text/plain");
        response.getWriter().println("Invalid format " + format + " - supported formats: html|json|jsonp|txt");
    }

}

From source file:org.apache.sling.scripting.sightly.impl.html.dom.MarkupHandler.java

public void onAttribute(String name, String value, char quoteChar) {
    ElementContext context = elementStack.peek();
    if (Syntax.isPluginAttribute(name)) {
        handlePlugin(name, StringUtils.defaultString(value, ""), context);
    } else {/*www  . j a v  a2s.co  m*/
        context.addAttribute(name, value, quoteChar);
    }
}

From source file:org.apache.struts2.osgi.BaseOsgiHost.java

/**
  * Gets a param from the ServletContext, returning the default value if the param is not set
  *//from w ww  .jav a2  s .  co  m
  * @param paramName    the name of the param to get from the ServletContext
  * @param defaultValue value to return if the param is not set
  * @return
  */
protected String getServletContextParam(String paramName, String defaultValue) {
    return StringUtils.defaultString(this.servletContext.getInitParameter(paramName), defaultValue);
}

From source file:org.apache.zeppelin.interpreter.Interpreter.java

/**
 * Replace markers #{contextFieldName} by values from {@link InterpreterContext} fields
 * with same name and marker #{user}. If value == null then replace by empty string.
 *///from www  .  j a va  2s.co m
private void replaceContextParameters(Properties properties) {
    InterpreterContext interpreterContext = InterpreterContext.get();
    if (interpreterContext != null) {
        String markerTemplate = "#\\{%s\\}";
        List<String> skipFields = Arrays.asList("paragraphTitle", "paragraphId", "paragraphText");
        List typesToProcess = Arrays.asList(String.class, Double.class, Float.class, Short.class, Byte.class,
                Character.class, Boolean.class, Integer.class, Long.class);
        for (String key : properties.stringPropertyNames()) {
            String p = properties.getProperty(key);
            if (StringUtils.isNotEmpty(p)) {
                for (Field field : InterpreterContext.class.getDeclaredFields()) {
                    Class clazz = field.getType();
                    if (!skipFields.contains(field.getName())
                            && (typesToProcess.contains(clazz) || clazz.isPrimitive())) {
                        Object value = null;
                        try {
                            value = FieldUtils.readField(field, interpreterContext, true);
                        } catch (Exception e) {
                            logger.error("Cannot read value of field {0}", field.getName());
                        }
                        p = p.replaceAll(String.format(markerTemplate, field.getName()),
                                value != null ? value.toString() : StringUtils.EMPTY);
                    }
                }
                p = p.replaceAll(String.format(markerTemplate, "user"),
                        StringUtils.defaultString(userName, StringUtils.EMPTY));
                properties.setProperty(key, p);
            }
        }
    }
}

From source file:org.artifactory.common.wicket.component.file.browser.panel.FileBrowserPanel.java

public String getCurrentFolder() {
    return StringUtils.defaultString(pathHelper.getWorkingDirectoryPath(), "/");
}

From source file:org.bdval.cache.TableCache.java

/**
 * Given the specified paramters, return the File that will
 * be used for by TableCache./*w ww  . ja  v a  2s.c  om*/
 *
 * @param splitId     the split id
 * @param splitType   the split type
 * @param datasetName the dataset name
 * @return the File for the TableCache
 */
private File getCachedTableFile(final int splitId, final String splitType, final String datasetName) {
    final String cachedTableFilename = String.format(S_CACHED_FILENAME, cacheDirectoryName, datasetName,
            StringUtils.defaultString(splitType, "complete"), splitId);
    return new File(cachedTableFilename);
}