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

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

Introduction

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

Prototype

public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) 

Source Link

Document

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

 StringUtils.defaultIfEmpty(null, "NULL")  = "NULL" StringUtils.defaultIfEmpty("", "NULL")    = "NULL" StringUtils.defaultIfEmpty(" ", "NULL")   = " " StringUtils.defaultIfEmpty("bat", "NULL") = "bat" StringUtils.defaultIfEmpty("", null)      = null 

Usage

From source file:ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider.java

/**
 * Constructor allowing the description, servername and server to be set
 * /*from w  w  w. j a v  a2s .  c  om*/
 * @param ctx
 *           the {@link FhirContext} instance.
 * @param implementationDescription
 *           the implementation description. If null, "" is used
 * @param serverName
 *           the server name. If null, "" is used
 * @param serverVersion
 *           the server version. If null, "" is used
 */
protected AbstractJaxRsConformanceProvider(FhirContext ctx, String implementationDescription, String serverName,
        String serverVersion) {
    super(ctx);
    serverConfiguration.setFhirContext(ctx);
    serverConfiguration.setImplementationDescription(StringUtils.defaultIfEmpty(implementationDescription, ""));
    serverConfiguration.setServerName(StringUtils.defaultIfEmpty(serverName, ""));
    serverConfiguration.setServerVersion(StringUtils.defaultIfEmpty(serverVersion, ""));
}

From source file:ductive.console.commands.parser.CmdParserBuilder.java

private Parser<?> argValueParser(ArgumentType arg) {
    ArgParserRegistration registration = argParserRegistry.find(arg.type,
            StringUtils.defaultIfEmpty(arg.parserQualifier, null));
    if (registration != null)
        return argParserFactory.create(registration);

    if (arg.type.isArray())
        return fallbackArgValueParser(arg, arg.type.getComponentType());

    return fallbackArgValueParser(arg, arg.type);
}

From source file:com.xpn.xwiki.internal.pdf.FOPXSLFORenderer.java

@Override
public void render(InputStream input, OutputStream output, String outputFormat) throws Exception {
    FOUserAgent foUserAgent = this.fopFactory.newFOUserAgent();

    // Transform FOP fatal errors into warnings so that the PDF export isn't stopped.
    foUserAgent.getEventBroadcaster().addEventListener(new XWikiFOPEventListener());

    // Construct FOP with desired output format.
    Fop fop = this.fopFactory.newFop(outputFormat, foUserAgent, output);

    // Identity transformer
    Transformer transformer = this.transformerFactory.newTransformer();

    // Setup input stream.
    Source source = new StreamSource(input);

    // Resulting SAX events (the generated FO) must be piped through to FOP.
    Result result = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing.
    transformer.transform(source, result);

    // Result processing
    FormattingResults foResults = fop.getResults();
    if (foResults != null && this.logger.isDebugEnabled()) {
        @SuppressWarnings("unchecked")
        List<PageSequenceResults> pageSequences = foResults.getPageSequences();
        for (PageSequenceResults pageSequenceResults : pageSequences) {
            this.logger
                    .debug("PageSequence " + StringUtils.defaultIfEmpty(pageSequenceResults.getID(), "<no id>")
                            + " generated " + pageSequenceResults.getPageCount() + " pages.");
        }//from   w  ww.j a v a 2s .  c  o m
        this.logger.debug("Generated " + foResults.getPageCount() + " pages in total.");
    }
}

From source file:com.jredrain.dao.MapResultTransFormer.java

/**
 * ????
 *
 * @param name
 * @return
 */
