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

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

Introduction

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

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:org.jahia.modules.ugp.showcase.DbUserGroupProvider.java

private void filterQuery(Criteria query, Properties searchCriteria) {
    if (searchCriteria == null || searchCriteria.isEmpty()) {
        return;//from  w  w  w . ja  va  2s. c o m
    }

    String v = StringUtils.defaultIfBlank(searchCriteria.getProperty("groupname"),
            searchCriteria.getProperty("*"));
    if (StringUtils.isNotEmpty(v) && !"*".equals(v)) {
        query.add(Restrictions.ilike("groupname", StringUtils.replace(v, "*", "%")));
    }
}

From source file:org.jahia.modules.ugp.showcase.DbUserProvider.java

private Criteria addPropertyCriteria(String propName, Criteria query, Properties searchCriteria,
        Criteria propsQuery, List<Criterion> propsFilters) {
    String v = StringUtils.defaultIfBlank(searchCriteria.getProperty(propName),
            searchCriteria.getProperty("*"));
    if (StringUtils.isNotEmpty(v) && !"*".equals(v)) {
        if (propsQuery == null) {
            propsQuery = query.createCriteria("properties");
        }/*from   w ww .j  av  a2  s. c  o m*/
        propsFilters.add(Restrictions.and(Restrictions.eq("name", propName),
                Restrictions.ilike("value", StringUtils.replace(v, "*", "%"))));
    }
    return propsQuery;
}

From source file:org.jahia.modules.ugp.showcase.DbUserProvider.java

private Criteria filterQuery(Criteria query, Properties searchCriteria) {
    if (searchCriteria == null || searchCriteria.isEmpty()) {
        return query;
    }/*from  ww w .  j a  v a 2s.c om*/

    String v = StringUtils.defaultIfBlank(searchCriteria.getProperty("username"),
            searchCriteria.getProperty("*"));
    if (StringUtils.isNotEmpty(v) && !"*".equals(v)) {
        query.add(Restrictions.ilike("username", StringUtils.replace(v, "*", "%")));
    }

    List<Criterion> propsFilters = new LinkedList<>();
    Criteria propsQuery = addPropertyCriteria("j:firstName", query, searchCriteria, null, propsFilters);
    propsQuery = addPropertyCriteria("j:firstName", query, searchCriteria, propsQuery, propsFilters);
    propsQuery = addPropertyCriteria("j:lastName", query, searchCriteria, propsQuery, propsFilters);
    propsQuery = addPropertyCriteria("j:email", query, searchCriteria, propsQuery, propsFilters);

    if (propsQuery != null && !propsFilters.isEmpty()) {
        propsQuery.add(Restrictions.or(propsFilters.toArray(new Criterion[] {})));
    }

    return propsQuery != null ? propsQuery : query;
}

From source file:org.jahia.osgi.JahiaBundleTemplatesPackageHandler.java

static JahiaTemplatesPackage build(Bundle bundle) {
    if (bundle == null) {
        throw new IllegalArgumentException("Provided bundle is null");
    }/* w w  w .  ja v a2s.  c o m*/

    String moduleType = getHeader(bundle, "Jahia-Module-Type");

    if (StringUtils.isEmpty(moduleType)) {
        // not a valid Jahia module package
        return null;
    }

    final JahiaTemplatesPackage pkg = new JahiaTemplatesPackage(bundle);

    pkg.setModuleType(moduleType);

    pkg.setModulePriority(
            Integer.parseInt(StringUtils.defaultString(getHeader(bundle, "Jahia-Module-Priority"), "0")));
    pkg.setEditModeBlocked(Boolean
            .parseBoolean(StringUtils.defaultString(getHeader(bundle, "Jahia-Block-Edit-Mode"), "false")));
    pkg.setAutoDeployOnSite(StringUtils.defaultString(getHeader(bundle, "Jahia-Deploy-On-Site")));
    pkg.setName(StringUtils.defaultString(getHeader(bundle, "Implementation-Title", "Bundle-Name"),
            bundle.getSymbolicName()));

    pkg.setVersion(new ModuleVersion(StringUtils.defaultIfBlank(getHeader(bundle, "Implementation-Version"),
            bundle.getVersion().toString())));

    pkg.setId(bundle.getSymbolicName());
    pkg.setDescription(getHeader(bundle, "Bundle-Description"));
    detectResourceBundle(bundle, pkg);

    String srcFolder = getHeader(bundle, "Jahia-Source-Folders");
    if (srcFolder != null) {
        File sources = new File(srcFolder);
        if (sources.exists()) {
            ServicesRegistry.getInstance().getJahiaTemplateManagerService().setSourcesFolderInPackage(pkg,
                    sources);
        }
    }

    if (pkg.getScmURI() == null) {
        String scmUri = getHeader(bundle, "Jahia-Source-Control-Connection");
        pkg.setScmURI(scmUri);
    }

    if (pkg.getScmTag() == null) {
        String scmTag = getHeader(bundle, "Jahia-Source-Control-Tag");
        pkg.setScmTag(scmTag);
    }

    //Check if sources are downloadable for this package
    boolean isSourcesDownloadable = SettingsBean.getInstance().isMavenExecutableSet();
    if (isSourcesDownloadable) {
        String downloadSourcesHeader = getHeader(bundle, "Jahia-Download-Sources-Available");
        if (downloadSourcesHeader != null && ("false".equalsIgnoreCase(downloadSourcesHeader)
                || "no".equalsIgnoreCase(downloadSourcesHeader))) {
            isSourcesDownloadable = false;
        }
    }
    pkg.setSourcesDownloadable(isSourcesDownloadable);

    URL rootEntry = bundle.getEntry("/");
    if (rootEntry != null) {
        pkg.setFilePath(rootEntry.getPath());
    }

    String depends = getHeader(bundle, "Jahia-Depends");
    if (StringUtils.isNotBlank(depends)) {
        String[] dependencies = StringUtils.split(depends, ",");
        for (String dependency : dependencies) {
            pkg.setDepends(dependency.trim());
        }
    }

    pkg.setProvider(
            StringUtils.defaultString(getHeader(bundle, "Implementation-Vendor"), "Jahia Solutions Group SA"));

    pkg.setClassLoader(BundleUtils.createBundleClassLoader(bundle));

    pkg.setForgeUrl(getHeader(bundle, "Jahia-Private-App-Store"));

    pkg.setGroupId(getHeader(bundle, "Jahia-GroupId"));

    return pkg;
}

