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:ductive.console.commands.register.spring.ArgumentParserBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {
        @Override//from   w  w w . ja  v  a 2  s.c  om
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            ArgParser argParser = AnnotationUtils.findAnnotation(method, ArgParser.class);
            if (argParser == null)
                return;

            String qualifier = StringUtils.defaultIfEmpty(argParser.value(), null);

            if (!void.class.equals(argParser.bind())) {
                argParserRegistry.register(argParser.bind(), qualifier, bean, method);
                return;
            }

            Type genericReturnType = method.getGenericReturnType();
            Validate.isTrue(ParameterizedType.class.isInstance(genericReturnType),
                    String.format(
                            "method %s: return type of parser generator method must be a subclass of %s<?>",
                            method, Parser.class.getCanonicalName()));

            ParameterizedType pt = ParameterizedType.class.cast(genericReturnType);
            Validate.isTrue(Parser.class.isAssignableFrom((Class<?>) pt.getRawType()),
                    String.format(
                            "method %s: return type of parser generator method must be a subclass of %s<?>",
                            method, Parser.class.getCanonicalName()));

            Type[] genericParams = pt.getActualTypeArguments();
            Validate.isTrue(genericParams.length == 1);

            argParserRegistry.register((Class<?>) genericParams[0], qualifier, bean, method);
        }

    });
    return bean;
}

From source file:net.siegmar.japtproxy.JaptProxyServer.java

/**
 * Starts Jetty./*from  www .ja va2  s  .  c  o  m*/
 *
 * @param host        the host to bound.
 * @param port        the port to bound.
 * @param contextPath the context path to bound.
 */
private static void startServer(final String host, final int port, final String contextPath) {
    final Logger log = LoggerFactory.getLogger(JaptProxyServer.class);
    log.info("Starting Japt-Proxy {} on host {} port {} using context path '{}'", Util.VERSION,
            StringUtils.defaultIfEmpty(host, "*"), port, contextPath);

    // Spring startup
    final ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
            "master.xml", "standalone.xml");
    classPathXmlApplicationContext.registerShutdownHook();

    // Jetty startup
    final Server server = new Server();

    final Connector connector = new BlockingChannelConnector();

    if (!StringUtils.isBlank(host)) {
        connector.setHost(host);
    }

    connector.setPort(port);
    server.setConnectors(new Connector[] { connector });

    server.setStopAtShutdown(true);

    final Context root = new Context(server, contextPath);
    final JaptProxyServlet japtProxyServlet = classPathXmlApplicationContext.getBean("japtProxyServlet",
            JaptProxyServlet.class);
    root.addServlet(new ServletHolder(japtProxyServlet), "/*");

    try {
        server.start();
    } catch (final Exception e) {
        // shame on Jetty's exception handling
        throw new IllegalStateException("Couldn't start HTTP engine", e);
    }
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v1.TitleImpl.java

@PostConstruct
private void initModel() {
    if (StringUtils.isBlank(title)) {
        title = StringUtils.defaultIfEmpty(currentPage.getPageTitle(), currentPage.getTitle());
    }//from   w ww .java  2 s .c  o m

    if (heading == null) {
        heading = Utils.Heading.getHeading(type);
        if (heading == null) {
            heading = Utils.Heading.getHeading(currentStyle.get(PN_DESIGN_DEFAULT_TYPE, String.class));
        }
    }

    if (StringUtils.isNotEmpty(linkURL)) {
        linkURL = Utils.getURL(request, pageManager, linkURL);
    } else {
        linkURL = null;
    }

    if (currentStyle != null) {
        linkDisabled = currentStyle.get(Title.PN_TITLE_LINK_DISABLED, linkDisabled);
    }
}

From source file:com.yqboots.web.thymeleaf.processor.element.PaginationElementProcessor.java

/**
 * {@inheritDoc}//from  w  w w  .  j ava  2  s  .  co m
 */
