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

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

Introduction

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

Prototype

public static String trimToNull(final String str) 

Source Link

Document

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

Usage

From source file:com.moviejukebox.model.Movie.java

public void addSet(final String set, final Integer order) {
    String newSet = StringUtils.trimToNull(set);

    if (StringTools.isValidString(newSet)) {
        setDirty(DirtyFlag.INFO);//  w ww  .  j a va2s  .  c o m
        LOG.debug("Set added: {}, {}", newSet, order == null ? ", unordered" : ", order: " + order);
        sets.put(newSet, order);
    }
}

From source file:com.oncore.calorders.core.utils.FormatHelper.java

/**
 * This method checks the strings in input fields are same or not. The null
 * value and empty string "" are treated as same.
 *
 * @param obj1 The first string to compare
 * @param obj2 The second string to compare
 * @return true if the two strings are same, e.g. no change.
 *//* w ww  .  j  a  v  a2 s.c o  m*/
public static Boolean sameAfterTrimToNull(String obj1, String obj2) {
    return StringUtils.equals(StringUtils.trimToNull(obj1), StringUtils.trimToNull(obj2));
}

From source file:hoot.services.controllers.review.ReviewResource.java

/**
 * Retrieves all other unresolved element references to reviews for a given
 * element/*from w  w  w.jav a  2s. c  om*/
 *
 * @param queryElementInfo
 *            element whose review references are to be retrieved
 * @return a list containing all features the input feature needs to be
 *         reviewed with
 */
private static List<ReviewRef> getAllReferences(ElementInfo queryElementInfo) {
    long mapIdNum = MapResource.validateMap(queryElementInfo.getMapId());

    // check for query element existence
    Set<Long> elementIds = new HashSet<>();
    elementIds.add(queryElementInfo.getId());

    if ((StringUtils.trimToNull(queryElementInfo.getType()) == null) || !Element.allElementsExist(mapIdNum,
            Element.elementTypeFromString(queryElementInfo.getType()), elementIds)) {
        handleError(new Exception("Element with ID: " + queryElementInfo + " and type: "
                + queryElementInfo.getType() + " does not exist."), "");
    }

    // select all review relation id's from current relation members where
    // member id = requesting element's member id and the element type = the requesting element type
    List<Long> allReviewRelationIds = getAllReviewRelations(queryElementInfo, mapIdNum);

    List<ReviewRef> references = new ArrayList<>();
    if (!allReviewRelationIds.isEmpty()) {
        // select all relation members where themember's id is not equal to the requesting element's id and the
        // member's type is not = to the requesting element's type
        List<CurrentRelationMembers> referencedMembers = createQuery(mapIdNum).select(currentRelationMembers)
                .from(currentRelationMembers).where(currentRelationMembers.relationId.in(allReviewRelationIds))
                .orderBy(currentRelationMembers.relationId.asc(), currentRelationMembers.memberId.asc(),
                        currentRelationMembers.sequenceId.asc())
                .fetch();

        // return all elements corresponding to the filtered down set of relation members
        for (CurrentRelationMembers member : referencedMembers) {
            references.add(new ReviewRef(queryElementInfo.getMapId(), member.getMemberId(),
                    Element.elementTypeForElementEnum(member.getMemberType()).toString().toLowerCase(),
                    member.getRelationId()));
        }
    }

    return references;
}

From source file:com.adobe.acs.commons.hc.impl.HealthCheckStatusEmailer.java

/**
 * Hostname retrieval code borrowed from Malt on StackOverflow
 * > https://stackoverflow.com/questions/7348711/recommended-way-to-get-hostname-in-java
 ** //*  w  ww  .j  av  a2s .c  o m*/
        
/**
 * Attempts to get the hostname of running AEM instance. Uses the OSGi configured fallback if unavailable.
 *
 * @return the AEM Instance's hostname.
 */
