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.nuxeo.ecm.platform.ui.web.restAPI.DownloadFileRestlet.java

@Override
public void handle(Request req, Response res) {
    HttpServletRequest request = getHttpRequest(req);
    HttpServletResponse response = getHttpResponse(res);

    String repo = (String) req.getAttributes().get("repo");
    if (repo == null || repo.equals("*")) {
        handleError(res, "you must specify a repository");
        return;/*w ww .  j a  v  a 2s  .  co  m*/
    }

    DocumentModel dm;
    try {
        navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
        documentManager = navigationContext.getOrCreateDocumentManager();
        String docid = (String) req.getAttributes().get("docid");
        if (docid != null) {
            dm = documentManager.getDocument(new IdRef(docid));
        } else {
            handleError(res, "you must specify a valid document IdRef");
            return;
        }
    } catch (NuxeoException e) {
        handleError(res, e);
        return;
    }

    try {
        String blobPropertyName = getQueryParamValue(req, BLOB_PROPERTY_NAME, null);
        String filenamePropertyName = getQueryParamValue(req, FILENAME_PROPERTY_NAME, null);
        Blob blob;
        String xpath;
        String filename;
        if (blobPropertyName != null && filenamePropertyName != null) {
            filename = (String) dm.getPropertyValue(filenamePropertyName);
            blob = (Blob) dm.getPropertyValue(blobPropertyName);
            xpath = blobPropertyName;
        } else {
            String schemaName = getQueryParamValue(req, SCHEMA, DEFAULT_SCHEMA);
            String blobFieldName = getQueryParamValue(req, BLOB_FIELD, DEFAULT_BLOB_FIELD);
            String filenameFieldName = getQueryParamValue(req, FILENAME_FIELD, DEFAULT_FILENAME_FIELD);
            filename = (String) dm.getProperty(schemaName, filenameFieldName);
            blob = (Blob) dm.getProperty(schemaName, blobFieldName);
            xpath = schemaName + ':' + blobFieldName;
        }
        if (StringUtils.isBlank(filename)) {
            filename = StringUtils.defaultIfBlank(blob.getFilename(), "file");
        }

        // trigger download
        String reason = "download";
        Map<String, Serializable> extendedInfos = null;
        DownloadService downloadService = Framework.getService(DownloadService.class);
        downloadService.downloadBlob(request, response, dm, xpath, blob, filename, reason, extendedInfos, null,
                byteRange -> setEntityToBlobOutput(blob, byteRange, res));
    } catch (IOException | NuxeoException e) {
        handleError(res, e);
    }
}

From source file:org.onehippo.forge.document.commenting.cms.impl.DefaultJcrCommentPersistenceManager.java

protected void bindCommentNode(CommentingContext commentingContext, final Node commentNode,
        final CommentItem commentItem) throws RepositoryException {
    commentNode.setProperty(PROP_SUBJECTID, StringUtils.defaultIfBlank(commentItem.getSubjectId(), ""));
    commentNode.setProperty(PROP_AUTHOR, StringUtils.defaultIfBlank(commentItem.getAuthor(), ""));

    Calendar now = Calendar.getInstance();

    if (!commentNode.hasProperty(PROP_CREATED)) {
        commentNode.setProperty(PROP_CREATED, now);
        commentNode.setProperty(PROP_LAST_MODIFIED, now);
    } else {//w  w  w  .j  av  a 2s. co  m
        commentNode.setProperty(PROP_LAST_MODIFIED, now);
    }

    commentNode.setProperty(PROP_CONTENT, StringUtils.defaultIfBlank(commentItem.getContent(), ""));

    Property existingProp;
    Object value;

    for (String propName : commentItem.getAttributeNames()) {
        existingProp = null;

        if (commentNode.hasProperty(propName)) {
            existingProp = commentNode.getProperty(propName);
        }

        if (existingProp != null && existingProp.getDefinition().isProtected()) {
            continue;
        }

        value = commentItem.getAttribute(propName);

        if (value == null) {
            continue;
        }

        if (!value.getClass().isArray()) {
            if (value instanceof String) {
                commentNode.setProperty(propName, (String) value);
            } else if (value instanceof Boolean) {
                commentNode.setProperty(propName, (Boolean) value);
            } else if (value instanceof Long) {
                commentNode.setProperty(propName, (Long) value);
            } else if (value instanceof Double) {
                commentNode.setProperty(propName, (Double) value);
            } else if (value instanceof Calendar) {
                commentNode.setProperty(propName, (Calendar) value);
            }
        } else {
            if (value instanceof String[]) {
                String[] stringValues = (String[]) value;
                Value[] values = new Value[stringValues.length];
                for (int i = 0; i < stringValues.length; i++) {
                    values[i] = commentNode.getSession().getValueFactory().createValue(stringValues[i]);
                }
                commentNode.setProperty(propName, values);
            } else if (value instanceof boolean[]) {
                boolean[] booleanValues = (boolean[]) value;
                Value[] values = new Value[booleanValues.length];
                for (int i = 0; i < booleanValues.length; i++) {
                    values[i] = commentNode.getSession().getValueFactory().createValue(booleanValues[i]);
                }
                commentNode.setProperty(propName, values);
            } else if (value instanceof long[]) {
                long[] longValues = (long[]) value;
                Value[] values = new Value[longValues.length];
                for (int i = 0; i < longValues.length; i++) {
                    values[i] = commentNode.getSession().getValueFactory().createValue(longValues[i]);
                }
                commentNode.setProperty(propName, values);
            } else if (value instanceof double[]) {
                double[] doubleValues = (double[]) value;
                Value[] values = new Value[doubleValues.length];
                for (int i = 0; i < doubleValues.length; i++) {
                    values[i] = commentNode.getSession().getValueFactory().createValue(doubleValues[i]);
                }
                commentNode.setProperty(propName, values);
            } else if (value instanceof Calendar[]) {
                Calendar[] dateValues = (Calendar[]) value;
                Value[] values = new Value[dateValues.length];
                for (int i = 0; i < dateValues.length; i++) {
                    values[i] = commentNode.getSession().getValueFactory().createValue(dateValues[i]);
                }
                commentNode.setProperty(propName, values);
            }
        }
    }
}

