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

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

Introduction

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

Prototype

public static String defaultString(final String str, final String defaultStr) 

Source Link

Document

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

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

Usage

From source file:io.wcm.handler.mediasource.dam.impl.RenditionMetadata.java

/**
 * @param rendition DAM rendition/*from   ww w.j av a 2  s .c  o m*/
 */
public RenditionMetadata(Rendition rendition) {
    this.rendition = rendition;

    // check if rendition is original image
    boolean isOriginal = isOriginalRendition(rendition);
    Asset asset = rendition.getAsset();

    // get filename and extension
    String renditionName = rendition.getName();
    if (isOriginal) {
        renditionName = asset.getName();
    }
    this.fileName = renditionName;
    this.fileExtension = StringUtils.substringAfterLast(renditionName, ".");

    // get image width/height
    int imageWidth = 0;
    int imageHeight = 0;
    if (isOriginal) {
        // get width/height from metadata for original renditions
        try {
            imageWidth = Integer.parseInt(
                    StringUtils.defaultString(asset.getMetadataValue(DamConstants.TIFF_IMAGEWIDTH), "0"));
        } catch (NumberFormatException ex) {
            // ignore
        }
        if (imageWidth == 0) {
            try {
                imageWidth = Integer.parseInt(StringUtils
                        .defaultString(asset.getMetadataValue(DamConstants.EXIF_PIXELXDIMENSION), "0"));
            } catch (NumberFormatException ex) {
                // ignore
            }
        }
        try {
            imageHeight = Integer.parseInt(
                    StringUtils.defaultString(asset.getMetadataValue(DamConstants.TIFF_IMAGELENGTH), "0"));
        } catch (NumberFormatException ex) {
            // ignore
        }
        if (imageHeight == 0) {
            try {
                imageHeight = Integer.parseInt(StringUtils
                        .defaultString(asset.getMetadataValue(DamConstants.EXIF_PIXELYDIMENSION), "0"));
            } catch (NumberFormatException ex) {
                // ignore
            }
        }
    } else if (FileExtension.isImage(this.fileExtension)) {
        // otherwise get from rendition metadata written by {@link DamRenditionMetadataService}
        String metadataPath = JcrConstants.JCR_CONTENT + "/"
                + DamRenditionMetadataService.NN_RENDITIONS_METADATA + "/" + rendition.getName();
        Resource metadataResource = asset.adaptTo(Resource.class).getChild(metadataPath);
        if (metadataResource != null) {
            ValueMap props = metadataResource.getValueMap();
            imageWidth = props.get(DamRenditionMetadataService.PN_IMAGE_WIDTH, 0);
            imageHeight = props.get(DamRenditionMetadataService.PN_IMAGE_HEIGHT, 0);
        }
    }
    this.width = imageWidth;
    this.height = imageHeight;
}

From source file:io.wcm.handler.media.markup.DummyImageMediaMarkupBuilder.java

@Override
public HtmlElement<?> build(Media media) {

    // Create dummy image element to be displayed in Edit mode as placeholder.
    Dimension dimension = MediaMarkupBuilderUtil.getMediaformatDimension(media);
    MediaArgs mediaArgs = media.getMediaRequest().getMediaArgs();

    // create dummy image
    String dummyImageUrl = StringUtils.defaultString(mediaArgs.getDummyImageUrl(), DUMMY_IMAGE);
    dummyImageUrl = urlHandler.get(dummyImageUrl).urlMode(media.getMediaRequest().getMediaArgs().getUrlMode())
            .buildExternalResourceUrl();
    Image image = new Image(dummyImageUrl, dimension.getWidth(), dimension.getHeight())
            .addCssClass(MediaNameConstants.CSS_DUMMYIMAGE);

    // set additional attributes
    setAdditionalAttributes(image, media);

    // enable drag&drop for media source - if none is specified use first one defined in config
    MediaSource mediaSource = media.getMediaSource();
    if (mediaSource == null && !mediaHandlerConfig.getSources().isEmpty()) {
        Class<? extends MediaSource> mediaSourceClass = mediaHandlerConfig.getSources().iterator().next();
        mediaSource = AdaptTo.notNull(adaptable, mediaSourceClass);
    }/*from  w  ww.j a va 2 s .  co m*/
    if (mediaSource != null) {
        mediaSource.enableMediaDrop(image, media.getMediaRequest());
    }

    return image;
}