@SuppressWarnings({ "squid:S3776", "squid:S1192" })
private String getHostname() {
    String hostname = null;
    final String os = System.getProperty("os.name").toLowerCase();

    // Unpleasant 'if structure' to avoid making unnecessary Runtime calls; only call Runtime.

    if (os.indexOf("win") >= 0) {
        hostname = System.getenv("COMPUTERNAME");
        if (StringUtils.isBlank(hostname)) {
            try {
                hostname = execReadToString("hostname");
            } catch (IOException ex) {
                log.warn("Unable to collect hostname from Windows via 'hostname' command.", ex);
            }
        }
    } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("mac") >= 0) {
        hostname = System.getenv("HOSTNAME");

        if (StringUtils.isBlank(hostname)) {
            try {
                hostname = execReadToString("hostname");
            } catch (IOException ex) {
                log.warn("Unable to collect hostname from *nix via 'hostname' command.", ex);
            }
        }

        if (StringUtils.isBlank(hostname)) {
            try {
                execReadToString("cat /etc/hostname");
            } catch (IOException ex) {
                log.warn("Unable to collect hostname from *nix via 'cat /etc/hostname' command.", ex);
            }
        }
    } else {
        log.warn("Unidentifiable OS [ {} ]. Could not collect hostname.", os);
    }

    hostname = StringUtils.trimToNull(hostname);

    if (StringUtils.isBlank(hostname)) {
        log.debug("Unable to derive hostname from OS; defaulting to OSGi Configured value [ {} ]",
                fallbackHostname);
        return fallbackHostname;
    } else {
        log.debug("Derived hostname from OS: [ {} ]", hostname);
        return hostname;
    }
}

From source file:com.oncore.calorders.core.utils.FormatHelper.java

/**
 * This method checks the selected values in a drop down list are same or
 * not. The unknown value in drop down "-1" is treated as null. The
 * parameters can be any type. This method should be used to compare drop
 * down values only, not values on input fields.
 *
 * @param obj1 The first value to compare
 * @param obj2 The second value to compare
 * @return true if the two values are same, e.g. no change.
 */// ww w.  j a  v a 2s . c o m
public static Boolean sameSelectedValues(Object obj1, Object obj2) {
    String value1 = null;
    String value2 = null;

    if (obj1 != null) {
        value1 = obj1.toString();
    }

    if (obj2 != null) {
        value2 = obj2.toString();
    }

    if (StringUtils.equals(value1, UNKNOWN_VALUE + "")) {
        value1 = null;
    }

    if (StringUtils.equals(value2, UNKNOWN_VALUE + "")) {
        value2 = null;
    }

    return StringUtils.equals(StringUtils.trimToNull(value1), StringUtils.trimToNull(value2));
}

From source file:com.norconex.collector.http.url.impl.HtmlLinkExtractor.java

@Override
public void loadFromXML(Reader in) {
    XMLConfiguration xml = ConfigurationUtil.newXMLConfiguration(in);
    setMaxURLLength(xml.getInt("[@maxURLLength]", getMaxURLLength()));
    setIgnoreNofollow(xml.getBoolean("[@ignoreNofollow]", isIgnoreNofollow()));
    setKeepReferrerData(xml.getBoolean("[@keepReferrerData]", isKeepReferrerData()));

    // Content Types
    ContentType[] cts = ContentType//from   w  w w . j  a v a2 s .co  m
            .valuesOf(StringUtils.split(StringUtils.trimToNull(xml.getString("contentTypes")), ", "));
    if (!ArrayUtils.isEmpty(cts)) {
        setContentTypes(cts);
    }

    // tag & attributes
    List<HierarchicalConfiguration> tagNodes = xml.configurationsAt("tags.tag");
    if (!tagNodes.isEmpty()) {
        clearLinkTags();
        for (HierarchicalConfiguration tagNode : tagNodes) {
            String name = tagNode.getString("[@name]", null);
            String attr = tagNode.getString("[@attribute]", null);
            if (!StringUtils.isAnyBlank(name, attr)) {
                addLinkTag(name, attr);
            }
        }
    }
}

From source file:alfio.controller.EventController.java

private CodeType getCodeType(int eventId, String code) {
    String trimmedCode = StringUtils.trimToNull(code);
    if (trimmedCode == null) {
        return CodeType.NOT_FOUND;
    } else if (specialPriceRepository.getByCode(trimmedCode).isPresent()) {
        return CodeType.SPECIAL_PRICE;
    } else if (promoCodeRepository.findPromoCodeInEventOrOrganization(eventId, trimmedCode).isPresent()) {
        return CodeType.PROMO_CODE_DISCOUNT;
    } else if (ticketCategoryRepository.findCodeInEvent(eventId, trimmedCode).isPresent()) {
        return CodeType.TICKET_CATEGORY_CODE;
    } else {/*from ww  w  .  jav  a2s.  c om*/
        return CodeType.NOT_FOUND;
    }
}

