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

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

Introduction

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

Prototype

public static String defaultIfEmpty(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:org.jahia.services.render.URLGenerator.java

public String getLogin() {
    if (login == null) {
        login = StringUtils.defaultIfEmpty(LoginConfig.getInstance().getCustomLoginUrl(context.getRequest()),
                Login.getServletPath());
    }/*from w w  w  .ja  v a 2s .co m*/

    return login;
}

From source file:org.jahia.services.seo.jcr.VanityUrlMapper.java

/**
 * checks if a vanity exists and put the result as an attribute of the request
 * this is used in urlRewriting rules/* ww  w .j  a  va 2s. c o m*/
 * @param hsRequest
 *              the request used during urlRewriting operations
 * @param outboundUrl
 *              the url received to be checked
 */
public void checkVanityUrl(HttpServletRequest hsRequest, String outboundContext, String outboundUrl) {
    hsRequest.removeAttribute(VANITY_KEY);

    URLResolverFactory urlResolverFactory = (URLResolverFactory) SpringContextSingleton
            .getBean("urlResolverFactory");
    VanityUrlService vanityUrlService = (VanityUrlService) SpringContextSingleton
            .getBean("org.jahia.services.seo.jcr.VanityUrlService");

    String ctx = StringUtils.defaultIfEmpty(hsRequest.getContextPath(), "");
    String fullUrl = ctx + Render.getRenderServletPath() + outboundUrl;
    hsRequest.setAttribute(VANITY_KEY, fullUrl);

    if (StringUtils.isNotEmpty(outboundUrl) && !Url.isLocalhost(hsRequest.getServerName())) {
        String serverName = null;
        String siteKey = null;
        String contextToCheck = outboundContext;
        int schemaDelimiterIndex = outboundContext.indexOf("://");
        if (schemaDelimiterIndex != -1) {
            try {
                URI uri = new URI(outboundContext);
                siteKey = lookupSiteKeyByServerName(uri.getHost());
                if (siteKey != null) {
                    contextToCheck = uri.getPath();
                    StringBuffer sb = new StringBuffer().append(uri.getScheme()).append("://")
                            .append(uri.getHost());
                    if (uri.getPort() != -1) {
                        sb.append(':').append(uri.getPort());
                    }
                    serverName = sb.toString();
                }
            } catch (URISyntaxException e) {
                // simply continue as siteKey will be determined later
            }
        } else if (StringUtils.isNotEmpty(
                (String) hsRequest.getAttribute(ServerNameToSiteMapper.ATTR_NAME_SERVERNAME_FOR_LINK))) {
            String host = (String) hsRequest.getAttribute(ServerNameToSiteMapper.ATTR_NAME_SERVERNAME_FOR_LINK);
            host = StringUtils.substringBefore(StringUtils.substringAfter(host, "://"), ":");
            siteKey = lookupSiteKeyByServerName(host);
        }
        if (StringUtils.equals(ctx, contextToCheck)) {
            String url = "/render" + outboundUrl;
            try {
                url = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // shouldn't happen
                throw new RuntimeException(e);
            }
            URLResolver urlResolver = urlResolverFactory.createURLResolver(url, hsRequest.getServerName(),
                    hsRequest);
            try {
                JCRNodeWrapper node = urlResolver.getNode();
                if (urlResolver.isMapped()) {
                    RenderContext context = (RenderContext) hsRequest.getAttribute("renderContext");
                    if (siteKey == null) {
                        siteKey = context != null ? context.getSite().getSiteKey()
                                : node.getResolveSite().getSiteKey();
                    }
                    VanityUrl vanityUrl = vanityUrlService.getVanityUrlForWorkspaceAndLocale(node,
                            urlResolver.getWorkspace(), urlResolver.getLocale(), siteKey);
                    if (vanityUrl != null && vanityUrl.isActive()) {
                        //for macros some parameters added (like ##requestParameters## for languageswitcher)
                        String macroExtension = "";
                        if (fullUrl.matches("(.?)*##[a-zA-Z]*##$")) {
                            macroExtension = "##" + StringUtils.substringBetween(fullUrl, "##") + "##";
                        }
                        hsRequest.setAttribute(VANITY_KEY, ctx + Render.getRenderServletPath() + "/"
                                + urlResolver.getWorkspace() + vanityUrl.getUrl() + macroExtension);
                        if (serverName != null) {
                            hsRequest.setAttribute(ServerNameToSiteMapper.ATTR_NAME_SERVERNAME_FOR_LINK,
                                    serverName);
                        }
                    }
                }
            } catch (RepositoryException e) {
                logger.debug("Error when trying to obtain vanity url", e);
                if (serverName != null) {
                    hsRequest.setAttribute(ServerNameToSiteMapper.ATTR_NAME_SERVERNAME_FOR_LINK, serverName);
                }
            }
        }
    }
}

From source file:org.jahia.services.templates.SourceControlHelper.java

private ModuleInfo getModuleInfo(final File sources, final String scmURI, final String moduleId,
        final String version, final String branchOrTag)
        throws IOException, DocumentException, XmlPullParserException {
    ModuleInfo info = new ModuleInfo();
    info.id = moduleId;//from  www  .  j a v  a2  s.c  o  m
    info.path = sources;
    info.version = version;

    Model pom = null;

    if (!StringUtils.isEmpty(moduleId)) {
        // Find the root folder of the module inside the repository, if in a subfolder
        Collection<File> files = FileUtils.listFiles(sources, POM_XML_FILE_FILTER, TrueFileFilter.INSTANCE);
        for (File file : files) {
            Model modulePom = PomUtils.read(file);
            if (moduleId.equals(modulePom.getArtifactId())) {
                // we've found our candidate
                pom = modulePom;
                info.path = file.getParentFile();
                break;
            }
        }
    } else {
        pom = PomUtils.read(new File(sources, "pom.xml"));
    }
    if (pom != null) {
        info.id = pom.getArtifactId();
        info.groupId = pom.getGroupId();
        info.version = pom.getVersion();
        Parent parent = pom.getParent();
        if (parent != null) {
            String v = parent.getVersion();
            if (info.version == null) {
                info.version = v;
            }

            if (info.groupId == null) {
                info.groupId = parent.getGroupId();
            }
        }
    } else {
        FileUtils.deleteQuietly(sources);
        String msg = Messages.getInternalWithArguments("source.not.found.with.uri",
                LocaleContextHolder.getLocale(), moduleId, StringUtils.defaultIfEmpty(version, ""), scmURI,
                StringUtils.defaultIfEmpty(branchOrTag, ""));
        logger.error(msg);
        throw new IOException(msg);
    }

    return info;
}

From source file:org.jahia.services.templates.TemplatePackageRegistry.java

/**
 * Returns the template package that corresponds to the provided OSGi bundle or <code>null</code> if the package is not registered.
 *
 * @param osgiBundle the corresponding OSGi bundle
 * @return the template package that corresponds to the provided OSGi bundle or <code>null</code> if the package is not registered
 *///from  w  ww.  jav  a  2s  .c o m
public JahiaTemplatesPackage lookupByBundle(Bundle osgiBundle) {
    if (packagesByName == null) {
        return null;
    }
    if (osgiBundle == null) {
        throw new IllegalArgumentException("OSGi bundle is null");
    }

    String moduleId = osgiBundle.getSymbolicName();
    String version = StringUtils.defaultIfEmpty((String) osgiBundle.getHeaders().get("Implementation-Version"),
            osgiBundle.getVersion().toString());

    return lookupByIdAndVersion(moduleId, new ModuleVersion(version));
}

From source file:org.jasig.portlet.blackboardvcportlet.mvc.sessionmngr.forms.TelephonyForm.java

/**
 * Sets the variable sessionSIPPhone. If setting to "" it will change it to null so that the validation
 * will only provide one error message/*from w ww.j  a  va2s  . co  m*/
 * @param sessionSIPPhone
 */
public void setSessionSIPPhone(String sessionSIPPhone) {
    this.sessionSIPPhone = StringUtils.defaultIfEmpty(sessionSIPPhone, null);
}

From source file:org.jboss.as.test.integration.security.common.AbstractSecurityDomainsServerSetupTask.java

/**
 * Creates authenticaton=>jaspi node and its child nodes.
 *
 * @param securityConfigurations/*  ww w.j a v  a2s.  c  om*/
 * @return
 */
private List<ModelNode> createJaspiAuthnNodes(JaspiAuthn securityConfigurations, String domainName) {
    if (securityConfigurations == null) {
        LOGGER.trace("No security configuration for JASPI module.");
        return null;
    }
    if (securityConfigurations.getAuthnModules() == null || securityConfigurations.getAuthnModules().length == 0
            || securityConfigurations.getLoginModuleStacks() == null
            || securityConfigurations.getLoginModuleStacks().length == 0) {
        throw new IllegalArgumentException(
                "Missing mandatory part of JASPI configuration in the security domain.");
    }

    final List<ModelNode> steps = new ArrayList<ModelNode>();

    PathAddress domainAddress = PathAddress.pathAddress().append(SUBSYSTEM, SUBSYSTEM_SECURITY)
            .append(SECURITY_DOMAIN, domainName);
    PathAddress jaspiAddress = domainAddress.append(
            org.jboss.as.test.integration.security.common.Constants.AUTHENTICATION,
            org.jboss.as.test.integration.security.common.Constants.JASPI);
    steps.add(Util.createAddOperation(jaspiAddress));

    for (final AuthnModule config : securityConfigurations.getAuthnModules()) {
        LOGGER.trace("Adding auth-module: " + config);
        final ModelNode securityModuleNode = Util
                .createAddOperation(jaspiAddress.append(AUTH_MODULE, config.getName()));
        steps.add(securityModuleNode);
        securityModuleNode.get(ModelDescriptionConstants.CODE).set(config.getName());
        if (config.getFlag() != null) {
            securityModuleNode.get(FLAG).set(config.getFlag());
        }
        if (config.getModule() != null) {
            securityModuleNode.get(org.jboss.as.test.integration.security.common.Constants.MODULE)
                    .set(config.getModule());
        }
        if (config.getLoginModuleStackRef() != null) {
            securityModuleNode
                    .get(org.jboss.as.test.integration.security.common.Constants.LOGIN_MODULE_STACK_REF)
                    .set(config.getLoginModuleStackRef());
        }
        Map<String, String> configOptions = config.getOptions();
        if (configOptions == null) {
            LOGGER.trace("No module options provided.");
            configOptions = Collections.emptyMap();
        }
        final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS);
        for (final Map.Entry<String, String> entry : configOptions.entrySet()) {
            final String optionName = entry.getKey();
            final String optionValue = entry.getValue();
            moduleOptionsNode.add(optionName, optionValue);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Adding module option [" + optionName + "=" + optionValue + "]");
            }
        }
    }
    //Unable to use securityComponentNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true) because the login-module-stack is empty

    for (final LoginModuleStack lmStack : securityConfigurations.getLoginModuleStacks()) {
        PathAddress lmStackAddress = jaspiAddress.append(
                org.jboss.as.test.integration.security.common.Constants.LOGIN_MODULE_STACK, lmStack.getName());
        steps.add(Util.createAddOperation(lmStackAddress));

        for (final SecurityModule config : lmStack.getLoginModules()) {
            final String code = config.getName();
            final ModelNode securityModuleNode = Util
                    .createAddOperation(lmStackAddress.append(LOGIN_MODULE, code));

            final String flag = StringUtils.defaultIfEmpty(config.getFlag(),
                    org.jboss.as.test.integration.security.common.Constants.REQUIRED);
            securityModuleNode.get(ModelDescriptionConstants.CODE).set(code);
            securityModuleNode.get(FLAG).set(flag);
            if (LOGGER.isInfoEnabled()) {
                LOGGER.trace("Adding JASPI login module stack [code=" + code + ", flag=" + flag + "]");
            }
            Map<String, String> configOptions = config.getOptions();
            if (configOptions == null) {
                LOGGER.trace("No module options provided.");
                configOptions = Collections.emptyMap();
            }
            final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS);
            for (final Map.Entry<String, String> entry : configOptions.entrySet()) {
                final String optionName = entry.getKey();
                final String optionValue = entry.getValue();
                moduleOptionsNode.add(optionName, optionValue);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Adding module option [" + optionName + "=" + optionValue + "]");
                }
            }
            securityModuleNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
            steps.add(securityModuleNode);
        }

    }

    return steps;
}