protected String getAlias(String name) {
    return StringUtils.defaultIfEmpty(aliasMap.get(name.toLowerCase()), name);
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Retrieve all fields deemed as Exposed, i.e. they are public or have a public accessor method or are marked by an
 * annotation to be exposed.// w  ww .  j a  v a  2  s.  co m
 *
 * @param clazz cannot be <code>null</code>.
 * @return
 */
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) {
    List<ReflectedInfo> results = null;
    try {
        results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() {
            /**
             * This method is called if the value is not found in the cache. This
             * is where the real reflection work is done.
             */
            public List<ReflectedInfo> call() throws Exception {
                List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>();
                for (Method m : clazz.getMethods()) {
                    if (ReflectionUtils.isGetter(m) && !isIgnored(m)) {
                        Field f = getGetterField(m);
                        if (f != null && !isIgnored(f)) {
                            f.setAccessible(true);
                            Siren4JProperty propAnno = f.getAnnotation(Siren4JProperty.class);
                            String effectiveName = propAnno != null
                                    ? StringUtils.defaultIfEmpty(propAnno.name(), f.getName())
                                    : f.getName();
                            Siren4JSubEntity subAnno = f.getAnnotation(Siren4JSubEntity.class);
                            if (subAnno != null && !ArrayUtils.isEmpty(subAnno.rel())) {
                                effectiveName = subAnno.rel().length == 1 ? subAnno.rel()[0]
                                        : ArrayUtils.toString(subAnno.rel());
                            }
                            exposed.add(new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f),
                                    effectiveName));
                        }
                    }
                }
                return exposed;
            }

        });
    } catch (ExecutionException e) {
        throw new Siren4JRuntimeException(e);
    }
    return results;

}

From source file:com.ibasco.agql.examples.base.BaseExample.java

@SuppressWarnings("unchecked")
protected String promptInput(String message, boolean required, String defaultReturnValue,
        String defaultProperty) {
    Scanner userInput = new Scanner(System.in);
    String returnValue;//from   w  w  w. j  a va 2 s  .  co m
    //perform some bit of magic to determine if the prompt is a password type
    boolean inputEmpty, isPassword = StringUtils.containsIgnoreCase(message, "password");
    int retryCounter = 0;
    String defaultValue = defaultReturnValue;

    //Get value from file (if available)
    if (!StringUtils.isEmpty(defaultProperty)) {
        if (isPassword) {
            try {
                String defaultProp = getProp(defaultProperty);
                if (!StringUtils.isEmpty(defaultProp))
                    defaultValue = decrypt(defaultProp);
            } catch (Exception e) {
                throw new AsyncGameLibUncheckedException(e);
            }
        } else {
            defaultValue = getProp(defaultProperty);
        }
    }

    do {
        if (!StringUtils.isEmpty(defaultValue)) {
            if (isPassword) {
                System.out.printf("%s [%s]: ", message, StringUtils.replaceAll(defaultValue, ".", "*"));
            } else
                System.out.printf("%s [%s]: ", message, defaultValue);
        } else {
            System.out.printf("%s: ", message);
        }
        System.out.flush();
        returnValue = StringUtils.defaultIfEmpty(userInput.nextLine(), defaultValue);
        inputEmpty = StringUtils.isEmpty(returnValue);
    } while ((inputEmpty && ++retryCounter < 3) && required);

    //If the token is still empty, throw an error
    if (inputEmpty && required) {
        System.err.println("Required parameter is missing");
    } else if (inputEmpty && !StringUtils.isEmpty(defaultValue)) {
        returnValue = defaultValue;
    }

    //Save to properties file
    if (!StringUtils.isEmpty(defaultProperty)) {
        if (isPassword) {
            try {
                saveProp(defaultProperty, encrypt(returnValue));
            } catch (Exception e) {
                throw new AsyncGameLibUncheckedException(e);
            }
        } else {
            saveProp(defaultProperty, returnValue);
        }
    }

    return returnValue;
}

From source file:com.formkiq.core.service.sign.SigningServiceImpl.java

/**
 * Crate Form Field./*ww w .java 2s .  co m*/
 * @param id int
 * @param type {@link FormJSONFieldType}
 * @param label {@link String}
 * @param value {@link Object}
 * @return {@link FormJSONField}
 */
