List of usage examples for org.apache.commons.lang3 StringUtils trimToNull
public static String trimToNull(final String str)
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 .
From source file:com.adobe.acs.commons.mcp.impl.processes.TagCreator.java
/** * Parses the input Excel file and creates a list of TagDefinition objects to process. * * @param manager the action manager/*www . j a v a2 s . c o m*/ * @throws IOException */ @SuppressWarnings({ "squid:S3776", "squid:S1141" }) public void parseTags(ActionManager manager) throws Exception { manager.withResolver(rr -> { final XSSFWorkbook workbook = new XSSFWorkbook(tagDefinitionFile); final XSSFSheet sheet = workbook.getSheetAt(0); final Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) { final Row row = rows.next(); final Iterator<Cell> cells = row.cellIterator(); int cellIndex = 0; // The previousTagId is reset on each new row. String previousTagId = null; while (cells.hasNext()) { final Cell cell = cells.next(); final String cellValue = StringUtils.trimToNull(cell.getStringCellValue()); if (StringUtils.isBlank(cellValue)) { // Hitting a blank cell means its the end of this row; don't process anything past this break; } // Generate a tag definition that will in turn be used to drive the tag creation TagDefinition tagDefinition = getTagDefinition(primary, cellIndex, cellValue, previousTagId); if (tagDefinition == null) { tagDefinition = getTagDefinition(fallback, cellIndex, cellValue, previousTagId); } if (tagDefinition == null) { log.warn("Could not find a Tag Data Converter that accepts value [ {} ]; skipping...", cellValue); // Record parse failure record(ReportRowSatus.FAILED_TO_PARSE, cellValue, "", ""); // Break to next Row break; } else { /* Prepare for next Cell */ cellIndex++; previousTagId = tagDefinition.getId(); if (tagDefinitions.get(tagDefinition.getId()) == null) { tagDefinitions.put(tagDefinition.getId(), tagDefinition); } } } } log.info("Finished Parsing and collected [ {} ] tags for import.", tagDefinitions.size()); }); }
From source file:com.esri.geoportal.harvester.agpsrc.AgpInputBroker.java
@Override public void initialize(InitContext context) throws DataProcessorException { definition.override(context.getParams()); td = context.getTask().getTaskDefinition(); CloseableHttpClient httpclient = HttpClientBuilder.create().useSystemProperties().build(); if (context.getTask().getTaskDefinition().isIgnoreRobotsTxt()) { client = new AgpClient(httpclient, definition.getHostUrl(), definition.getCredentials(), definition.getMaxRedirects()); } else {// w ww.j a v a 2 s.c om Bots bots = BotsUtils.readBots(definition.getBotsConfig(), httpclient, definition.getHostUrl()); client = new AgpClient(new BotsHttpClient(httpclient, bots), definition.getHostUrl(), definition.getCredentials(), definition.getMaxRedirects()); } try { String folderId = StringUtils.trimToNull(definition.getFolderId()); if (folderId != null) { FolderEntry[] folders = this.client.listFolders(definition.getCredentials().getUserName(), generateToken(1)); FolderEntry selectedFodler = Arrays.stream(folders) .filter(folder -> folder.id != null && folder.id.equals(folderId)).findFirst() .orElse(Arrays.stream(folders) .filter(folder -> folder.title != null && folder.title.equals(folderId)).findFirst() .orElse(null)); if (selectedFodler != null) { definition.setFolderId(selectedFodler.id); } else { definition.setFolderId(null); } } else { definition.setFolderId(null); } } catch (IOException | URISyntaxException ex) { throw new DataProcessorException( String.format("Error listing folders for user: %s", definition.getCredentials().getUserName()), ex); } }
From source file:com.esri.geoportal.harvester.agp.AgpOutputBroker.java
@Override public PublishingStatus publish(DataReference ref) throws DataOutputException { try {//from w ww . j a v a2s . c o m // extract map of attributes (normalized names) MapAttribute attributes = extractMapAttributes(ref); if (attributes == null) { throw new DataOutputException(this, String.format("Error extracting attributes from data.")); } // build typeKeywords array String src_source_type_s = URLEncoder.encode(ref.getBrokerUri().getScheme(), "UTF-8"); String src_source_uri_s = URLEncoder.encode(ref.getBrokerUri().toASCIIString(), "UTF-8"); String src_source_name_s = URLEncoder.encode(ref.getBrokerName(), "UTF-8"); String src_uri_s = URLEncoder.encode(ref.getSourceUri().toASCIIString(), "UTF-8"); String src_lastupdate_dt = ref.getLastModifiedDate() != null ? URLEncoder.encode(fromatDate(ref.getLastModifiedDate()), "UTF-8") : null; String[] typeKeywords = { String.format("src_source_type_s=%s", src_source_type_s), String.format("src_source_uri_s=%s", src_source_uri_s), String.format("src_source_name_s=%s", src_source_name_s), String.format("src_uri_s=%s", src_uri_s), String.format("src_lastupdate_dt=%s", src_lastupdate_dt) }; try { // generate token if (token == null) { token = generateToken(); } // find resource URL URL resourceUrl = new URL(getAttributeValue(attributes, "resource.url", null)); ItemType itemType = ItemType.matchPattern(resourceUrl.toExternalForm()).stream().findFirst() .orElse(null); if (itemType == null || itemType.getDataType() != DataType.URL) { return PublishingStatus.SKIPPED; } // find thumbnail URL String sThumbnailUrl = StringUtils.trimToNull(getAttributeValue(attributes, "thumbnail.url", null)); URL thumbnailUrl = sThumbnailUrl != null ? new URL(sThumbnailUrl) : null; // check if item exists QueryResponse search = client.search( String.format("typekeywords:%s", String.format("src_uri_s=%s", src_uri_s)), 0, 0, token); ItemEntry itemEntry = search != null && search.results != null && search.results.length > 0 ? search.results[0] : null; if (itemEntry == null) { // add item if doesn't exist ItemResponse response = addItem(getAttributeValue(attributes, "title", null), getAttributeValue(attributes, "description", null), resourceUrl, thumbnailUrl, itemType, extractEnvelope(getAttributeValue(attributes, "bbox", null)), typeKeywords); if (response == null || !response.success) { throw new DataOutputException(this, String.format("Error adding item: %s", ref.getSourceUri())); } client.share(definition.getCredentials().getUserName(), definition.getFolderId(), response.id, true, true, null, token); return PublishingStatus.CREATED; } else if (itemEntry.owner.equals(definition.getCredentials().getUserName())) { itemEntry = client.readItem(itemEntry.id, token); if (itemEntry == null) { throw new DataOutputException(this, String.format("Unable to read item entry.")); } // update item if does exist ItemResponse response = updateItem(itemEntry.id, itemEntry.owner, itemEntry.ownerFolder, getAttributeValue(attributes, "title", null), getAttributeValue(attributes, "description", null), resourceUrl, thumbnailUrl, itemType, extractEnvelope(getAttributeValue(attributes, "bbox", null)), typeKeywords); if (response == null || !response.success) { throw new DataOutputException(this, String.format("Error updating item: %s", ref.getSourceUri())); } existing.remove(itemEntry.id); return PublishingStatus.UPDATED; } else { return PublishingStatus.SKIPPED; } } catch (MalformedURLException ex) { return PublishingStatus.SKIPPED; } } catch (MetaException | IOException | ParserConfigurationException | SAXException | URISyntaxException ex) { throw new DataOutputException(this, String.format("Error publishing data"), ex); } }
From source file:hoot.services.controllers.wps.MarkItemsReviewedProcesslet.java
@Override public void process(ProcessletInputs inputParams, ProcessletOutputs outputParams, ProcessletExecutionInfo processletExecInfo) throws ProcessletException { final String errorMessageStart = "marking items as reviewed"; Connection conn = DbUtils.createConnection(); MarkItemsReviewedResponse markItemsReviewedResponse = null; try {/*from www .j ava2 s . c om*/ //Any changes to these default parameters must also be reflected in //$HOOT_HOME/hoot-services/src/main/webapp/WEB-INF/workspace/MarkItemsReviewedProcesslet.xml //and vice versa. ReviewInputParamsValidator inputParamsValidator = new ReviewInputParamsValidator(inputParams); final String mapId = (String) inputParamsValidator.validateAndParseInputParam("mapId", "", null, null, false, null); final boolean markAll = (Boolean) inputParamsValidator.validateAndParseInputParam("markAll", false, null, null, true, false); final String reviewedItemsStr = (String) inputParamsValidator .validateAndParseInputParam("reviewedItems", "", null, null, true, null); ReviewedItems reviewedItems = null; if (reviewedItemsStr != null) { reviewedItems = (new ObjectMapper()).readValue(reviewedItemsStr, ReviewedItems.class); } if (!markAll && (reviewedItems == null || reviewedItems.getReviewedItems() == null || reviewedItems.getReviewedItems().length == 0)) { throw new Exception("Invalid input parameter: markAll set to false and " + "markItemsReviewedRequest.reviewedItems empty."); } final String reviewedItemsChangesetStr = (String) inputParamsValidator .validateAndParseInputParam("reviewedItemsChangeset", "", null, null, true, ""); MarkItemsReviewedRequest markItemsReviewedRequest = new MarkItemsReviewedRequest(); markItemsReviewedRequest.setReviewedItems(reviewedItems); markItemsReviewedRequest.setReviewedItemsChangeset(reviewedItemsChangesetStr); log.debug("Initializing transaction manager..."); PlatformTransactionManager transactionManager = appContext.getBean("transactionManager", PlatformTransactionManager.class); log.debug("Initializing database connection..."); //TODO: verify that no other writes are seen during this transaction log.debug("Intializing transaction..."); TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); conn.setAutoCommit(false); try { markItemsReviewedResponse = (new ReviewItemsMarker(conn, mapId)) .markItemsReviewed(markItemsReviewedRequest, markAll); } catch (Exception e) { log.debug("Rolling back database transaction for MarkItemsReviewedProcesslet..."); transactionManager.rollback(transactionStatus); conn.rollback(); throw e; } log.debug("Committing MarkItemsReviewedProcesslet database transaction..."); transactionManager.commit(transactionStatus); conn.commit(); if (StringUtils.trimToNull(markItemsReviewedResponse.getChangesetUploadResponse()) != null) { log.debug("Returning changeset upload response: " + StringUtils.abbreviate(markItemsReviewedResponse.getChangesetUploadResponse(), 100) + " ..."); } else { log.debug("Returning null changeset upload response..."); } ((LiteralOutput) outputParams.getParameter("changesetUploadResponse")) .setValue(markItemsReviewedResponse.getChangesetUploadResponse()); log.debug("Returning number of items marked as reviewed: " + markItemsReviewedResponse.getNumItemsMarkedReviewed() + " ..."); ((LiteralOutput) outputParams.getParameter("numItemsMarkedReviewed")) .setValue(String.valueOf(markItemsReviewedResponse.getNumItemsMarkedReviewed())); log.debug("Returning changeset ID: " + markItemsReviewedResponse.getChangesetId() + " ..."); ((LiteralOutput) outputParams.getParameter("changesetId")) .setValue(String.valueOf(markItemsReviewedResponse.getChangesetId())); } catch (Exception e) { try { ReviewUtils.handleError(e, errorMessageStart, true); } catch (Exception e2) { throw (ProcessletException) e2; } } finally { try { conn.setAutoCommit(true); DbUtils.closeConnection(conn); } catch (Exception e) { try { ReviewUtils.handleError(e, errorMessageStart, true); } catch (Exception e2) { throw (ProcessletException) e2; } } } }
From source file:it.jaschke.alexandria.model.view.BookListViewModel.java
/** * Returns the arguments for the selection clause used on the query to * retrieve the list of books.//from ww w .j a va 2 s.c om * * @return the arguments for the selection clause used on the query to * retrieve the list of books. */ public String[] getBookListQuerySelectionArguments() { String searchPattern = "%" + mSearchString + "%"; return StringUtils.trimToNull(mSearchString) != null ? new String[] { searchPattern, searchPattern } : null; }
From source file:alfio.controller.form.ReservationForm.java
public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate( Errors bindingResult, TicketReservationManager tickReservationManager, AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) { int selectionCount = ticketSelectionCount(); if (selectionCount <= 0) { bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE); return Optional.empty(); }/*from w w w. j a v a 2 s . c o m*/ List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream() .map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(), event.getId(), r.getTicketCategoryId()))) .collect(toList()); Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream() .filter(p -> p.getKey().getAmount() > p.getValue()).findAny(); if (error.isPresent()) { bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null); return Optional.empty(); } final List<TicketReservationModification> categories = selected(); final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices(); final boolean validCategorySelection = categories.stream().allMatch(c -> { TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId()); return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent(); }); final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> { AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(), event.getId()); ZonedDateTime now = ZonedDateTime.now(event.getZoneId()); return as.getInception(event.getZoneId()).isBefore(now) && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0 && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice() && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0)) && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent(); }); if (!validCategorySelection || !validAdditionalServiceSelected) { bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE); return Optional.empty(); } List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>(); // Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode)) .flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode)); // final ZonedDateTime now = ZonedDateTime.now(event.getZoneId()); maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager, eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft())); return bindingResult.hasErrors() ? Optional.empty() : Optional.of(Pair.of(res, additionalServices.stream() .map(as -> new ASReservationWithOptionalCodeModification(as, specialCode)) .collect(Collectors.toList()))); }
From source file:net.eledge.android.toolkit.db.internal.FieldType.java
public String toString(Object instance, Field field) throws IllegalArgumentException, IllegalAccessException { Object value = field.get(instance); if (value != null) { return StringUtils.trimToNull(value.toString()); }/*from w w w.j a v a 2s . c o m*/ return null; }
From source file:alfio.controller.EventController.java
@RequestMapping(value = "/event/{eventName}/promoCode/{promoCode}", method = RequestMethod.POST) @ResponseBody/*from www.j av a 2 s .c o m*/ public ValidationResult savePromoCode(@PathVariable("eventName") String eventName, @PathVariable("promoCode") String promoCode, Model model, HttpServletRequest request) { SessionUtil.removeSpecialPriceData(request); Optional<Event> optional = eventRepository.findOptionalByShortName(eventName); if (!optional.isPresent()) { return ValidationResult.failed(new ValidationResult.ErrorDescriptor("event", "")); } Event event = optional.get(); ZonedDateTime now = ZonedDateTime.now(event.getZoneId()); Optional<String> maybeSpecialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode)); Optional<SpecialPrice> specialCode = maybeSpecialCode .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode)); Optional<PromoCodeDiscount> promotionCodeDiscount = maybeSpecialCode .flatMap((trimmedCode) -> promoCodeRepository.findPromoCodeInEventOrOrganization(event.getId(), trimmedCode)); if (specialCode.isPresent()) { if (!optionally(() -> eventManager.getTicketCategoryById(specialCode.get().getTicketCategoryId(), event.getId())).isPresent()) { return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", "")); } if (specialCode.get().getStatus() != SpecialPrice.Status.FREE) { return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", "")); } } else if (promotionCodeDiscount.isPresent() && !promotionCodeDiscount.get().isCurrentlyValid(event.getZoneId(), now)) { return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", "")); } else if (!specialCode.isPresent() && !promotionCodeDiscount.isPresent()) { return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", "")); } if (maybeSpecialCode.isPresent() && !model.asMap().containsKey("hasErrors")) { if (specialCode.isPresent()) { SessionUtil.saveSpecialPriceCode(maybeSpecialCode.get(), request); } else if (promotionCodeDiscount.isPresent()) { SessionUtil.savePromotionCodeDiscount(maybeSpecialCode.get(), request); } return ValidationResult.success(); } return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", "")); }
From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java
public ApacheHttpClient4Factory(final HttpClientDefaults clientDefaults, @Nullable final Set<? extends HttpClientObserver> httpClientObservers) { Preconditions.checkArgument(clientDefaults != null, "clientDefaults can not be null!"); this.httpClientObservers = httpClientObservers; initParams();/*w w w. j a va2 s. co m*/ registry.register(HTTP_SCHEME); try { final TrustManager[] trustManagers = new TrustManager[] { getTrustManager(clientDefaults) }; final KeyManager[] keyManagers = getKeyManagers(clientDefaults); final SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); registry.register(new Scheme("https", HTTPS_PORT, sslSocketFactory)); } catch (GeneralSecurityException ce) { throw new IllegalStateException(ce); } catch (IOException ioe) { throw new IllegalStateException(ioe); } connectionManager = new ThreadSafeClientConnManager(registry); defaultAcceptEncoding = StringUtils.trimToNull(clientDefaults.getDefaultAcceptEncoding()); }
From source file:com.webbfontaine.valuewebb.utils.TTMailUtils.java
static List<String> extractRecepients(CharSequence str) { String[] recepients = RECIPIENT_PATTERN.split(str); List<String> retVal = new ArrayList<>(recepients.length); for (String recepient : recepients) { if ((recepient = StringUtils.trimToNull(recepient)) != null) { retVal.add(recepient);//from www . ja va 2 s . c o m } } return retVal; }