@Override
protected List<Node> getMarkupSubstitutes(final Arguments arguments, final Element element) {
    final List<Node> nodes = new ArrayList<>();

    final Configuration configuration = arguments.getConfiguration();

    // Obtain the attribute value
    final IWebContext context = (IWebContext) arguments.getContext();
    final String contextPath = StringUtils.defaultIfEmpty(
            element.getAttributeValue(SpringHrefAttrProcessor.ATTR_NAME),
            context.getServletContext().getContextPath());

    // Obtain the Thymeleaf Standard Expression parser
    final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
    // Parse the attribute value as a Thymeleaf Standard Expression
    final String pageAttrValue = element.getAttributeValue(ATTR_PAGE);
    final IStandardExpression expression = parser.parseExpression(configuration, arguments, pageAttrValue);
    Page<?> page = (Page<?>) expression.execute(configuration, arguments);

    final Element container = new Element("ul");
    container.setAttribute("class", "pagination");

    container.addChild(getFirstElement(page, contextPath));
    container.addChild(getPreviousElement(page, contextPath));
    addStepElements(page, contextPath, container);
    container.addChild(getNextElement(page, contextPath));
    container.addChild(getLastElement(page, contextPath));

    nodes.add(container);

    return nodes;
}

From source file:com.adaptris.core.services.metadata.PayloadFromMetadataService.java

/**
 * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage)
 *//* w  w  w  .  ja  v  a2  s. co m*/
public void doService(AdaptrisMessage msg) throws ServiceException {
    String payload = msg.resolve(StringUtils.defaultIfEmpty(template, ""), dotAll());
    for (KeyValuePair kvp : getMetadataTokens().getKeyValuePairs()) {
        if (msg.getMetadataValue(kvp.getKey()) != null) {
            if (!quiet()) {
                log.trace("Replacing {} with {}", kvp.getValue(), msg.getMetadataValue(kvp.getKey()));
            }
            payload = payload.replaceAll(kvp.getValue(), munge(msg.getMetadataValue(kvp.getKey())));
        } else {
            if (!quiet()) {
                log.trace("{} returns no value; no substitution", kvp.getKey());
            }
        }
    }
    msg.setContent(payload, msg.getContentEncoding());
}

From source file:com.xpn.xwiki.web.sx.SxDocumentSource.java

/**
 * {@inheritDoc}/*w  w  w .  ja  v  a  2s . c  o m*/
 * 
 * @see SxSource#getCachePolicy()
 */
public CachePolicy getCachePolicy() {
    CachePolicy finalCache = CachePolicy.LONG;

    if (this.document.getObjects(this.extension.getClassName()) != null) {
        for (BaseObject sxObj : this.document.getObjects(this.extension.getClassName())) {
            if (sxObj == null) {
                continue;
            }
            try {
                CachePolicy cache = CachePolicy.valueOf(StringUtils.upperCase(
                        StringUtils.defaultIfEmpty(sxObj.getStringValue(CACHE_POLICY_PROPERTY_NAME), "LONG")));
                if (cache.compareTo(finalCache) > 0) {
                    finalCache = cache;
                }
            } catch (Exception ex) {
                LOGGER.warn("SX object [{}#{}] has an invalid cache policy: [{}]",
                        new Object[] { this.document.getFullName(), sxObj.getStringValue("name"),
                                sxObj.getStringValue(CACHE_POLICY_PROPERTY_NAME) });
            }
        }
    }
    return finalCache;
}

From source file:com.ejisto.modules.vertx.handler.service.ContainerService.java