private FormJSONField createFormField(final int id, final FormJSONFieldType type, final String label,
        final Object value) {

    FormJSONField f = new FormJSONField();
    f.setId(id);
    f.setLabel(label);
    f.setType(type);

    if (value instanceof Date) {

        Date date = (Date) value;
        String v = this.jsonDateFormat.format(date);
        f.setValue(v);

    } else {

        f.setValue(StringUtils.defaultIfEmpty((String) value, ""));
    }
    return f;
}

From source file:com.xpn.xwiki.plugin.skinx.AbstractDocumentSkinExtensionPlugin.java

/**
 * {@inheritDoc}/* w  ww  .j av a 2 s . c om*/
 * <p>
 * For this kind of resources, an XObject property (<tt>use</tt>) with the value <tt>always</tt> indicates always
 * used extensions. The list of extensions for each wiki is lazily placed in a cache: if the extension set for the
 * context wiki is null, then they will be looked up in the database and added to it. The cache is invalidated using
 * the notification mechanism.
 * </p>
 * 
 * @see AbstractSkinExtensionPlugin#getAlwaysUsedExtensions(XWikiContext)
 */
@Override
public Set<String> getAlwaysUsedExtensions(XWikiContext context) {
    // Retrieve the current wiki name from the XWiki context
    String currentWiki = StringUtils.defaultIfEmpty(context.getDatabase(), context.getMainXWiki());
    // If we already have extensions defined for this wiki, we return them
    if (this.alwaysUsedExtensions.get(currentWiki) != null) {
        return this.alwaysUsedExtensions.get(currentWiki);
    } else {
        // Otherwise, we look them up in the database.
        Set<String> extensions = new HashSet<String>();
        String query = ", BaseObject as obj, StringProperty as use where obj.className='"
                + getExtensionClassName() + "'"
                + " and obj.name=doc.fullName and use.id.id=obj.id and use.id.name='use' and use.value='always'";
        try {
            for (String extension : context.getWiki().getStore().searchDocumentsNames(query, context)) {
                try {
                    XWikiDocument doc = context.getWiki().getDocument(extension, context);
                    // Only add the extension as being "always used" if the page holding it has been saved with
                    // programming rights.
                    if (context.getWiki().getRightService().hasProgrammingRights(doc, context)) {
                        extensions.add(extension);
                    }
                } catch (XWikiException e1) {
                    LOGGER.error("Error while adding skin extension [{}] as always used. It will be ignored.",
                            extension, e1);
                }
            }
            this.alwaysUsedExtensions.put(currentWiki, extensions);
            return extensions;
        } catch (XWikiException e) {
            LOGGER.error("Error while retrieving always used JS extensions", e);
            return Collections.emptySet();
        }
    }
}

From source file:com.sonicle.webtop.core.sdk.ServiceManifest.java

