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:hoot.services.writers.review.ReviewPrepareDbWriter.java

protected boolean parseElementReviewTags(final long mapId) throws Exception {
    final String logMsgStart = "Parsing element review tags for map with ID: " + mapId + ".  Step 3 of 4.";
    log.info(logMsgStart);/* w ww  .  j  av  a 2s  .c om*/
    //SQLQuery query = new SQLQuery(conn, DbUtils.getConfiguration());
    //parse review tags for all nodes, ways, and relations from the OSM element tables for the given
    //map
    reviewRecordsParsed = 0;
    reviewRecordWritten = false;
    List<ReviewItems> reviewRecordsToInsert = new ArrayList<ReviewItems>();
    //create this outside of the batch read loop, since we need to maintain a list of unique
    //ID's parsed over the entire map's set of reviewable records
    reviewableItemIdToReviewAgainstItemIds = ArrayListMultimap.create();
    reviewableItemIdToReviewAgainstItemIds.putAll(previouslyReviewedItemIdToReviewAgainstItemIds);

    int numReviewItemsAdded = 0;
    for (ElementType elementType : ElementType.values()) {
        if (!elementType.equals(ElementType.Changeset)) {
            //final Element prototype = ElementFactory.getInstance().create(elementType, conn);

            int numElementsReturned = Integer.MAX_VALUE;
            int elementIndex = 0;
            while (numElementsReturned > 0) {
                //get a batch of reviewable elements
                final Map<Long, Object> reviewableElementRecords = getReviewableElementRecords(mapId,
                        elementType, maxRecordSelectSize, elementIndex);
                numElementsReturned = reviewableElementRecords.size();
                elementIndex += numElementsReturned;
                for (Map.Entry<Long, Object> reviewableElementRecordEntry : reviewableElementRecords
                        .entrySet()) {
                    final Object reviewableElementRecord = reviewableElementRecordEntry.getValue();
                    final Map<String, String> tags = PostgresUtils.postgresObjToHStore((PGobject) MethodUtils
                            .invokeMethod(reviewableElementRecord, "getTags", new Object[] {}));
                    String reviewableItemId = StringUtils.trimToNull(tags.get("uuid"));
                    if (StringUtils.isEmpty(reviewableItemId)) {
                        log.warn("Invalid UUID: " + tags.get("uuid") + " for map with ID: " + mapId
                                + " Skipping adding review record...");
                    } else {
                        //some items won't have a review score tag; For now, the way this is being handled
                        //is that items missing a tag get a review score = 1.0; items with an empty string
                        //or invalid string for a review tag get a review score of -1.0, which invalidates
                        //the review pair.  The case could be argued that invalid/empty score strings should
                        //also result in a review score = 1.0.
                        double reviewScore = -1.0;
                        if (tags.containsKey("hoot:review:score")) {
                            try {
                                reviewScore = Double.parseDouble(tags.get("hoot:review:score"));
                            } catch (NumberFormatException e) {
                            }
                        } else {
                            reviewScore = 1.0;
                        }

                        if (reviewScore != -1.0 && tags.containsKey("hoot:review:uuid")
                                && StringUtils.trimToNull(tags.get("hoot:review:uuid")) != null) {
                            String[] reviewAgainstItemIds = null;
                            final String itemsToReviewAgainstStr = StringUtils
                                    .trimToNull(tags.get("hoot:review:uuid"));
                            //We are parsing pairwise comparisons and don't want duplicates, so ignore one
                            //to many reviewable item to review against item relationships.  They are always
                            //represented with a duplicated one to one relationship in the data.
                            if (!itemsToReviewAgainstStr.contains(";")) {
                                reviewAgainstItemIds = new String[] { itemsToReviewAgainstStr };
                            } else {
                                reviewAgainstItemIds = itemsToReviewAgainstStr.split(";");
                            }

                            for (int i = 0; i < reviewAgainstItemIds.length; i++) {
                                final String reviewAgainstItemId = reviewAgainstItemIds[i];
                                //TODO: I believe this check is not correct, but I know of no other way to handle
                                //this for now...
                                //TODO: make this a batch query somehow
                                if (new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(elementIdMappings)
                                        .where(elementIdMappings.mapId.eq(mapId)
                                                .and(elementIdMappings.elementId.eq(reviewAgainstItemId)))
                                        .count() == 0) {
                                    log.debug("No element ID mapping exists for review against item with ID: "
                                            + reviewAgainstItemId + " for map with ID: " + mapId
                                            + ".  Skipping adding " + "review record...");
                                } else {
                                    if (!reviewPairAlreadyParsed(reviewableItemId, reviewAgainstItemId)) {
                                        log.debug("Adding review item with reviewable item ID: "
                                                + reviewableItemId + " and " + "review against item ID: "
                                                + reviewAgainstItemId);
                                        reviewRecordsToInsert.add(createReviewItemRecord(reviewableItemId,
                                                reviewScore, reviewAgainstItemId, mapId));
                                        reviewableItemIdToReviewAgainstItemIds.put(reviewableItemId,
                                                reviewAgainstItemId);
                                        flushReviewRecords(reviewRecordsToInsert, maxRecordBatchSize,
                                                logMsgStart);
                                        numReviewItemsAdded++;
                                    }
                                }
                            }
                        } else if (!tags.containsKey("hoot:review:uuid")
                                || StringUtils.trimToNull(tags.get("hoot:review:uuid")) == null) {
                            if (!reviewPairAlreadyParsed(reviewableItemId, reviewableItemId)) {
                                log.debug("Adding review item with reviewable item ID: " + reviewableItemId
                                        + " and " + "review against item ID: " + reviewableItemId);
                                reviewRecordsToInsert.add(createReviewItemRecord(reviewableItemId, reviewScore,
                                        reviewableItemId, mapId));
                                reviewableItemIdToReviewAgainstItemIds.put(reviewableItemId, reviewableItemId);
                                flushReviewRecords(reviewRecordsToInsert, maxRecordBatchSize, logMsgStart);
                                numReviewItemsAdded++;
                            }
                        }
                    }
                }
            }
        }
    }

    //final flush
    flushReviewRecords(reviewRecordsToInsert, 0, logMsgStart);

    log.debug("Wrote " + numReviewItemsAdded + " review items.");

    if (simulateFailure) {
        throw new Exception("Simulated test review data parse failure.");
    }

    return reviewRecordWritten;
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

public void getBucket(String bucket, GetBucketRequest getBucketRequest,
        Handler<Response<CommonResponseHeaders, GetBucketRespone>> handler,
        Handler<Throwable> exceptionHandler) {
    checkNotNull(StringUtils.trimToNull(bucket), "bucket must not be null");
    checkNotNull(getBucketRequest, "getBucketRequest must not be null");
    checkNotNull(handler, "handler must not be null");
    checkNotNull(exceptionHandler, "exceptionHandler must not be null");

    final S3ClientRequest request = createGetBucketRequest(bucket, getBucketRequest,
            new XmlBodyResponseHandler<>("getBucket", jaxbUnmarshaller, new CommonResponseHeadersMapper(),
                    handler, exceptionHandler));
    request.exceptionHandler(exceptionHandler);
    request.end();/*from  w  ww . java 2 s.  c  om*/
}

From source file:net.lmxm.ute.configuration.ConfigurationReader.java

/**
 * Parses the subversion revision./*ww  w  . j av a  2 s. c  o m*/
 * 
 * @param task the task
 * @param revision the revision
 */
private void parseSubversionRevision(final SubversionExportTask task, final String revision) {
    final String prefix = "parseSubversionRevision() :";

    LOGGER.debug("{} entered", prefix);

    final String trimmedRevision = StringUtils.trimToNull(revision);

    if (trimmedRevision == null || SubversionUtils.isHeadRevision(trimmedRevision)) {
        task.setRevision(SubversionRevision.HEAD);
    } else if (SubversionUtils.isRevisionNumber(trimmedRevision)) {
        task.setRevision(SubversionRevision.NUMBERED);
        task.setRevisionNumber(Long.valueOf(trimmedRevision));
    } else if (SubversionUtils.isRevisionDate(trimmedRevision)) {
        task.setRevision(SubversionRevision.DATE);
        task.setRevisionDate(SubversionUtils.parseRevisionDate(trimmedRevision));
    } else {
        LOGGER.error("{} Invalid revision value: {}", prefix, trimmedRevision);
        throw new ConfigurationException(ExceptionResourceType.INVALID_SUBVERSION_REVISION_VALUE,
                trimmedRevision);
    }

    LOGGER.debug("{} returning", prefix);
}

From source file:alfio.manager.EventManager.java

private void createCategoriesForEvent(EventModification em, Event event) {
    boolean freeOfCharge = em.isFreeOfCharge();
    ZoneId zoneId = TimeZone.getTimeZone(event.getTimeZone()).toZoneId();
    int eventId = event.getId();

    int requestedSeats = em.getTicketCategories().stream().filter(TicketCategoryModification::isBounded)
            .mapToInt(TicketCategoryModification::getMaxTickets).sum();
    int notAssignedTickets = em.getAvailableSeats() - requestedSeats;
    Validate.isTrue(notAssignedTickets >= 0,
            "Total categories' seats cannot be more than the actual event seats");
    Validate.isTrue(/*from w  ww  . jav  a  2 s .  c  o  m*/
            notAssignedTickets > 0
                    || em.getTicketCategories().stream().allMatch(TicketCategoryModification::isBounded),
            "Cannot add an unbounded category if there aren't any free tickets");

    em.getTicketCategories().forEach(tc -> {
        final int price = evaluatePrice(tc.getPriceInCents(), freeOfCharge);
        final int maxTickets = tc.isBounded() ? tc.getMaxTickets() : 0;
        final AffectedRowCountAndKey<Integer> category = ticketCategoryRepository.insert(
                tc.getInception().toZonedDateTime(zoneId), tc.getExpiration().toZonedDateTime(zoneId),
                tc.getName(), maxTickets, tc.isTokenGenerationRequested(), eventId, tc.isBounded(), price,
                StringUtils.trimToNull(tc.getCode()), toZonedDateTime(tc.getValidCheckInFrom(), zoneId),
                toZonedDateTime(tc.getValidCheckInTo(), zoneId),
                toZonedDateTime(tc.getTicketValidityStart(), zoneId),
                toZonedDateTime(tc.getTicketValidityEnd(), zoneId));

        insertOrUpdateTicketCategoryDescription(category.getKey(), tc, event);

        if (tc.isTokenGenerationRequested()) {
            final TicketCategory ticketCategory = ticketCategoryRepository.getByIdAndActive(category.getKey(),
                    event.getId());
            final MapSqlParameterSource[] args = prepareTokenBulkInsertParameters(ticketCategory,
                    ticketCategory.getMaxTickets());
            jdbc.batchUpdate(specialPriceRepository.bulkInsert(), args);
        }
    });
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private MultiMap populatePutObjectHeaders(PutObjectRequest putObjectRequest) {
    final MultiMap headers = MultiMap.caseInsensitiveMultiMap();

    if (StringUtils.trimToNull(putObjectRequest.getCacheControl()) != null) {
        headers.add(Headers.CACHE_CONTROL, StringUtils.trim(putObjectRequest.getCacheControl()));
    }/*from   w w  w.  j ava2 s  . c  o m*/
    if (StringUtils.trimToNull(putObjectRequest.getContentDisposition()) != null) {
        headers.add(Headers.CONTENT_DISPOSITION, StringUtils.trim(putObjectRequest.getContentDisposition()));
    }
    if (StringUtils.trimToNull(putObjectRequest.getContentEncoding()) != null) {
        headers.add(Headers.CONTENT_ENCODING, StringUtils.trim(putObjectRequest.getContentEncoding()));
    }
    if (StringUtils.trimToNull(putObjectRequest.getContentMD5()) != null) {
        headers.add(Headers.CONTENT_MD5, StringUtils.trim(putObjectRequest.getContentMD5()));
    }
    if (StringUtils.trimToNull(putObjectRequest.getContentType()) != null) {
        headers.add(Headers.CONTENT_TYPE, StringUtils.trim(putObjectRequest.getContentType()));
    }
    if (StringUtils.trimToNull(putObjectRequest.getExpires()) != null) {
        headers.add(Headers.EXPIRES, StringUtils.trim(putObjectRequest.getExpires()));
    }

    for (Map.Entry<String, String> meta : putObjectRequest.getAmzMeta()) {
        headers.add(Headers.X_AMZ_META_PREFIX + meta.getKey(), StringUtils.trim(meta.getValue()));
    }
    if (putObjectRequest.getAmzStorageClass() != null) {
        headers.add(Headers.X_AMZ_STORAGE_CLASS, putObjectRequest.getAmzStorageClass().name());
    }
    if (StringUtils.trimToNull(putObjectRequest.getAmzTagging()) != null) {
        headers.add(Headers.X_AMZ_TAGGING, StringUtils.trim(putObjectRequest.getAmzTagging()));
    }
    if (StringUtils.trimToNull(putObjectRequest.getAmzWebsiteRedirectLocation()) != null) {
        headers.add(Headers.X_AMZ_WEBSITE_REDIRECT_LOCATION,
                StringUtils.trim(putObjectRequest.getAmzWebsiteRedirectLocation()));
    }

    return headers;
}

From source file:com.greenpepper.server.rpc.xmlrpc.XmlRpcDataMarshaller.java

/**
 * <p>toNullIfEmpty.</p>//ww  w.j av a2  s  .  co  m
 *
 * @param str a {@link java.lang.String} object.
 * @return a {@link java.lang.String} object.
 */
public static String toNullIfEmpty(String str) {
    return StringUtils.trimToNull(str);
}

From source file:alfio.manager.EventManager.java

private Integer insertCategory(TicketCategoryModification tc, Event event) {
    ZoneId zoneId = event.getZoneId();
    int eventId = event.getId();
    final int price = evaluatePrice(tc.getPriceInCents(), event.isFreeOfCharge());
    final AffectedRowCountAndKey<Integer> category = ticketCategoryRepository.insert(
            tc.getInception().toZonedDateTime(zoneId), tc.getExpiration().toZonedDateTime(zoneId), tc.getName(),
            tc.isBounded() ? tc.getMaxTickets() : 0, tc.isTokenGenerationRequested(), eventId, tc.isBounded(),
            price, StringUtils.trimToNull(tc.getCode()), toZonedDateTime(tc.getValidCheckInFrom(), zoneId),
            toZonedDateTime(tc.getValidCheckInTo(), zoneId),
            toZonedDateTime(tc.getTicketValidityStart(), zoneId),
            toZonedDateTime(tc.getTicketValidityEnd(), zoneId));
    TicketCategory ticketCategory = ticketCategoryRepository.getByIdAndActive(category.getKey(), eventId);
    if (tc.isBounded()) {
        List<Integer> lockedTickets = ticketRepository.selectNotAllocatedTicketsForUpdate(eventId,
                ticketCategory.getMaxTickets(), asList(TicketStatus.FREE.name(), TicketStatus.RELEASED.name()));
        jdbc.batchUpdate(ticketRepository.bulkTicketUpdate(), lockedTickets.stream()
                .map(id -> new MapSqlParameterSource("id", id).addValue("categoryId", ticketCategory.getId())
                        .addValue("srcPriceCts", ticketCategory.getSrcPriceCts()))
                .toArray(MapSqlParameterSource[]::new));
        if (tc.isTokenGenerationRequested()) {
            insertTokens(ticketCategory);
            ticketRepository.revertToFree(eventId, ticketCategory.getId(), lockedTickets);
        } else {//w w  w  .  jav  a2s .co  m
            ticketRepository.resetTickets(lockedTickets);//reset to RELEASED
        }
    }

    insertOrUpdateTicketCategoryDescription(category.getKey(), tc, event);
    return category.getKey();
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private MultiMap populateAclHeadersRequest(AclHeadersRequest aclHeadersRequest) {
    final MultiMap headers = MultiMap.caseInsensitiveMultiMap();

    if (aclHeadersRequest.getAmzAcl() != null) {
        headers.add(Headers.X_AMZ_ACL, StringUtils.trim(aclHeadersRequest.getAmzAcl().getValue()));
    }//from   ww  w.ja  v  a 2 s . c o  m
    if (StringUtils.trimToNull(aclHeadersRequest.getAmzGrantRead()) != null) {
        headers.add(Headers.X_AMZ_GRANT_READ, StringUtils.trim(aclHeadersRequest.getAmzGrantRead()));
    }
    if (StringUtils.trimToNull(aclHeadersRequest.getAmzGrantWrite()) != null) {
        headers.add(Headers.X_AMZ_GRANT_WRITE, StringUtils.trim(aclHeadersRequest.getAmzGrantWrite()));
    }
    if (StringUtils.trimToNull(aclHeadersRequest.getAmzGrantReadAcp()) != null) {
        headers.add(Headers.X_AMZ_GRANT_READ_ACP, StringUtils.trim(aclHeadersRequest.getAmzGrantReadAcp()));
    }
    if (StringUtils.trimToNull(aclHeadersRequest.getAmzGrantWriteAcp()) != null) {
        headers.add(Headers.X_AMZ_GRANT_WRITE_ACP, StringUtils.trim(aclHeadersRequest.getAmzGrantWriteAcp()));
    }
    if (StringUtils.trimToNull(aclHeadersRequest.getAmzGrantFullControl()) != null) {
        headers.add(Headers.X_AMZ_GRANT_FULL_CONTROL,
                StringUtils.trim(aclHeadersRequest.getAmzGrantFullControl()));
    }

    return headers;
}

From source file:alfio.manager.EventManager.java

private void updateCategory(TicketCategoryModification tc, boolean freeOfCharge, ZoneId zoneId, Event event,
        boolean resetTicketsToFree) {

    int eventId = event.getId();
    final int price = evaluatePrice(tc.getPriceInCents(), freeOfCharge);
    TicketCategory original = ticketCategoryRepository.getByIdAndActive(tc.getId(), eventId);
    ticketCategoryRepository.update(tc.getId(), tc.getName(), tc.getInception().toZonedDateTime(zoneId),
            tc.getExpiration().toZonedDateTime(zoneId), tc.getMaxTickets(), tc.isTokenGenerationRequested(),
            price, StringUtils.trimToNull(tc.getCode()), toZonedDateTime(tc.getValidCheckInFrom(), zoneId),
            toZonedDateTime(tc.getValidCheckInTo(), (zoneId)),
            toZonedDateTime(tc.getTicketValidityStart(), zoneId),
            toZonedDateTime(tc.getTicketValidityEnd(), zoneId));
    TicketCategory updated = ticketCategoryRepository.getByIdAndActive(tc.getId(), eventId);
    int addedTickets = 0;
    if (original.isBounded() ^ tc.isBounded()) {
        handleTicketAllocationStrategyChange(event, original, tc);
    } else {/*from w ww  . j  ava 2 s . c  o  m*/
        addedTickets = updated.getMaxTickets() - original.getMaxTickets();
        handleTicketNumberModification(event, original, updated, addedTickets, resetTicketsToFree);
    }
    handleTokenModification(original, updated, addedTickets);
    handlePriceChange(event, original, updated);

    insertOrUpdateTicketCategoryDescription(tc.getId(), tc, event);

    //

    auditingRepository.insertUpdateTicketInCategoryId(tc.getId());

}

From source file:com.hubrick.vertx.s3.client.S3Client.java

private MultiMap populateInitMultipartUploadHeaders(InitMultipartUploadRequest multipartPutObjectRequest) {
    final MultiMap headers = MultiMap.caseInsensitiveMultiMap();

    if (StringUtils.trimToNull(multipartPutObjectRequest.getCacheControl()) != null) {
        headers.add(Headers.CACHE_CONTROL, StringUtils.trim(multipartPutObjectRequest.getCacheControl()));
    }//w w w  .ja va  2s.  c  om
    if (StringUtils.trimToNull(multipartPutObjectRequest.getContentDisposition()) != null) {
        headers.add(Headers.CONTENT_DISPOSITION,
                StringUtils.trim(multipartPutObjectRequest.getContentDisposition()));
    }
    if (StringUtils.trimToNull(multipartPutObjectRequest.getContentEncoding()) != null) {
        headers.add(Headers.CONTENT_ENCODING, StringUtils.trim(multipartPutObjectRequest.getContentEncoding()));
    }
    if (StringUtils.trimToNull(multipartPutObjectRequest.getContentType()) != null) {
        headers.add(Headers.CONTENT_TYPE, StringUtils.trim(multipartPutObjectRequest.getContentType()));
    }
    if (StringUtils.trimToNull(multipartPutObjectRequest.getExpires()) != null) {
        headers.add(Headers.EXPIRES, StringUtils.trim(multipartPutObjectRequest.getExpires()));
    }

    for (Map.Entry<String, String> meta : multipartPutObjectRequest.getAmzMeta()) {
        headers.add(Headers.X_AMZ_META_PREFIX + meta.getKey(), StringUtils.trim(meta.getValue()));
    }
    if (multipartPutObjectRequest.getAmzStorageClass() != null) {
        headers.add(Headers.X_AMZ_STORAGE_CLASS, multipartPutObjectRequest.getAmzStorageClass().name());
    }
    if (StringUtils.trimToNull(multipartPutObjectRequest.getAmzWebsiteRedirectLocation()) != null) {
        headers.add(Headers.X_AMZ_WEBSITE_REDIRECT_LOCATION,
                StringUtils.trim(multipartPutObjectRequest.getAmzWebsiteRedirectLocation()));
    }

    return headers;
}