From source file:org.jboss.as.test.integration.security.common.AbstractSecurityDomainsServerSetupTask.java

/**
 * Creates a {@link ModelNode} with the security component configuration. If the securityConfigurations array is empty or
 * null, then null is returned.//w  w w  .  j  a va  2 s.  c  o m
 *
 * @param securityComponent name of security component (e.g. {@link org.jboss.as.test.integration.security.common.Constants#AUTHORIZATION})
 * @param subnodeName       name of the security component subnode, which holds module configurations (e.g.
 *                          {@link org.jboss.as.test.integration.security.common.Constants#POLICY_MODULES})
 * @param flagAttributeName name of attribute to which the value of {@link SecurityModule#getFlag()} is set
 * @param flagDefaultValue  default value for flagAttributeName attr.
 * @param securityModules   configurations
 * @return ModelNode instance or null
 */
private boolean createSecurityModelNode(String securityComponent, String subnodeName, String flagAttributeName,
        String flagDefaultValue, final SecurityModule[] securityModules, String domainName,
        ModelNode operations) {
    if (securityModules == null || securityModules.length == 0) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.trace("No security configuration for " + securityComponent + " module.");
        }
        return false;
    }
    PathAddress address = PathAddress.pathAddress().append(SUBSYSTEM, SUBSYSTEM_SECURITY)
            .append(SECURITY_DOMAIN, domainName).append(securityComponent, CLASSIC);
    operations.add(Util.createAddOperation(address));

    for (final SecurityModule config : securityModules) {
        final String code = config.getName();
        final ModelNode securityModuleNode = Util.createAddOperation(address.append(subnodeName, code));

        final String flag = StringUtils.defaultIfEmpty(config.getFlag(), flagDefaultValue);
        securityModuleNode.get(ModelDescriptionConstants.CODE).set(code);
        securityModuleNode.get(flagAttributeName).set(flag);
        Map<String, String> configOptions = config.getOptions();
        if (configOptions == null) {
            LOGGER.trace("No module options provided.");
            configOptions = Collections.emptyMap();
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.trace("Adding " + securityComponent + " module [code=" + code + ", " + flagAttributeName
                    + "=" + flag + ", options = " + configOptions + "]");
        }
        final ModelNode moduleOptionsNode = securityModuleNode.get(MODULE_OPTIONS);
        for (final Map.Entry<String, String> entry : configOptions.entrySet()) {
            final String optionName = entry.getKey();
            final String optionValue = entry.getValue();
            moduleOptionsNode.add(optionName, optionValue);
        }
        securityModuleNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true);
        operations.add(securityModuleNode);
    }
    return true;
}

