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

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

Introduction

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

Prototype

public static String trimToEmpty(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null .

Usage

From source file:com.mirth.connect.client.ui.Frame.java

/**
 * Alerts the user with an exception dialog with the passed in stack trace.
 *///from  w  ww.j  a  va2s .  c  o m
public void alertThrowable(Component parentComponent, Throwable t, String customMessage,
        boolean showMessageOnForbidden, String safeErrorKey) {
    if (connectionError) {
        return;
    }

    if (safeErrorKey != null) {
        increaseSafeErrorFailCount(safeErrorKey);

        if (getSafeErrorFailCount(safeErrorKey) < 3) {
            return;
        }
    }

    parentComponent = getVisibleComponent(parentComponent);
    String message = StringUtils.trimToEmpty(customMessage);
    boolean showDialog = true;

    if (t != null) {
        // Always print the stacktrace for troubleshooting purposes
        t.printStackTrace();

        if (t instanceof ExecutionException && t.getCause() != null) {
            t = t.getCause();
        }
        if (t.getCause() != null && t.getCause() instanceof ClientException) {
            t = t.getCause();
        }

        if (StringUtils.isBlank(message) && StringUtils.isNotBlank(t.getMessage())) {
            message = t.getMessage();
        }

        /*
         * Logout if an exception occurs that indicates the server is no longer running or
         * accessible. We only want to do this if a ClientException was passed in, indicating it
         * was actually due to a request to the server. Other places in the application could
         * call this method with an exception that happens to contain the string
         * "Connection reset", for example.
         */
        if (t instanceof ClientException) {
            if (t instanceof ForbiddenException
                    || t.getCause() != null && t.getCause() instanceof ForbiddenException) {
                message = "You are not authorized to perform this action.\n\n" + message;
                if (!showMessageOnForbidden) {
                    showDialog = false;
                }
            } else if (StringUtils.contains(t.getMessage(), "Received close_notify during handshake")) {
                return;
            } else if (t.getCause() != null && t.getCause() instanceof IllegalStateException
                    && mirthClient.isClosed()) {
                return;
            } else if (StringUtils.contains(t.getMessage(), "reset") || (t instanceof UnauthorizedException
                    || t.getCause() != null && t.getCause() instanceof UnauthorizedException)) {
                connectionError = true;
                statusUpdaterExecutor.shutdownNow();

                alertWarning(parentComponent,
                        "Sorry your connection to Mirth has either timed out or there was an error in the connection.  Please login again.");
                if (!exportChannelOnError()) {
                    return;
                }
                mirthClient.close();
                this.dispose();
                LoginPanel.getInstance().initialize(PlatformUI.SERVER_URL, PlatformUI.CLIENT_VERSION, "", "");
                return;
            } else if (t.getCause() != null && t.getCause() instanceof HttpHostConnectException
                    && StringUtils.contains(t.getCause().getMessage(), "Connection refused")) {
                connectionError = true;
                statusUpdaterExecutor.shutdownNow();

                String server;
                if (!StringUtils.isBlank(PlatformUI.SERVER_NAME)) {
                    server = PlatformUI.SERVER_NAME + "(" + PlatformUI.SERVER_URL + ")";
                } else {
                    server = PlatformUI.SERVER_URL;
                }
                alertWarning(parentComponent, "The Mirth Connect server " + server
                        + " is no longer running.  Please start it and log in again.");
                if (!exportChannelOnError()) {
                    return;
                }
                mirthClient.close();
                this.dispose();
                LoginPanel.getInstance().initialize(PlatformUI.SERVER_URL, PlatformUI.CLIENT_VERSION, "", "");
                return;
            }
        }

        for (String stackFrame : ExceptionUtils.getStackFrames(t)) {
            if (StringUtils.isNotEmpty(message)) {
                message += '\n';
            }
            message += StringUtils.trim(stackFrame);
        }
    }

    logger.error(message);

    if (showDialog) {
        Window owner = getWindowForComponent(parentComponent);

        if (owner instanceof java.awt.Frame) {
            new ErrorDialog((java.awt.Frame) owner, message);
        } else { // window instanceof Dialog
            new ErrorDialog((java.awt.Dialog) owner, message);
        }
    }
}

From source file:com.omertron.themoviedbapi.TheMovieDbApi.java

/**
 * This method lets users create a new list. A valid session id is required.
 *
 * @param sessionId/*  w  w w .  j  av  a 2 s  .c o  m*/
 * @param name
 * @param description
 * @return The list id
 * @throws MovieDbException
 */
public String createList(String sessionId, String name, String description) throws MovieDbException {
    ApiUrl apiUrl = new ApiUrl(apiKey, "list");
    apiUrl.addArgument(PARAM_SESSION, sessionId);

    Map<String, String> body = new HashMap<String, String>();
    body.put("name", StringUtils.trimToEmpty(name));
    body.put("description", StringUtils.trimToEmpty(description));

    String jsonBody = convertToJson(body);

    URL url = apiUrl.buildUrl();
    String webpage = requestWebPage(url, jsonBody);

    try {
        return mapper.readValue(webpage, MovieDbListStatus.class).getListId();
    } catch (IOException ex) {
        LOG.warn("Failed to create list: {}", ex.getMessage(), ex);
        throw new MovieDbException(MovieDbExceptionType.MAPPING_FAILED, webpage, url, ex);
    }
}

From source file:com.moviejukebox.plugin.ImdbPlugin.java

/**
 * Find the character from the XML item string
 *
 * @param item/*from  w  w  w. ja  v a  2 s .  co  m*/
 * @return
 */
private static String getCharacter(final String item) {
    String character = UNKNOWN;
    int beginIndex, endIndex;

    LOG.trace("Looking for character in '{}'", item);

    String charBegin = "<a href=\"/character/";
    String charEnd = "</a>";

    beginIndex = item.indexOf(charBegin);
    if (beginIndex > -1) {
        endIndex = item.indexOf(charEnd, beginIndex);
        endIndex = endIndex < 0 ? item.length() : endIndex + charEnd.length();

        character = HTMLTools.stripTags(item.substring(beginIndex, endIndex), true);

        // Remove any text in brackets
        endIndex = character.indexOf('(');
        if (endIndex > -1) {
            character = StringUtils.trimToEmpty(character.substring(0, endIndex));
        }
    } else {
        // Try an alternative method to get the character
        // It's usually at the end of the string between <br/> and </div>
        beginIndex = item.lastIndexOf("<br/>");
        endIndex = item.lastIndexOf("</div>");
        if (endIndex > beginIndex) {
            character = HTMLTools.stripTags(item.substring(beginIndex, endIndex), true);
            // Remove anything in ()
            character = character.replaceAll("\\([^\\)]*\\)", "");
        }
    }

    LOG.trace("Returning character: '{}'", StringTools.isValidString(character) ? character : UNKNOWN);
    return StringTools.isValidString(character) ? character : UNKNOWN;
}

From source file:alfio.manager.TicketReservationManager.java

public TicketReservation findByPartialID(String reservationId) {
    Validate.notBlank(reservationId, "invalid reservationId");
    Validate.matchesPattern(reservationId, "^[^%]*$", "invalid character found");
    List<TicketReservation> results = ticketReservationRepository
            .findByPartialID(StringUtils.trimToEmpty(reservationId).toLowerCase() + "%");
    Validate.isTrue(results.size() > 0, "reservation not found");
    Validate.isTrue(results.size() == 1, "multiple results found. Try handling this reservation manually.");
    return results.get(0);
}

From source file:net.sourceforge.pmd.PMD.java

private static List<DataSource> internalGetApplicableFiles(PMDConfiguration configuration,
        Set<Language> languages) {
    LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(languages);
    List<DataSource> files = new ArrayList<>();

    if (null != configuration.getInputPaths()) {
        files.addAll(FileUtil.collectFiles(configuration.getInputPaths(), fileSelector));
    }/*from  w  w  w .  j a  v a  2s.  co  m*/

    if (null != configuration.getInputUri()) {
        String uriString = configuration.getInputUri();
        try {
            List<DataSource> dataSources = getURIDataSources(uriString);

            files.addAll(dataSources);
        } catch (PMDException ex) {
            LOG.log(Level.SEVERE, "Problem with Input URI", ex);
            throw new RuntimeException("Problem with DBURI: " + uriString, ex);
        }
    }

    if (null != configuration.getInputFilePath()) {
        String inputFilePath = configuration.getInputFilePath();
        File file = new File(inputFilePath);
        try {
            if (!file.exists()) {
                LOG.log(Level.SEVERE, "Problem with Input File Path", inputFilePath);
                throw new RuntimeException("Problem with Input File Path: " + inputFilePath);
            } else {
                String filePaths = FileUtils.readFileToString(new File(inputFilePath));
                filePaths = StringUtils.trimToEmpty(filePaths);
                filePaths = filePaths.replaceAll("\\r?\\n", ",");
                filePaths = filePaths.replaceAll(",+", ",");

                files.addAll(FileUtil.collectFiles(filePaths, fileSelector));
            }
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Problem with Input File", ex);
            throw new RuntimeException("Problem with Input File Path: " + inputFilePath, ex);
        }

    }
    return files;
}

From source file:net.sourceforge.pmd.util.FileUtil.java

/**
 * Reads the file, which contains the filelist. This is used for the
 * command line arguments --filelist/-filelist for both PMD and CPD.
 * The separator in the filelist is a command and/or newlines.
 * /*  w w  w  . j  a  v a  2  s . c o  m*/
 * @param filelist the file which contains the list of path names
 * @return a comma-separated list of file paths
 * @throws IOException if the file couldn't be read
 */
public static String readFilelist(File filelist) throws IOException {
    String filePaths = FileUtils.readFileToString(filelist);
    filePaths = StringUtils.trimToEmpty(filePaths);
    filePaths = filePaths.replaceAll("\\r?\\n", ",");
    filePaths = filePaths.replaceAll(",+", ",");
    return filePaths;
}

From source file:nl.sidn.stats.MetricManager.java

private String createMetricName(String metric) {
    //replace dot in the server name with underscore otherwise graphite will assume nesting
    String cleanServer = StringUtils
            .trimToEmpty(StringUtils.replace(Settings.getInstance().getServer().getFullname(), ".", "_"));
    return graphitePrefix + "." + cleanServer + metric;
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseCustomFieldHandler.java

/**
 * Appends the custom field values on a query. Should be invoked when
 * building the where part of the query/*  w ww  .j ava2  s  .c o m*/
 *
 * @param hql The current HQL buffer
 * @param values The custom field values used to filter
 */
public void appendConditions(final StringBuilder hql, final Map<String, Object> namedParameters,
        final Collection<? extends CustomFieldValue> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    for (final CustomFieldValue fieldValue : values) {
        CustomField field = fieldValue.getField();
        if (field == null) {
            continue;
        }
        field = fetchDao.fetch(field);
        String value = fieldValue.getValue();
        // Remove any manually entered '%'
        value = StringUtils.trimToNull(StringUtils.replace(value, "%", ""));
        if (value == null) {
            continue;
        }
        final String alias = alias(field);
        final String fieldParam = "field_" + alias;
        final String valueParam = "value_" + alias;

        hql.append(" and ").append(alias).append(".field = :").append(fieldParam);
        namedParameters.put(fieldParam, field);

        if (LoggedUser.hasUser() && !LoggedUser.isAdministrator()) {
            if (field.getNature() == CustomField.Nature.MEMBER) {
                // Exclude hidden fields
                hql.append(" and ").append(alias).append(".hidden <> true");
            }
        }
        // Check the field type
        switch (field.getType()) {
        case STRING:
            if (StringUtils.isNotEmpty(field.getPattern())) {
                // Remove the mask and consider the value as matching exactly
                value = StringHelper.removeMask(field.getPattern(), value, false);
                hql.append(" and ").append(alias).append(".stringValue like :").append(valueParam);
                namedParameters.put(valueParam, value);
            } else {
                // Use a like expression
                hql.append(" and ").append(alias).append(".stringValue like :").append(valueParam);
                namedParameters.put(valueParam, StringUtils.trimToEmpty(value) + "%");
            }
            break;
        case BOOLEAN:
            if (Boolean.parseBoolean(value)) {
                hql.append(" and ").append(alias).append(".stringValue = :" + valueParam);
            } else {
                hql.append(" and ").append(alias).append(".stringValue <> :" + valueParam);
            }
            namedParameters.put(valueParam, "true");
            break;
        case ENUMERATED:
            boolean byName = true;
            if (StringUtils.containsOnly(value, "0123456789,")) {
                // Try by id
                try {
                    final Collection<CustomFieldPossibleValue> possibleValues = new ArrayList<CustomFieldPossibleValue>();
                    final String[] possibleValueIds = StringUtils.split(value, ',');
                    for (final String idAsString : possibleValueIds) {
                        final CustomFieldPossibleValue possibleValue = customFieldPossibleValueDao
                                .load(Long.valueOf(idAsString));
                        if (!possibleValue.getField().equals(field)) {
                            throw new Exception();
                        }
                        possibleValues.add(possibleValue);
                    }
                    byName = false;
                    hql.append(" and ").append(alias).append(".possibleValue in (:").append(valueParam)
                            .append(')');
                    namedParameters.put(valueParam, possibleValues);
                } catch (final Exception e) {
                    // Possible value not found by id - next try by name
                }
            }
            if (byName) {
                hql.append(" and ").append(alias).append(".possibleValue.value = :").append(valueParam);
                namedParameters.put(valueParam, value);
            }
            break;
        case MEMBER:
            Long memberId = null;
            if (fieldValue.getMemberValue() != null) {
                memberId = fieldValue.getMemberValue().getId();
            } else {
                memberId = IdConverter.instance().valueOf(value);
            }
            if (memberId != null) {
                hql.append(" and ").append(alias).append(".memberValue.id = :").append(valueParam);
                namedParameters.put(valueParam, memberId);
            }
            break;
        default:
            hql.append(" and ").append(alias).append(".stringValue = :").append(valueParam);
            namedParameters.put(valueParam, value);
            break;
        }
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseQueryHandler.java

/**
 * Returns an HQL query without the fetch part
 *//*from  w w  w.  j  ava2s .co  m*/
private static String stripFetch(String hql) {
    // This is done so we don't confuse the matcher, i.e.: from X x left join fetch x.a *left* join fetch ... -> that *left* could be an alias
    hql = hql.replaceAll("left join", "^left join");

    Matcher matcher = LEFT_JOIN_FETCH.matcher(hql);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String path = StringUtils.trimToEmpty(matcher.group(1));
        String alias = StringUtils.trimToEmpty(matcher.group(2));
        boolean nextIsLeft = "left".equalsIgnoreCase(alias);
        boolean safeToRemove = alias.isEmpty() || nextIsLeft || "where".equalsIgnoreCase(alias)
                || "order".equalsIgnoreCase(alias) || "group".equalsIgnoreCase(alias);
        String replacement;
        if (safeToRemove) {
            // No alias - we can just remove the entire left join fetch
            replacement = nextIsLeft ? "" : " " + alias;
        } else {
            // Just remove the 'fetch'
            replacement = " left join " + path + " " + alias;
        }
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    return sb.toString().replaceAll("\\^left join", "left join");
}

From source file:nl.vpro.jcr.criteria.query.xpath.utils.XPathTextUtils.java

/**
 * Convert a string to a JCR search expression literal, suitable for use in jcr:contains() (inside XPath queries).
 * The characters - and " have special meaning, and may be escaped with a backslash to obtain their literal value.
 * See JSR-170 spec v1.0, Sec. 6.6.5.2.//from w w w  .j a  v  a 2s. c o m
 * @param str Any string.
 * @return A valid XPath 2.0 string literal suitable for use in jcr:contains(), including enclosing quotes.
 */
public static String stringToJCRSearchExp(String str) {
    if (StringUtils.isEmpty(str)) {
        return str;
    }

    String parseString = StringUtils.trimToEmpty(str);

    // workaround for https://issues.apache.org/jira/browse/JCR-2732
    parseString = StringUtils.replaceEach(parseString, new String[] { ":)", ":(" },
            new String[] { ": )", ": (" });

    /*
     * http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters
     * http://www.javalobby.org/java/forums/t86124.html
     */
    String escapeChars = "[\\\\+\\-\\!\\(\\)\\:\\^\\]\\{\\}\\~\\*\\?\"\\[\\]|]";
    parseString = parseString.replaceAll(escapeChars, "\\\\$0");
    parseString = parseString.replaceAll("\'", "\'\'");

    // workaround for https://issues.apache.org/jira/browse/JCR-2733
    if (StringUtils.startsWith(parseString, "OR ")) {
        parseString = parseString.replaceFirst("\\bOR\\b", "\"OR\"");
    }

    return parseString;

}