From source file:org.jahia.services.atmosphere.AtmosphereServlet.java

@Override
public void init(final ServletConfig sc) throws ServletException {
    ServletConfig scFacade;//  ww  w. java 2 s .c  o  m

    String asyncSupport = SettingsBean.getInstance().getAtmosphereAsyncSupport();
    // override asyncSupport only if explicitly set via jahia.properties or not set at all
    if (StringUtils.isNotEmpty(asyncSupport) || sc.getInitParameter(PROPERTY_COMET_SUPPORT) == null) {
        final String implName = StringUtils.defaultIfBlank(asyncSupport, DEFAULT_ASYNC_SUPPORT);
        scFacade = new ServletConfig() {
            @Override
            public String getInitParameter(String name) {
                return PROPERTY_COMET_SUPPORT.equals(name) ? implName : sc.getInitParameter(name);
            }

            @Override
            public Enumeration<String> getInitParameterNames() {
                ArrayList<String> names = Lists.newArrayList(PROPERTY_COMET_SUPPORT);
                CollectionUtils.addAll(names, sc.getInitParameterNames());
                return Collections.enumeration(names);
            }

            @Override
            public ServletContext getServletContext() {
                return sc.getServletContext();
            }

            @Override
            public String getServletName() {
                return sc.getServletName();
            }
        };
    } else {
        scFacade = sc;
    }

    super.init(scFacade);
}

From source file:org.jahia.services.modulemanager.persistence.PersistentBundleInfoBuilder.java

/**
 * Parses the supplied resource and builds the information for the bundle.
 *
 * @param resource The bundle resource//from w w w .j  a va2 s  .co m
 * @param calculateChecksum should we calculate the resource checksum?
 * @param checkTransformationRequired should we check if the module dependency capability headers has to be added
 * @return The information about the supplied bundle
 * @throws IOException In case of resource read errors
 */
