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

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

Introduction

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

Prototype

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

Source Link

Document

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

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

Usage

From source file:org.phenotips.vocabulary.internal.solr.OrphanetRareDiseaseOntology.java

/**
 * Adds dynamic solr query parameters to {@code query}, based on the received {@code rawQuery raw query string},
 * {@code rows the maximum number of results to return}, {@code sort the sorting order}, and {@code customFilter a
 * custom filter}./* ww w  . j  av a  2s  . c  om*/
 *
 * @param rawQuery unprocessed query string
 * @param rows the maximum number of search items to return
 * @param sort the optional sort parameter
 * @param customFilter custom filter for the results
 * @param query a {@link SolrQuery solr query} object
 * @return the updated {@link SolrQuery solr query} object
 */
private SolrQuery addDynamicQueryParam(@Nonnull final String rawQuery, final Integer rows,
        @Nullable final String sort, @Nullable final String customFilter, @Nonnull SolrQuery query) {
    final String queryString = rawQuery.trim();
    final String escapedQuery = ClientUtils.escapeQueryChars(queryString);
    if (StringUtils.isNotBlank(customFilter)) {
        query.setFilterQueries(customFilter);
    }
    query.setQuery(escapedQuery);
    query.set(SpellingParams.SPELLCHECK_Q, queryString);
    final String lastWord = StringUtils.defaultIfBlank(StringUtils.substringAfterLast(escapedQuery, " "),
            escapedQuery) + "*";
    query.set(DisMaxParams.BQ,
            String.format("nameSpell:%1$s^20 defSpell:%1$s^3 text:%1$s^1 textSpell:%1$s^2", lastWord));
    query.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        for (final String sortItem : sort.split("\\s*,\\s*")) {
            query.addSort(StringUtils.substringBefore(sortItem, " "),
                    sortItem.endsWith(" desc") || sortItem.startsWith("-") ? ORDER.desc : ORDER.asc);
        }
    }
    return query;
}

From source file:org.polymap.p4.data.importer.wfs.WfsImporter.java

protected String normalize(String s) {
    return StringUtils.defaultIfBlank(s, null);
}

From source file:org.polymap.p4.data.importer.wms.OwsMetadata.java

public OwsMetadata markdown(ResponsibleParty party) {
    if (party != null) {
        //markdownH3( i18n.get( "contactInfo" ) );
        markdownH3(//  ww  w .j  av  a 2  s .c  o  m
                StringUtils.defaultIfBlank(party.getOrganisationName().toString(), party.getIndividualName()));
        markdownListItem( /*"individualName",*/ party.getIndividualName());
        //markdownListItem( "organisationName", party.getOrganisationName() );
        markdownListItem( /*"positionName",*/ party.getPositionName());
        buf.append("\n");

        markdown(party.getContactInfo());
    }
    return this;
}

From source file:org.polymap.rhei.batik.engine.DefaultBrowserNavigation.java

protected void pushState(String state, String title) {
    assert !StringUtils.isBlank(state);
    title = NO_TITLE_CHAR.matcher(StringUtils.defaultIfBlank(title, "-")).replaceAll("");
    log.debug("pushState(): " + state + " / " + title);
    js.execute(Joiner.on("").useForNull("").join("window.history.pushState({},'", title, "','#", state, "');"));
    //"document.title='", title , "';" ) );
}

From source file:org.polymap.rhei.batik.engine.DefaultBrowserNavigation.java

protected void replaceState(String state, String title) {
    assert !StringUtils.isBlank(state);
    title = NO_TITLE_CHAR.matcher(StringUtils.defaultIfBlank(title, "-")).replaceAll("");
    log.debug("replaceState(): " + state + " / " + title);
    js.execute(//from   w ww  .j  a va 2s.co m
            Joiner.on("").useForNull("").join("window.history.replaceState({},'", title, "','#", state, "');"));
    //"document.title='", title , "';" ) );
}

From source file:org.primefaces.extensions.component.dynaform.DynaFormRenderer.java