From source file:com.norconex.collector.http.url.impl.GenericLinkExtractor.java

private String toCleanAbsoluteURL(final Referer urlParts, final String newURL) {
    String url = StringUtils.trimToNull(newURL);
    if (!isValidNewURL(url)) {
        return null;
    }//from   w  ww  .j a v  a2 s  .  com

    // Decode HTML entities.
    url = StringEscapeUtils.unescapeHtml4(url);

    if (url.startsWith("//")) {
        // this is URL relative to protocol
        url = urlParts.protocol + StringUtils.substringAfter(url, "//");
    } else if (url.startsWith("/")) {
        // this is a URL relative to domain name
        url = urlParts.absoluteBase + url;
    } else if (url.startsWith("?") || url.startsWith("#")) {
        // this is a relative url and should have the full page base
        url = urlParts.documentBase + url;
    } else if (!url.contains("://")) {
        if (urlParts.relativeBase.endsWith("/")) {
            // This is a URL relative to the last URL segment
            url = urlParts.relativeBase + url;
        } else {
            url = urlParts.relativeBase + "/" + url;
        }
    }

    if (url.length() > maxURLLength) {
        LOG.debug("URL length (" + url.length() + ") exeeding " + "maximum length allowed (" + maxURLLength
                + ") to be extracted. URL (showing first " + LOGGING_MAX_URL_LENGTH + " chars): "
                + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "...");
        return null;
    }

    return url;
}

From source file:com.github.devnied.emvnfccard.parser.EmvParser.java

/**
 * Extract card holder lastname and firstname
 *
 * @param pData/*from w w w  .  ja  v a 2  s  .  co m*/
 *            card data
 */
protected void extractCardHolderName(final byte[] pData) {
    // Extract Card Holder name (if exist)
    byte[] cardHolderByte = TlvUtil.getValue(pData, EmvTags.CARDHOLDER_NAME);
    if (cardHolderByte != null) {
        String[] name = StringUtils.split(new String(cardHolderByte).trim(), CARD_HOLDER_NAME_SEPARATOR);
        if (name != null && name.length == 2) {
            card.setHolderFirstname(StringUtils.trimToNull(name[0]));
            card.setHolderLastname(StringUtils.trimToNull(name[1]));
        }
    }
}

From source file:alfio.controller.EventController.java

@RequestMapping(value = "/event/{eventName}/code/{code}", method = { RequestMethod.GET, RequestMethod.HEAD })
public String handleCode(@PathVariable("eventName") String eventName, @PathVariable("code") String code,
        Model model, ServletWebRequest request, RedirectAttributes redirectAttributes, Locale locale) {
    String trimmedCode = StringUtils.trimToNull(code);
    return eventRepository.findOptionalByShortName(eventName).map(event -> {
        String redirectToEvent = "redirect:/event/" + eventName + "/";
        ValidationResult res = savePromoCode(eventName, trimmedCode, model, request.getRequest());
        CodeType codeType = getCodeType(event.getId(), trimmedCode);
        if (res.isSuccess() && codeType == CodeType.PROMO_CODE_DISCOUNT) {
            return redirectToEvent;
        } else if (codeType == CodeType.TICKET_CATEGORY_CODE) {
            TicketCategory category = ticketCategoryRepository.findCodeInEvent(event.getId(), trimmedCode)
                    .get();// w w  w  .java 2  s  .  c o  m
            if (!category.isAccessRestricted()) {
                return makeSimpleReservation(eventName, request, redirectAttributes, locale, null, event,
                        category.getId());
            } else {
                Optional<SpecialPrice> specialPrice = specialPriceRepository
                        .findActiveNotAssignedByCategoryId(category.getId()).stream().findFirst();
                if (!specialPrice.isPresent()) {
                    return redirectToEvent;
                }
                savePromoCode(eventName, specialPrice.get().getCode(), model, request.getRequest());
                return makeSimpleReservation(eventName, request, redirectAttributes, locale,
                        specialPrice.get().getCode(), event, category.getId());
            }
        } else if (res.isSuccess() && codeType == CodeType.SPECIAL_PRICE) {
            int ticketCategoryId = specialPriceRepository.getByCode(trimmedCode).get().getTicketCategoryId();
            return makeSimpleReservation(eventName, request, redirectAttributes, locale, trimmedCode, event,
                    ticketCategoryId);
        } else {
            return redirectToEvent;
        }
    }).orElse("redirect:/");
}