public static PersistentBundle build(Resource resource, boolean calculateChecksum,
        boolean checkTransformationRequired) throws IOException {

    // populate data from manifest
    String groupId = null;
    String symbolicName = null;
    String version = null;
    String displayName = null;
    try (JarInputStream jarIs = new JarInputStream(resource.getInputStream())) {
        Manifest mf = jarIs.getManifest();
        if (mf != null) {
            Attributes attrs = mf.getMainAttributes();
            groupId = attrs.getValue(ATTR_NAME_GROUP_ID);
            symbolicName = attrs.getValue(ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
            version = StringUtils.defaultIfBlank(attrs.getValue(ATTR_NAME_BUNDLE_VERSION),
                    attrs.getValue(ATTR_NAME_IMPL_VERSION));
            displayName = StringUtils.defaultIfBlank(attrs.getValue(ATTR_NAME_IMPL_TITLE),
                    attrs.getValue(ATTR_NAME_BUNDLE_NAME));
        }
    }

    if (StringUtils.isBlank(symbolicName) || StringUtils.isBlank(version)) {
        // not a valid JAR or bundle information is missing -> we stop here
        logger.warn("Not a valid JAR or bundle information is missing for resource " + resource);
        return null;
    }

    PersistentBundle bundleInfo = new PersistentBundle(groupId, symbolicName, version);
    bundleInfo.setDisplayName(displayName);
    if (calculateChecksum) {
        bundleInfo.setChecksum(calculateDigest(resource));
    }
    if (checkTransformationRequired) {
        bundleInfo.setTransformationRequired(isTransformationRequired(resource));
    }
    bundleInfo.setResource(resource);
    return bundleInfo;
}

From source file:org.jahia.test.bin.TestServlet.java

protected void handleGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    String pathInfo = StringUtils.substringAfter(httpServletRequest.getPathInfo(), "/test");
    boolean isHtmlOutput = ".html".equals(pathInfo);
    String xmlTest = httpServletRequest.getParameter("xmlTest");
    if (pathInfo.contains("selenium") || !StringUtils.isEmpty(xmlTest)) {
        JahiaTemplatesPackage seleniumModule = ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                .getTemplatePackageById("selenium");
        if (seleniumModule == null) {
            throw new ServletException("Selenium module not found (or not started)");
        }// w w  w.j a  va  2s.c  o  m
        TestNG myTestNG = new TestNG();
        SurefireTestNGXMLResultFormatter xmlResultFormatter = new SurefireTestNGXMLResultFormatter(
                httpServletResponse.getOutputStream());
        myTestNG.addListener((ISuiteListener) xmlResultFormatter);
        myTestNG.addListener((ITestListener) xmlResultFormatter);

        final Enumeration<URL> resources = seleniumModule.getBundle().findEntries("testng",
                StringUtils.defaultIfBlank(xmlTest, "*.xml"), false);
        if (resources != null && resources.hasMoreElements()) {
            final List<XmlSuite> allSuites = new ArrayList<XmlSuite>();
            ClassLoaderUtils.executeWith(seleniumModule.getClassLoader(), new Callback<Boolean>() {
                @Override
                public Boolean execute() {
                    while (resources.hasMoreElements()) {
                        InputStream is = null;
                        try {
                            is = resources.nextElement().openStream();
                            Parser parser = new Parser(is);
                            List<XmlSuite> suites = parser.parseToList();

                            for (XmlSuite suite : suites) {
                                suite.setPreserveOrder("true");
                                suite.setConfigFailurePolicy("continue");
                                for (XmlTest test : suite.getTests()) {
                                    test.setPreserveOrder("true");
                                }
                            }

                            allSuites.addAll(suites);
                        } catch (Exception e) {
                            logger.error("Error executing test", e);
                        } finally {
                            IOUtils.closeQuietly(is);
                        }
                    }
                    return Boolean.TRUE;
                }
            });
            myTestNG.setXmlSuites(allSuites);
        } else {
            String className = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);
            try {
                Class<?> testClass = Class.forName(className);
                List<Class<?>> classes = getTestClasses(testClass, new ArrayList<Class<?>>());
                if (!classes.isEmpty()) {
                    myTestNG.setTestClasses(classes.toArray(new Class[classes.size()]));
                }
            } catch (Exception e) {
                logger.error("Error executing test", e);
            }
        }

        String testOutputDirectory = httpServletRequest.getParameter("testOutputDirectory");
        if (!StringUtils.isEmpty(testOutputDirectory)) {
            myTestNG.setOutputDirectory(testOutputDirectory);
            logger.info("Output directory set to " + testOutputDirectory);
        }
        myTestNG.setConfigFailurePolicy("continue");
        myTestNG.setPreserveOrder(true);
        myTestNG.run();
    } else if (StringUtils.isNotEmpty(pathInfo) && !pathInfo.contains("*") && !pathInfo.trim().equals("/")
            && !isHtmlOutput) {
        runTest(httpServletRequest, httpServletResponse, pathInfo);
    } else {
        Pattern testNamePattern = !isHtmlOutput && StringUtils
                .isNotEmpty(pathInfo) && !pathInfo.trim().equals("/") ? Pattern.compile(
                        pathInfo.length() > 1 && pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo)
                        : null;
        Set<String> testCases = getAllTestCases(
                Boolean.valueOf(httpServletRequest.getParameter("skipCoreTests")));

        PrintWriter pw = httpServletResponse.getWriter();
        // Return the lists of available tests
        List<String> tests = new LinkedList<String>();
        for (String o : testCases) {
            if (testNamePattern == null || testNamePattern.matcher(o).matches()) {
                tests.add(o);
            }
        }

        if (isHtmlOutput) {
            outputHtml(tests, httpServletRequest, httpServletResponse);
        } else {
            for (String c : tests) {
                pw.println(c);
            }
        }
    }
}

From source file:org.jasig.portlet.cms.controller.attachment.AbstractAttachmentThumbnailCreator.java