private void downloadAndInstallContainer(HttpServerRequest request) {
    final MultiMap params = request.params();
    String url = StringUtils.defaultIfEmpty(params.get("url"),
            settingsManager.getValue("container.default.url"));

    final Optional<Container> defaultContainer = Optional.ofNullable(params.get("defaultContainer"))
            .filter(Boolean::parseBoolean)
            .map(x -> containersRepository.safeLoadContainer(DEFAULT_CONTAINER_ID.getValue()));

    if (defaultContainer.isPresent()) {
        writeError(request, BAD_REQUEST.code(), BAD_REQUEST.reasonPhrase());
        return;/*  ww  w  .j a  v a  2  s .  com*/
    }

    taskManager.addNewTask(new BackgroundTask<>(() -> {
        try {
            final ContainerType containerType;
            if (!StringUtils.isEmpty(params.get("containerType"))) {
                containerType = ContainerType.valueOf(params.get("containerType"));
            } else {
                containerType = ContainerType.fromCargoId(DEFAULT_CARGO_ID.getValue());
            }
            containerManager.downloadAndInstall(url, System.getProperty(CONTAINERS_HOME_DIR.getValue()),
                    containerType);
            settingsManager.putValue(DEFAULT_CONTAINER_DOWNLOAD_URL, url);
            request.response().setStatusCode(OK.code()).setStatusMessage(OK.reasonPhrase()).end();
        } catch (DownloadFailed e) {
            log.debug("got DownloadFailed exception", e);
            writeError(request, NOT_FOUND.code(), NOT_FOUND.reasonPhrase());
        } catch (Exception e) {
            log.debug("got Exception", e);
            writeError(request, e);
        }
        return null;
    }));
}

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

/**
 * @param appName a string representing a unique name for this app. If not unique, the task will fail.
 * @param label the app label to be displayed in the app launcher.
 * @param appGroup a string representing one of the default app groups (i.e. <code>edit, manage, dev, tools</code>) or a custom one (which is assumed to be already existing when running this task).
 * @param icon a string representing an icon. If not set defaults to <code>icon-app</code>.
 * @param workspace name of the workspace. If null or empty the task will fail.
 * @param absRootPath the absolute path to use as the root for the content app to be created. If not set, defaults to <code>/</code>. If not absolute, the task will fail.
 */// w w  w. j  a  v  a 2s  .  c o  m
public JcrBrowserContentAppTask(String appName, String label, String appGroup, String icon, String workspace,
        String absRootPath) {
    super("JCR browser app",
            String.format(
                    "Creates a JCR browser content app named '%s' for workspace '%s' starting at path '%s'.",
                    appName, workspace, StringUtils.defaultIfEmpty(absRootPath, "/")));

    this.appName = appName;
    this.label = label;
    this.appGroup = appGroup;
    this.icon = icon;
    this.workspace = workspace;
    this.rootPath = absRootPath;
}

From source file:com.esri.geoportal.harvester.folder.FolderBroker.java

private File generateFileName(URI brokerUri, URI sourceUri, String id) {
    URI ssp = URI.create(brokerUri.getSchemeSpecificPart());
    String root = StringUtils.defaultIfEmpty(ssp.getHost(), ssp.getPath());
    File rootFolder = definition.getRootFolder().toPath().resolve(root).toFile();

    File fileName = rootFolder;//from   ww  w.  ja v  a2s .c  o m
    if (sourceUri.getPath() != null) {
        List<String> subFolder = splitPath(sourceUri.getPath().replaceAll("/[a-zA-Z]:/|/$", ""));
        if (!subFolder.isEmpty() && subFolder.get(0).equals(root)) {
            subFolder.remove(0);
        }
        for (String sf : subFolder) {
            fileName = new File(fileName, sf);
        }
        if (!fileName.getName().contains(".")) {
            fileName = fileName.getParentFile().toPath().resolve(fileName.getName() + ".xml").toFile();
        }
    } else {
        fileName = new File(fileName, id + ".xml");
    }

    return fileName;
}

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

/**
 * Constructor allowing the description, servername and server to be set
 * //  www. jav a2 s. c  o  m
 * @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(String implementationDescription, String serverName,
        String serverVersion) {
    serverConfiguration.setFhirContext(getFhirContext());
    serverConfiguration.setImplementationDescription(StringUtils.defaultIfEmpty(implementationDescription, ""));
    serverConfiguration.setServerName(StringUtils.defaultIfEmpty(serverName, ""));
    serverConfiguration.setServerVersion(StringUtils.defaultIfEmpty(serverVersion, ""));
}