protected void encodeBody(final FacesContext fc, final DynaForm dynaForm, final List<DynaFormRow> dynaFormRows,
        final boolean extended, final boolean visible) throws IOException {
    if (dynaFormRows == null || dynaFormRows.isEmpty()) {
        return;/* w w  w .  j a v a2  s. com*/
    }

    final ResponseWriter writer = fc.getResponseWriter();

    final String columnClassesValue = dynaForm.getColumnClasses();
    final String[] columnClasses = columnClassesValue == null ? EMPTY_COLUMN_CLASSES
            : columnClassesValue.split(",");
    final String labelCommonClass = columnClasses[0].trim();
    final String controlCommonClass = columnClasses.length > 1 ? columnClasses[1].trim()
            : EMPTY_COLUMN_CLASSES[1];

    for (final DynaFormRow dynaFormRow : dynaFormRows) {
        writer.startElement("tr", null);
        if (extended) {
            writer.writeAttribute("class", EXTENDED_ROW_CLASS, null);
        }

        if (!visible) {
            writer.writeAttribute("style", "display:none;", null);
        }

        writer.writeAttribute("role", "row", null);

        final List<AbstractDynaFormElement> elements = dynaFormRow.getElements();
        final int size = elements.size();

        for (int i = 0; i < size; i++) {
            final AbstractDynaFormElement element = elements.get(i);

            writer.startElement("td", null);
            if (element.getColspan() > 1) {
                writer.writeAttribute("colspan", element.getColspan(), null);
            }

            if (element.getRowspan() > 1) {
                writer.writeAttribute("rowspan", element.getRowspan(), null);
            }

            String styleClass = CELL_CLASS;
            if (i == 0 && element.getColspan() == 1) {
                styleClass = styleClass + " " + CELL_FIRST_CLASS;
            }

            if (i == size - 1 && element.getColspan() == 1) {
                styleClass = styleClass + " " + CELL_LAST_CLASS;
            }

            if (element instanceof DynaFormLabel) {
                // render label
                final DynaFormLabel label = (DynaFormLabel) element;

                writer.writeAttribute("class",
                        (styleClass + " " + LABEL_CLASS + " "
                                + StringUtils.defaultIfBlank(label.getStyleClass(), Constants.EMPTY_STRING)
                                + " " + labelCommonClass).trim(),
                        null);
                writer.writeAttribute("role", GRID_CELL_ROLE, null);

                writer.startElement("label", null);
                if (!label.isTargetValid()) {
                    writer.writeAttribute("class", LABEL_INVALID_CLASS, null);
                }

                writer.writeAttribute("for", label.getTargetClientId(), null);

                if (label.getValue() != null) {
                    if (label.isEscape()) {
                        writer.writeText(label.getValue(), "value");
                    } else {
                        writer.write(label.getValue());
                    }
                }

                if (label.isTargetRequired()) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", LABEL_INDICATOR_CLASS, null);
                    writer.write("*");
                    writer.endElement("span");
                }

                writer.endElement("label");
            } else if (element instanceof DynaFormControl) {
                // render control
                final DynaFormControl control = (DynaFormControl) element;
                dynaForm.setData(control);

                // find control's cell by type
                final UIDynaFormControl cell = dynaForm.getControlCell(control.getType());

                if (cell.getStyle() != null) {
                    writer.writeAttribute("style", cell.getStyle(), null);
                }

                if (cell.getStyleClass() != null) {
                    styleClass = styleClass + " " + cell.getStyleClass();
                }

                writer.writeAttribute("class", (styleClass + " " + controlCommonClass).trim(), null);
                writer.writeAttribute("role", GRID_CELL_ROLE, null);

                cell.encodeAll(fc);
            } else if (element instanceof DynaFormModelElement) {
                final DynaFormModelElement nestedModel = (DynaFormModelElement) element;

                // render nested model
                writer.writeAttribute("class", styleClass, null);
                writer.writeAttribute("role", GRID_CELL_ROLE, null);

                encodeMarkup(fc, dynaForm, nestedModel.getModel(), true);
            }

            writer.endElement("td");
        }

        writer.endElement("tr");
    }

    dynaForm.resetData();
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
public String getGradeForSubmitter(AssignmentSubmission submission, String submitter) {
    if (submission == null || StringUtils.isBlank(submitter))
        return null;

    String grade = null;//from www .j a va 2s . c  o m
    Assignment assignment = submission.getAssignment();

    // if this assignment is associated to the gradebook always use that score first
    String gradebookAssignmentName = assignment.getProperties()
            .get(PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT);
    if (StringUtils.isNotBlank(gradebookAssignmentName) && !gradebookExternalAssessmentService
            .isExternalAssignmentDefined(assignment.getContext(), gradebookAssignmentName)) {
        // associated gradebook item
        grade = gradebookService.getAssignmentScoreStringByNameOrId(assignment.getContext(),
                gradebookAssignmentName, submitter);
    }

    if (StringUtils.isNotBlank(grade)) {
        // exists a grade in the gradebook so we use that
        if (StringUtils.isNumeric(grade)) {
            Integer score = Integer.parseInt(grade);
            // convert gradebook to an asssignments score using the scale factor
            grade = Integer.toString(score * assignment.getScaleFactor());
        }
    } else {
        // otherwise use grade maintained by assignments or is considered externally mananged or is not released
        grade = submission.getGrade(); // start with submission grade
        if (assignment.getIsGroup()) {
            Optional<AssignmentSubmissionSubmitter> submissionSubmitter = submission.getSubmitters().stream()
                    .filter(s -> s.getSubmitter().equals(submitter)).findAny();
            if (submissionSubmitter.isPresent()) {
                grade = StringUtils.defaultIfBlank(submissionSubmitter.get().getGrade(), grade); // if there is a grade override use that
            }
        }
    }

    Integer scale = assignment.getScaleFactor() != null ? assignment.getScaleFactor() : getScaleFactor();
    grade = getGradeDisplay(grade, assignment.getTypeOfGrade(), scale);

    return grade;
}