From source file:io.wcm.caravan.io.http.request.CaravanHttpRequest.java

/**
 * @param serviceId Logical name of the request service. Used by {@link CaravanHttpClient} to resolve the real URL.
 *          If null, only {@code url} is used
 * @param method HTTP method verb/* w w w  . j av  a  2s .co m*/
 * @param url Service request URL. Can be an absolute URL or just an path getting combined with the URL of the logical
 *          service ID
 * @param headers HTTP headers
 * @param body HTTP Payload
 * @param charset Payload charset
 */
CaravanHttpRequest(final String serviceId, final String method, final String url,
        final Multimap<String, String> headers, final byte[] body, final Charset charset) {
    this.serviceId = serviceId; // nullable
    this.method = checkNotNull(method, "method of %s", url);
    this.url = checkNotNull(url, "url");
    this.headers = ImmutableMultimap
            .copyOf(LinkedHashMultimap.create(checkNotNull(headers, "headers of %s %s", method, url)));
    this.body = body; // nullable
    this.charset = charset; // nullable
    this.performanceMetrics = PerformanceMetrics
            .createNew(StringUtils.defaultString(serviceId, "UNKNOWN SERVICE") + " : "
                    + StringUtils.defaultString(method, "UNKNOWN METHOD"), url, getCorrelationId());
}

From source file:com.cognifide.qa.bb.provider.http.HttpClientProvider.java

private AuthScope getAuthScope(String urlString) {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    try {/*from www .ja  va 2s .c  om*/
        URI uri = new URI(urlString);
        host = StringUtils.defaultString(uri.getHost(), AuthScope.ANY_HOST);
        port = uri.getPort();
    } catch (URISyntaxException e) {
        LOG.error("Could not parse '{}' as a valid URI", urlString, e);
    }
    return new AuthScope(host, port);
}

From source file:com.mirth.connect.util.CodeTemplateUtil.java