public StringBuilder generateHtmlFragment() throws Exception {
    StringBuilder builder = new StringBuilder();

    final File tmpFile = File.createTempFile("cmp", "." + getAttachment().getFileName(),
            getTemporaryDirectory());/*from   w  w w  .j a  v a  2  s.com*/
    tmpFile.deleteOnExit();

    getAttachment().write(tmpFile);
    if (logger.isDebugEnabled())
        logger.debug("Created attachment file at " + tmpFile.getAbsolutePath());

    final String rel = getGalleryGroupKey();

    builder = PortletUtilities.appendFormat(builder, "<li class=''{0}''>", getListItemCssClassName());

    final String path = StringUtils.defaultIfBlank(getLinkElementAttachmentPath(tmpFile), "");

    builder = PortletUtilities.appendFormat(builder,
            "<a id=''{0}'' href=''{1}'' rel=''{2}'' title=''{3}'' path=''{4}'' type=''{5}''>",
            getLinkElementId(), getPathToAttachment(tmpFile), rel,
            StringEscapeUtils.escapeHtml(getAttachment().getTitle()), path, getAttachment().getMimeType());

    builder = PortletUtilities.appendFormat(builder, "<img id=''{0}'' class=''{1}'' src=''{2}'' alt=''{3}'' />",
            getImageElementId(), getListItemImageCssClassName(), getPathToAttachmentImage(tmpFile),
            StringEscapeUtils.escapeHtml(getAttachment().getName()));

    builder.append("</a>");
    builder.append("</li>");

    return builder;
}

From source file:org.jboss.loom.migrators.logging.LoggingMigrator.java

/**
 * Creates a CLI script for adding a Async-Handler
 *
 * @param asyncHandler object of Async-Handler
 * @return string containing created CLI script
 * @throws CliScriptException if required attributes are missing
 * @deprecated  Generate this out of ModelNode.
 *///from   w w w . j a  va2s .c o  m
static String createAsyncHandlerScript(AsyncHandlerBean asyncHandler) throws CliScriptException {
    String errMsg = " in async-handler (AsyncAppender in AS5) must be set.";
    Utils.throwIfBlank(asyncHandler.getName(), errMsg, "Name");
    //Utils.throwIfBlank(asyncHandler.getQueueLength(), errMsg, "Queue length"); // It doesn't have to, in AS 5.

    StringBuilder resultScript = new StringBuilder("/subsystem=logging/async-handler=");
    resultScript.append(asyncHandler.getName()).append(":add(");
    //resultScript.append("queue-length=").append( String.defaultIfNull( asyncHandler.getQueueLength(), 100) );

    CliAddScriptBuilder builder = new CliAddScriptBuilder();
    builder.addProperty("queue-length",
            StringUtils.defaultIfBlank(asyncHandler.getQueueLength(), DEFAULT_QUEUE_LENGTH));
    builder.addProperty("level", asyncHandler.getLevel());
    builder.addProperty("filter", asyncHandler.getFilter());
    builder.addProperty("formatter", asyncHandler.getFormatter());
    builder.addProperty("overflow-action", asyncHandler.getOverflowAction());
    // TODO: AS7CliUtils.copyProperties(handler, builder, "level filter formatter ...");

    resultScript.append(builder.formatAndClearProps());

    if (asyncHandler.getSubhandlers() != null) {
        StringBuilder handlersBuilder = new StringBuilder();
        for (String subHandler : asyncHandler.getSubhandlers()) {
            handlersBuilder.append(", \"").append(subHandler).append("\"");
        }

        String handlers = handlersBuilder.toString().replaceFirst(", ", "");
        if (!handlers.isEmpty()) {
            resultScript.append(", subhandlers=[").append(handlers).append("]");
        }
    }

    resultScript.append(")");

    return resultScript.toString();
}

From source file:org.jboss.tools.openshift.core.server.behavior.OpenShiftLaunchController.java

protected DebugContext createDebugContext(OpenShiftServerBehaviour beh, IProgressMonitor monitor) {
    monitor.subTask("Initialising debugging...");

    DockerImageLabels imageLabels = getDockerImageLabels(beh, monitor);
    IServer server = beh.getServer();//from  www .j  a v  a  2  s  .co  m
    String devmodeKey = StringUtils.defaultIfBlank(OpenShiftServerUtils.getDevmodeKey(server),
            imageLabels.getDevmodeKey());
    String debugPortKey = StringUtils.defaultIfBlank(OpenShiftServerUtils.getDebugPortKey(server),
            imageLabels.getDevmodePortKey());
    String debugPort = StringUtils.defaultIfBlank(OpenShiftServerUtils.getDebugPort(server),
            imageLabels.getDevmodePortValue());
    return new DebugContext(beh.getServer(), devmodeKey, debugPortKey, debugPort);
}