public ServiceManifest(HierarchicalConfiguration svcEl) throws Exception {

    String pkg = svcEl.getString("package");
    if (StringUtils.isEmpty(pkg))
        throw new Exception("Invalid value for property [package]");
    javaPackage = StringUtils.lowerCase(pkg);
    id = javaPackage;/*from   ww  w .  j  av a2  s .c  o m*/

    String jspkg = svcEl.getString("jsPackage");
    if (StringUtils.isEmpty(jspkg))
        throw new Exception("Invalid value for property [jsPackage]");
    jsPackage = jspkg; // Lowercase allowed!

    String sname = svcEl.getString("shortName");
    if (StringUtils.isEmpty(sname))
        throw new Exception("Invalid value for property [shortName]");
    xid = sname;

    ServiceVersion ver = new ServiceVersion(svcEl.getString("version"));
    if (ver.isUndefined())
        throw new Exception("Invalid value for property [version]");
    version = ver;

    buildDate = StringUtils.defaultIfBlank(svcEl.getString("buildDate"), null);
    buildType = StringUtils.defaultIfBlank(svcEl.getString("buildType"), BUILD_TYPE_DEV);
    company = StringUtils.defaultIfBlank(svcEl.getString("company"), null);
    companyEmail = StringUtils.defaultIfBlank(svcEl.getString("companyEmail"), null);
    companyWebSite = StringUtils.defaultIfBlank(svcEl.getString("companyWebSite"), null);
    supportEmail = StringUtils.defaultIfBlank(svcEl.getString("supportEmail"), null);

    List<HierarchicalConfiguration> hconf = null;

    hconf = svcEl.configurationsAt("controller");
    if (!hconf.isEmpty()) {
        //if (hconf.size() != 1) throw new Exception(invalidCardinalityEx("controller", "1"));
        if (hconf.size() > 1)
            throw new Exception(invalidCardinalityEx("controller", "*1"));

        final String cn = hconf.get(0).getString("[@className]");
        if (StringUtils.isBlank(cn))
            throw new Exception(invalidAttributeValueEx("controller", "className"));
        controllerClassName = buildJavaClassName(javaPackage, cn);

    } else { // Old-style configuration
        if (svcEl.containsKey("controllerClassName")) {
            controllerClassName = LangUtils.buildClassName(javaPackage,
                    StringUtils.defaultIfEmpty(svcEl.getString("controllerClassName"), "Controller"));
        }
    }

    hconf = svcEl.configurationsAt("manager");
    if (!hconf.isEmpty()) {
        if (!hconf.isEmpty()) {
            if (hconf.size() > 1)
                throw new Exception(invalidCardinalityEx("manager", "*1"));

            final String cn = hconf.get(0).getString("[@className]");
            if (StringUtils.isBlank(cn))
                throw new Exception(invalidAttributeValueEx("manager", "className"));
            managerClassName = buildJavaClassName(javaPackage, cn);
        }

    } else { // Old-style configuration
        if (svcEl.containsKey("managerClassName")) {
            managerClassName = LangUtils.buildClassName(javaPackage,
                    StringUtils.defaultIfEmpty(svcEl.getString("managerClassName"), "Manager"));
        }
    }

    /*
    hconf = svcEl.configurationsAt("privateService");
    if (!hconf.isEmpty()) {
       if (!hconf.isEmpty()) {
    if (hconf.size() > 1) throw new Exception(invalidCardinalityEx("manager", "*1"));
            
    final String cn = hconf.get(0).getString("[@className]");
    if (StringUtils.isBlank(cn)) throw new Exception(invalidAttributeValueEx("privateService", "className"));
    final String jcn = hconf.get(0).getString("[@jsClassName]");
    if (StringUtils.isBlank(jcn)) throw new Exception(invalidAttributeValueEx("privateService", "jsClassName"));
            
    privateServiceClassName = LangUtils.buildClassName(javaPackage, cn);
    privateServiceJsClassName = jcn;
    privateServiceVarsModelJsClassName = hconf.get(0).getString("[@jsClassName]");
       }
               
    } else { // Old-style configuration
       if (svcEl.containsKey("serviceClassName")) {
    String cn = StringUtils.defaultIfEmpty(svcEl.getString("serviceClassName"), "Service");
    privateServiceClassName = LangUtils.buildClassName(javaPackage, cn);
    privateServiceJsClassName = StringUtils.defaultIfEmpty(svcEl.getString("serviceJsClassName"), cn);
    privateServiceVarsModelJsClassName = StringUtils.defaultIfEmpty(svcEl.getString("serviceVarsModelJsClassName"), "model.ServiceVars");
       }
    }
    */

    if (svcEl.containsKey("serviceClassName")) {
        String cn = StringUtils.defaultIfEmpty(svcEl.getString("serviceClassName"), "Service");
        privateServiceClassName = LangUtils.buildClassName(javaPackage, cn);
        privateServiceJsClassName = StringUtils.defaultIfEmpty(svcEl.getString("serviceJsClassName"), cn);
        privateServiceVarsModelJsClassName = StringUtils
                .defaultIfEmpty(svcEl.getString("serviceVarsModelJsClassName"), "model.ServiceVars");
    }

    if (svcEl.containsKey("publicServiceClassName")) {
        String cn = StringUtils.defaultIfEmpty(svcEl.getString("publicServiceClassName"), "PublicService");
        publicServiceClassName = LangUtils.buildClassName(javaPackage,
                StringUtils.defaultIfEmpty(svcEl.getString("publicServiceClassName"), "PublicService"));
        publicServiceJsClassName = StringUtils.defaultIfEmpty(svcEl.getString("publicServiceJsClassName"), cn);
        publicServiceVarsModelJsClassName = StringUtils.defaultIfEmpty(
                svcEl.getString("publicServiceVarsModelJsClassName"), "model.PublicServiceVars");
    }

    hconf = svcEl.configurationsAt("jobService");
    if (!hconf.isEmpty()) {
        if (hconf.size() > 1)
            throw new Exception(invalidCardinalityEx("jobService", "*1"));

        final String cn = hconf.get(0).getString("[@className]");
        if (StringUtils.isBlank(cn))
            throw new Exception(invalidAttributeValueEx("jobService", "className"));
        jobServiceClassName = LangUtils.buildClassName(javaPackage, cn);

    } else { // Old-style configuration
        if (svcEl.containsKey("jobServiceClassName")) {
            jobServiceClassName = LangUtils.buildClassName(javaPackage,
                    StringUtils.defaultIfEmpty(svcEl.getString("jobServiceClassName"), "JobService"));
        }
    }

    if (!svcEl.configurationsAt("userOptions").isEmpty()) {
        userOptionsServiceClassName = LangUtils.buildClassName(javaPackage, StringUtils
                .defaultIfEmpty(svcEl.getString("userOptions.serviceClassName"), "UserOptionsService"));
        userOptionsViewJsClassName = StringUtils.defaultIfEmpty(svcEl.getString("userOptions.viewJsClassName"),
                "view.UserOptions");
        userOptionsModelJsClassName = StringUtils
                .defaultIfEmpty(svcEl.getString("userOptions.modelJsClassName"), "model.UserOptions");
    }

    hidden = svcEl.getBoolean("hidden", false);

    hconf = svcEl.configurationsAt("restApiEndpoint");
    if (!hconf.isEmpty()) {
        for (HierarchicalConfiguration el : hconf) {
            final String name = el.getString("[@name]");
            if (StringUtils.isBlank(name))
                throw new Exception(invalidAttributeValueEx("restApiEndpoint", "name"));
            final String path = el.getString("[@path]", "");

            if (restApiEndpoints.containsKey(path))
                throw new Exception(invalidAttributeValueEx("restApiEndpoint", "path"));
            restApiEndpoints.put(path, new RestApiEndpoint(buildJavaClassName(javaPackage, name), path));
        }
    }

    if (!svcEl.configurationsAt("restApis").isEmpty()) {
        List<HierarchicalConfiguration> restApiEls = svcEl.configurationsAt("restApis.restApi");
        for (HierarchicalConfiguration el : restApiEls) {
            final String oasFile = el.getString("[@oasFile]");
            if (StringUtils.isBlank(oasFile))
                throw new Exception(invalidAttributeValueEx("restApis.restApi", "oasFile"));
            final String context = oasFileToContext(oasFile);
            final String implPackage = el.getString("[@package]", "." + JAVAPKG_REST + "." + context);

            if (restApis.containsKey(oasFile))
                throw new Exception(invalidAttributeValueEx("restApis.restApi", "oasFile"));
            //String oasFilePath = LangUtils.packageToPath(buildJavaPackage(javaPackage, "." + JAVAPKG_REST)) + "/" + oasFile;
            String oasFilePath = LangUtils.packageToPath(javaPackage) + "/" + oasFile;
            restApis.put(oasFile,
                    new RestApi(oasFilePath, context, buildJavaPackage(javaPackage, implPackage)));
        }
    }

    if (!svcEl.configurationsAt("permissions").isEmpty()) {
        List<HierarchicalConfiguration> elPerms = svcEl.configurationsAt("permissions.permission");
        for (HierarchicalConfiguration elPerm : elPerms) {
            if (elPerm.containsKey("[@group]")) {
                String groupName = elPerm.getString("[@group]");
                if (StringUtils.isEmpty(groupName))
                    throw new Exception("Permission must have a valid uppercase group name");

                if (elPerm.containsKey("[@actions]")) {
                    String[] actions = StringUtils.split(elPerm.getString("[@actions]"), ",");
                    if (actions.length == 0)
                        throw new Exception("Resource must declare at least 1 action");
                    permissions.add(new ServicePermission(groupName, actions));
                } else {
                    throw new Exception("Permission must declare actions supported on group");
                }
            }
        }

        List<HierarchicalConfiguration> elShPerms = svcEl.configurationsAt("permissions.sharePermission");
        for (HierarchicalConfiguration elShPerm : elShPerms) {
            if (elShPerm.containsKey("[@group]")) {
                String groupName = elShPerm.getString("[@group]");
                if (StringUtils.isEmpty(groupName))
                    throw new Exception("Permission must have a valid uppercase group name");
                permissions.add(new ServiceSharePermission(groupName));
            }
        }
    }

    if (!svcEl.configurationsAt("portlets").isEmpty()) {
        List<HierarchicalConfiguration> elPortlets = svcEl.configurationsAt("portlets.portlet");
        for (HierarchicalConfiguration el : elPortlets) {
            if (el.containsKey("[@jsClassName]")) {
                final String jsClassName = el.getString("[@jsClassName]");
                if (StringUtils.isBlank(jsClassName))
                    throw new Exception("Invalid value for attribute [portlet->jsClassName]");
                portlets.add(new Portlet(LangUtils.buildClassName(jsPackage, jsClassName)));
            }
        }
    }
}