From source file:org.sejda.conversion.PdfFileSourceListAdapter.java

/**
 * Parse fileset definitions <filelist><fileset>[...]</fileset></filelist> ignoring the rest of the document
 * /*from w ww . j a v a 2  s . c o  m*/
 * @param doc
 * @return a list of string matching the contents of the <filelist><fileset> tags in the document
 * @throws XPathExpressionException
 */
private List<String> parseFileSets(Document doc, File configFile) throws XPathExpressionException {
    List<String> result = new ArrayList<>();

    NodeList nodeList = getNodeListMatchingXpath("//filelist/fileset/file", doc);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Node fileSet = node.getParentNode();

        String parentDirPath = nullSafeGetStringAttribute(fileSet, "dir");
        if (parentDirPath == null) {
            parentDirPath = configFile.getAbsoluteFile().getParent();
        }

        String filePath = extractFilePath(node);

        // warn if file in fileset is using absolute path mode
        if (FilenameUtils.getPrefixLength(filePath) > 0) {
            LOG.warn("File " + filePath + " in fileset "
                    + StringUtils.defaultIfBlank(nullSafeGetStringAttribute(fileSet, "dir"), "")
                    + " seems to be an absolute path. Will _not_ be resolved relative to the <fileset>, but as an absolute path. Normally you would want to use relative paths in a //filelist/fileset/file, and absolute paths in a //filelist/file.");
        }

        result.add(FilenameUtils.concat(parentDirPath, filePath));
    }

    return result;
}

From source file:org.sejda.core.support.prefix.processor.PrefixUtils.java

/**
 * Strips characters deemed usafe for a filename
 */// w w w . ja va 2  s .c  o m
public static String toSafeFilename(String input) {
    return StringUtils.defaultIfBlank(input, "").replaceAll("[`\0\f\t\n\r\\\\/:*?\\\"<>|]", "");
}

From source file:org.sejda.core.support.prefix.processor.PrefixUtils.java

/**
 * Strips all but characters that are known to be safe: alphanumerics for now.
 *//*  w ww.j  a  va2s  . c o m*/
public static String toStrictFilename(String input) {
    String safe = StringUtils.defaultIfBlank(input, "").replaceAll("[^A-Za-z0-9_ .-]", "");
    if (safe.length() > 255) {
        safe = safe.substring(0, 255);
    }
    return safe;
}