From source file:org.onehippo.forge.gallerymagick.core.command.GraphicsMagickCommand.java

/**
 * Constructor with an {@code executable} and a {@code subCommand}.
 * If {@code executable} is null, it tries to find it from a system property keyed by {@link #PROP_EXECUTABLE}.
 * If not found from the system property, it uses the default Graphics Magick executable, {@link #DEFAULT_EXECUTABLE}.
 * @param executable executable of Graphics Magick command
 * @param subCommand sub-command of <code>gm</code> command
 */// www .  ja va  2  s .  co m
public GraphicsMagickCommand(final String executable, final String subCommand) {
    super(StringUtils.defaultIfBlank(getExecutableFromSystemProperty(), DEFAULT_EXECUTABLE),
            StringUtils.defaultIfBlank(subCommand, DEFAULT_SUBCOMMAND_CONVERT));
}

From source file:org.onehippo.forge.gallerymagick.core.command.ImageMagickCommand.java

/**
 * Constructor with an {@code executable} and a {@code subCommand}.
 * If {@code executable} is null, it tries to find it from a system property keyed by {@link #PROP_EXECUTABLE_CONVERT}.
 * If not found from the system property, it uses the default Image Magick convert command executable, {@link #DEFAULT_SUBCOMMAND_CONVERT}.
 * @param executable (optional) executable of ImageMagick command
 * @param subCommand sub-command//  w  w w. ja  va  2  s .c  o  m
 */
public ImageMagickCommand(final String executable, final String subCommand) {
    super(StringUtils.defaultIfBlank(getExecutableFromSystemProperty(subCommand), executable),
            StringUtils.defaultIfBlank(subCommand, DEFAULT_SUBCOMMAND_CONVERT));
}

From source file:org.onehippo.forge.hst.pdf.renderer.servlet.HtmlPDFRenderingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(response instanceof HttpServletResponse)) {
        chain.doFilter(request, response);
        return;//from  w ww. jav  a 2  s  .com
    }

    if (response.isCommitted()) {
        log.warn("The servlet response is already committed for the request: '{}'.",
                ((HttpServletRequest) request).getRequestURI());
        chain.doFilter(request, response);
        return;
    }

    ContentCapturingHttpServletResponse capturingResponse = null;
    InputStream htmlInputStream = null;
    Reader htmlReader = null;
    OutputStream pdfOutputStream = null;

    try {
        capturingResponse = new ContentCapturingHttpServletResponse((HttpServletResponse) response);
        chain.doFilter(request, capturingResponse);

        if (capturingResponse.isWrittenToPrintWriter()) {
            htmlReader = new CharArrayReader(capturingResponse.toCharArray());
        } else {
            htmlInputStream = new ByteArrayInputStream(capturingResponse.toByteArray());
            String characterEncoding = StringUtils.defaultIfBlank(capturingResponse.getCharacterEncoding(),
                    "UTF-8");
            htmlReader = new InputStreamReader(htmlInputStream, characterEncoding);
        }

        capturingResponse.close();
        capturingResponse = null;

        response.setContentType("application/pdf");

        StringBuilder headerValue = new StringBuilder("attachment");
        headerValue.append("; filename=\"").append(getDocumentFilename((HttpServletRequest) request))
                .append("\"");
        ((HttpServletResponse) response).addHeader("Content-Disposition", headerValue.toString());

        pdfOutputStream = response.getOutputStream();
        pdfRenderer.renderHtmlToPDF(htmlReader, true, pdfOutputStream,
                getDocumentURL((HttpServletRequest) request),
                getExternalLinkBaseURL((HttpServletRequest) request));
    } catch (Exception e) {

    } finally {
        if (capturingResponse != null) {
            capturingResponse.close();
        }

        IOUtils.closeQuietly(pdfOutputStream);
        IOUtils.closeQuietly(htmlReader);
        IOUtils.closeQuietly(htmlInputStream);
    }
}