From source file:org.jboss.dashboard.ui.formatters.FileNavigationTreeFormatter.java

protected void renderDirectory(FileObject currentDir) throws FileSystemException {
    String dirName = currentDir.getName().getBaseName();
    setAttribute("dirName", StringUtils.defaultIfEmpty(dirName, "/"));
    setAttribute("path", currentDir.getName().getPath());
    FileObject[] children = currentDir.getChildren();
    List childDirectories = new ArrayList();
    boolean hasChildDirectories = false;
    if (children != null)
        for (int i = 0; i < children.length; i++) {
            FileObject child = children[i];
            if (child.getType().equals(FileType.FOLDER) && !child.isHidden() && child.isReadable()) {
                hasChildDirectories = true;
                childDirectories.add(child);
            }// ww  w . j a v  a2 s.  c o  m
        }
    setAttribute("hasChildrenDirectories", hasChildDirectories);
    String directoryPath = currentDir.getName().getPath();
    boolean isOpen = getFileNavigationHandler().getOpenPaths().contains(directoryPath);
    setAttribute("isOpen", isOpen);
    setAttribute("isCurrent", getFileNavigationHandler().getCurrentPath().equals(directoryPath));
    renderFragment("outputDirectory");
    if (childDirectories.size() > 0) {
        sortDirectories(childDirectories);
        if (isOpen) {
            renderFragment("beforeChildren");
            for (int i = 0; i < childDirectories.size(); i++) {
                FileObject child = (FileObject) childDirectories.get(i);
                renderDirectory(child);
            }
            renderFragment("afterChildren");
        }
    }
}