From source file:info.magnolia.ui.admincentral.setup.JcrBrowserContentAppTask.java

protected void createMainSubapp(Node appNode) throws TaskExecutionException {
    try {//  www  .jav a 2  s  . c  om
        Node subappsNode = NodeUtil.createPath(appNode, "subApps", NodeTypes.ContentNode.NAME);
        subappsNode.setProperty("extends", "/modules/ui-admincentral/apps/configuration/subApps");
        Node contentConnectorNode = NodeUtil.createPath(subappsNode, "browser/contentConnector",
                NodeTypes.ContentNode.NAME);

        if (StringUtils.isBlank(workspace)) {
            throw new TaskExecutionException("workspace cannot be null or empty");
        }
        contentConnectorNode.setProperty("workspace", workspace);

        if (StringUtils.isNotBlank(rootPath)) {
            if (!rootPath.startsWith("/")) {
                throw new TaskExecutionException(
                        String.format("Expected an absolute path for workspace [%s] but got [%s] instead.",
                                workspace, rootPath));
            }
            contentConnectorNode.setProperty("rootPath", rootPath);
        }
        if (mainNodeType != null) {
            Node nodeType = NodeUtil.createPath(contentConnectorNode, "nodeTypes/mainNodeType",
                    NodeTypes.ContentNode.NAME);
            String icon = mainNodeType.getIcon();
            String name = mainNodeType.getName();
            nodeType.setProperty("icon", StringUtils.defaultIfEmpty(icon, "icon-node-content"));
            nodeType.setProperty("name", StringUtils.defaultIfEmpty(name, NodeTypes.ContentNode.NAME));
            nodeType.setProperty("strict", false);
        }
    } catch (RepositoryException e) {
        throw new TaskExecutionException(e.getMessage());
    }
}