public static String updateCode(String code) {
    if (StringUtils.isNotBlank(code)) {
        code = StringUtils.trim(code);/*from ww  w.j a v a2s .c o  m*/
        int endIndex = 0;
        Matcher matcher = COMMENT_PATTERN.matcher(code);
        if (matcher.find()) {
            endIndex = matcher.end();
        }

        CodeTemplateDocumentation documentation = getDocumentation(code);
        String description = documentation.getDescription();
        CodeTemplateFunctionDefinition functionDefinition = documentation.getFunctionDefinition();

        if (StringUtils.isBlank(description)) {
            description = "Modify the description here. Modify the function name and parameters as needed. One function per template is recommended; create a new code template for each new function.";
        }

        StringBuilder builder = new StringBuilder("/**");

        for (String descriptionLine : description.split("\r\n|\r|\n")) {
            builder.append("\n\t").append(WordUtils.wrap(descriptionLine, 100, "\n\t", false));
        }

        if (functionDefinition != null) {
            builder.append('\n');

            if (CollectionUtils.isNotEmpty(functionDefinition.getParameters())) {
                for (Parameter parameter : functionDefinition.getParameters()) {
                    StringBuilder parameterBuilder = new StringBuilder("\n\t@param {");
                    parameterBuilder.append(StringUtils.defaultString(parameter.getType(), "Any"));
                    parameterBuilder.append("} ").append(parameter.getName()).append(" - ")
                            .append(StringUtils.trimToEmpty(parameter.getDescription()));

                    builder.append(WordUtils.wrap(parameterBuilder.toString(), 100, "\n\t\t", false));
                }
            }

            StringBuilder returnBuilder = new StringBuilder("\n\t@return {")
                    .append(StringUtils.defaultString(functionDefinition.getReturnType(), "Any")).append("} ")
                    .append(StringUtils.trimToEmpty(functionDefinition.getReturnDescription()));

            builder.append(WordUtils.wrap(returnBuilder.toString(), 100, "\n\t\t", false));
        }

        builder.append("\n*/\n");

        return builder.toString() + code.substring(endIndex);
    }

    return code;
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.XmlContentBuilder.java

/**
 * Build XML for any JCR content.//from  w w  w .  j  av a 2 s  .c  om
 * @param content Content with properties and nested nodes
 * @return JCR XML
 */
public Document buildContent(Map<String, Object> content) {
    Document doc = documentBuilder.newDocument();

    String primaryType = StringUtils.defaultString((String) content.get(PN_PRIMARY_TYPE), NT_UNSTRUCTURED);
    Element jcrRoot = createJcrRoot(doc, primaryType);

    exportPayload(doc, jcrRoot, content);

    return doc;
}

From source file:com.mirth.connect.client.ui.components.rsta.ac.js.MirthJavaScriptBasicCompletion.java

@Override
public String getInputText() {
    return StringUtils.defaultString(inputText, super.getInputText());
}

From source file:info.magnolia.test.fixture.JcrPropertyServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String path = request.getParameter("path");
    final String workspace = StringUtils.defaultString(request.getParameter("workspace"),
            RepositoryConstants.CONFIG);
    final String value = request.getParameter("value");
    final boolean delete = Boolean.valueOf(request.getParameter("delete"));
    final String nodePath = StringUtils.substringBeforeLast(path, "/");
    final String propertyName = StringUtils.substringAfterLast(path, "/");
    try {// ww w  .ja v  a2 s.co m
        final Node node = SessionUtil.getNode(workspace, nodePath);
        if (node == null) {
            throw new ServletException("Node does not exist [" + nodePath + "]");
        }

        final String returnValue = PropertyUtil.getString(node, propertyName);

        if (value != null) {
            node.setProperty(propertyName, value);
            node.getSession().save();
            log.info("Changing value of '{}' from [{}] to [{}]", path, returnValue, value);
        } else if (delete) {
            if (node.hasProperty(propertyName)) {
                Property property = node.getProperty(propertyName);
                property.remove();
                node.getSession().save();
                log.info("Removed property '{}' from [{}].", propertyName, path);
            } else {
                log.info("No property '{}' found at [{}].", propertyName, path);
            }
        }

        response.getWriter().write(String.valueOf(returnValue));
    } catch (RepositoryException e) {
        log.warn("Could not handle property [{}] from workspace [{}]", new Object[] { path, workspace });
        throw new ServletException("Could not read property [" + path + "]");
    }
}

From source file:cop.raml.utils.javadoc.MethodJavaDoc.java

@NotNull
private static TagReturn getReturn(List<String> doc) {
    if (CollectionUtils.isEmpty(doc))
        return TagReturn.NULL;

    Matcher matcher;//from  w w w  .ja  v  a2  s  . c om
    StringBuilder buf = null;

    for (String line : doc) {
        line = line.trim();

        if ((matcher = JavaDocTag.RETURN.getPattern().matcher(line)).find())
            buf = new StringBuilder(StringUtils.defaultString(matcher.group("text"), ""));
        else if (buf != null) {
            if (TAG.matcher(line).find())
                return createTagReturn(buf.toString());

            buf.append(buf.length() > 0 ? '\n' : "").append(line);
        }
    }

    return createTagReturn(buf != null ? buf.toString() : null);
}

From source file:io.wcm.config.core.impl.PathApplicationProvider.java

@Override
public String getLabel() {
    return StringUtils.defaultString(label, applicationId);
}