From source file:org.jboss.tools.openshift.internal.ui.job.DeployImageJob.java

private Map<String, String> getModifiedEnvVars(Collection<EnvironmentVariable> envVars,
        Map<String, String> dockerEnvVars) {
    Map<String, String> envs = new HashMap<>();
    for (EnvironmentVariable var : parameters.getEnvironmentVariables()) {
        //will return null if new
        if (!StringUtils.defaultIfEmpty(dockerEnvVars.get(var.getKey()), "").equals(var.getValue())) {
            envs.put(var.getKey(), var.getValue());
        }/*from w  w w .j a va  2 s .c  o m*/
    }
    return envs;
}

From source file:org.jenkinsci.plugins.DependencyCheck.DependencyCheckPublisher.java

@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger)
        throws InterruptedException, IOException {
    logger.log("Collecting Dependency-Check analysis files...");
    FilesParser dcCollector = new FilesParser(DependencyCheckPlugin.PLUGIN_NAME,
            StringUtils.defaultIfEmpty(getPattern(), DEFAULT_PATTERN), new ReportParser(getDefaultEncoding()),
            shouldDetectModules(), isMavenBuild(build));
    ParserResult project = build.getWorkspace().act(dcCollector);
    logger.logLines(project.getLogMessages());

    DependencyCheckResult result = new DependencyCheckResult(build, getDefaultEncoding(), project,
            useOnlyStableBuildsAsReference());
    build.getActions().add(new DependencyCheckResultAction(build, this, result));

    return result;
}