From source file:org.openhab.binding.homematic.internal.communicator.client.BaseRpcClient.java

/**
 * {@inheritDoc}//from w  w w.ja v  a2s  .  co m
 */
@Override
public ServerId getServerId(HmInterface hmInterface) throws HomematicClientException {
    ServerId serverId = null;
    try {
        serverId = new ServerId(getVersion(hmInterface));
    } catch (Exception ex) {
        // ignore, the getVersion method may not be implemented (CCU1)
    }

    if (serverId == null || !serverId.isHomegear()) {
        Map<String, String> deviceDescription = getDeviceDescription(hmInterface, "BidCoS-RF");
        String firmwareVersion = null;
        if (deviceDescription != null) {
            firmwareVersion = deviceDescription.get("FIRMWARE");
        }
        serverId = new ServerId(StringUtils.defaultIfBlank(firmwareVersion, "unknown"));
    }

    return serverId;
}

From source file:org.openhab.binding.homematic.internal.communicator.client.ServerId.java

/**
 * {@inheritDoc}//from  w ww  . ja  v a2s. c  o  m
 */
@Override
public String toString() {
    ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("name", name)
            .append("version", StringUtils.defaultIfBlank(version, "unknown"));
    if (address != null) {
        tsb.append("address", address);
    }
    return tsb.toString();
}

From source file:org.openhab.binding.unifi.internal.api.model.UniFiDevice.java

public String getName() {
    return StringUtils.defaultIfBlank(name, mac);
}

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleParameterValidator.java

/**
 * validate dictionary values//from w ww.j  a v  a2  s  .  c  o m
 */
private <N extends Number> void validateDictionaryValues(
        final ComputationRuleParameter computationRuleParameter,
        final List<ScoringRuleDictionaryElement> dictionaryValues, final Errors errors) {
    final ComputationRuleType fieldType = computationRuleParameter.getComputationRuleType();
    final String paramName = computationRuleParameter.getParameterName();
    if (CollectionUtils.isEmpty(dictionaryValues)) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_REQUIRED, fieldType,
                paramName);
    }

    final Map<String, Collection<ScoringRuleDictionaryElement>> duplicates = Maps.filterEntries(
            Multimaps.index(dictionaryValues, DICTIONARY_ELEMENT_TO_KEY_TRANSFORMER).asMap(),
            KEY_DUPLICATE_FILTER);
    if (!duplicates.isEmpty()) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_DUPLICATES, paramName,
                duplicates.keySet().toString());
    }

    for (int i = 0; i < dictionaryValues.size(); i++) {
        final ScoringRuleDictionaryElement scoringRuleDictionaryElement = dictionaryValues.get(i);
        String key = scoringRuleDictionaryElement.getKey();
        final String value = scoringRuleDictionaryElement.getValue();
        try {
            errors.pushNestedPath(DICTIONARY + "[" + i + "]");

            final DictionaryIndexType dictionaryIndex = computationRuleParameter.getDictionaryIndexType();

            final boolean indexIsInteger = dictionaryIndex == DictionaryIndexType.INTEGER;
            if (!rejectIfEmpty(key, errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY,
                    indexIsInteger ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, i + 1)
                    && indexIsInteger) {
                if (!StringUtils.isNumeric(key)) {
                    rejectValue(errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY + MSG_INVALID, fieldType,
                            paramName, key, dictionaryIndex);
                }
            }

            key = StringUtils.defaultIfBlank(key, String.valueOf(i + 1));

            final boolean valueIsNumeric = NUMERIC_TYPES.contains(fieldType);
            if (!rejectIfEmpty(value, errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE,
                    valueIsNumeric ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, key)
                    && valueIsNumeric) {
                final String min = computationRuleParameter.getMinimumValue();
                final String max = computationRuleParameter.getMaximumValue();
                try {
                    if (fieldType == ComputationRuleType.FLOAT) {
                        final Float floatValue = Float.parseFloat(value);
                        final Range<Float> floatRange = buildFloatRange(min, max);
                        if (floatRange != null && !floatRange.contains(floatValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    } else {
                        final Long longValue = Long.parseLong(value);
                        final Range<Long> longRange = buildLongRange(min, max);
                        if (longRange != null && !longRange.contains(longValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    }
                } catch (final NumberFormatException e) {
                    rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_NUMBER,
                            fieldType, paramName, key, value);
                }
            } else if (ComputationRuleType.BOOLEAN.equals(fieldType)
                    && !Boolean.FALSE.toString().equals(value.toString())
                    && !Boolean.TRUE.toString().equals(value.toString())) {
                rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_BOOLEAN,
                        fieldType, paramName, key, value);
            }
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:org.patientview.patientview.logon.PatientLogonWithTreatment.java

public void setTreatment(String treatment) {
    this.treatment = StringUtils.defaultIfBlank(treatment, "");
}