List of usage examples for org.apache.commons.lang3 StringUtils trim
public static String trim(final String str)
Removes control characters (char <= 32) from both ends of this String, handling null by returning null .
The String is trimmed using String#trim() .
From source file:de.micromata.genome.gwiki.page.impl.wiki.macros.GWikiCodeMacro.java
@Override public boolean renderImpl(GWikiContext ctx, MacroAttributes attrs) { if (RenderModes.ForIndex.isSet(ctx.getRenderMode()) == true) { ctx.append(WebUtils.escapeHtml(attrs.getBody())); return true; }/*from ww w .j a v a 2 s . c o m*/ String body = attrs.getBody(); body = StringUtils.trim(body); String clang = determineLang(body); if (RenderModes.ForRichTextEdit.isSet(ctx.getRenderMode()) == true) { ctx.append("<pre"); if (StringUtils.isNotBlank(clang) == true) { ctx.append(" class='language-" + clang + "'"); } ctx.append(" contenteditable='false'>"); ctx.append(WebUtils.escapeHtml(body)); ctx.append("</pre>"); return true; } // // TODO attributes rendering // String body = attrs.getBody(); // // body = WebUtils.escapeHtml(body); // // ctx.append("<pre class=\"wikiCode\""); // Html2WikiTransformInfo.renderMacroArgs(ctx, attrs); // ctx.append(">").append(body).append("</pre>"); // return true; // } boolean forText = RenderModes.ForText.isSet(ctx.getRenderMode()); ctx.append("<pre><code"); if (StringUtils.isNotBlank(clang) == true) { ctx.append(" class='language-" + clang + "'"); } if (forText == false) { body = StringEscapeUtils.escapeXml(body); } ctx.append(">").append(body).append("</code></pre>"); return true; }
From source file:com.wxine.android.model.Community.java
public Set<String> getFriends() { try {//from w ww.ja v a 2 s .c om String[] array = friend.split(","); for (String a : array) { if (StringUtils.isNotBlank(a)) { friends.add(StringUtils.trim(StringUtils.strip(a))); } } } catch (Exception e) { } return friends; }
From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineValidator.java
/** * Validates the contents of a provided {@link MicroPipelineConfiguration} for being compliant with a required format * and errors that may be inferred from provided contents * @param configuration/*ww w . j ava2 s .c om*/ * @return */ public MicroPipelineValidationResult validate(final MicroPipelineConfiguration configuration) { /////////////////////////////////////////////////////////////////////////////////// // validate configuration, components and queues for not being null if (configuration == null) return MicroPipelineValidationResult.MISSING_CONFIGURATION; if (configuration.getComponents() == null || configuration.getComponents().isEmpty()) return MicroPipelineValidationResult.MISSING_COMPONENTS; if (configuration.getQueues() == null || configuration.getQueues().isEmpty()) return MicroPipelineValidationResult.MISSING_QUEUES; // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // validate queues and store their identifiers in set for further look-ups executed // on component evaluation Set<String> queueIdentifiers = new HashSet<>(); for (final StreamingMessageQueueConfiguration queueCfg : configuration.getQueues()) { // queue identifier must neither be null nor empty if (StringUtils.isBlank(queueCfg.getId())) return MicroPipelineValidationResult.MISSING_QUEUE_ID; // convert to trimmed lower-case representation and check if it is unique String tempId = StringUtils.lowerCase(StringUtils.trim(queueCfg.getId())); if (queueIdentifiers.contains(tempId)) return MicroPipelineValidationResult.NON_UNIQUE_QUEUE_ID; queueIdentifiers.add(tempId); } // /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // validate components Set<String> componentIdentifiers = new HashSet<>(); for (final MicroPipelineComponentConfiguration componentCfg : configuration.getComponents()) { MicroPipelineValidationResult componentValidationResult = validateComponent(componentCfg, queueIdentifiers, componentIdentifiers); if (componentValidationResult != MicroPipelineValidationResult.OK) return componentValidationResult; // add identifier to set of managed components componentIdentifiers.add(StringUtils.lowerCase(StringUtils.trim(componentCfg.getId()))); } // /////////////////////////////////////////////////////////////////////////////////// // no errors found so far which could be inferred from configuration return MicroPipelineValidationResult.OK; }
From source file:alfio.controller.form.PaymentForm.java
public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event, List<TicketFieldConfiguration> fieldConf) { List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies(); Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod); PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains) .orElse(PaymentProxy.STRIPE); boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0; boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1; if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD); } else if (priceGreaterThanZero && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN); }/*from w w w . j a v a 2 s .c o m*/ if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) { bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED); } email = StringUtils.trim(email); fullName = StringUtils.trim(fullName); firstName = StringUtils.trim(firstName); lastName = StringUtils.trim(lastName); billingAddress = StringUtils.trim(billingAddress); ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL); rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255); if (event.mustUseFirstAndLastName()) { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName", ErrorsCode.STEP_2_EMPTY_FIRSTNAME); rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255); ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME); rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255); } else { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME); rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255); } rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS, billingAddress, 450); if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) { bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL); } if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event), email, billingAddress, hmac, event)) { bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC); } if (!postponeAssignment) { boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream() .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event))) .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent(); if (!success) { bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA); } } }
From source file:com.threewks.thundr.http.SyntheticHttpServletResponse.java
@Override public void setContentType(String type) { String[] contentTypeAndCharacterEncoding = type == null ? new String[] { null } : type.split(";"); this.contentType = StringUtils.trim(StringUtils.lowerCase(contentTypeAndCharacterEncoding[0])); if (contentTypeAndCharacterEncoding.length > 1) { String encoding = StringUtils.trimToEmpty(contentTypeAndCharacterEncoding[1]); encoding = encoding.replaceAll("(?i)charset=", ""); setCharacterEncoding(encoding);//from w w w . ja va 2 s. c o m } }
From source file:com.thoughtworks.go.domain.ArtifactPlan.java
public void setDest(String dest) { this.dest = StringUtils.trim(dest); }
From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java
@Override public Response validate(Response response, ConnectorMessage connectorMessage) { HL7v2ResponseValidationProperties responseValidationProperties = getReplacedResponseValidationProperties( connectorMessage);/* w w w . j ava 2 s . c o m*/ String[] successfulACKCodes = StringUtils.split(responseValidationProperties.getSuccessfulACKCode(), ','); String[] errorACKCodes = StringUtils.split(responseValidationProperties.getErrorACKCode(), ','); String[] rejectedACKCodes = StringUtils.split(responseValidationProperties.getRejectedACKCode(), ','); boolean validateMessageControlId = responseValidationProperties.isValidateMessageControlId(); String responseData = response.getMessage(); if (StringUtils.isNotBlank(responseData)) { try { if (responseData.trim().startsWith("<")) { // XML response received Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new CharArrayReader(responseData.toCharArray()))); String ackCode = XPathFactory.newInstance().newXPath().compile("//MSA.1/text()").evaluate(doc) .trim(); boolean rejected = Arrays.asList(rejectedACKCodes).contains(ackCode); boolean error = rejected || Arrays.asList(errorACKCodes).contains(ackCode); if (error || rejected) { String msa3 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//MSA.3/text()").evaluate(doc)); String err1 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//ERR.1/text()").evaluate(doc)); handleNACK(response, rejected, msa3, err1); } else if (Arrays.asList(successfulACKCodes).contains(ackCode)) { if (validateMessageControlId) { String msa2 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//MSA.2/text()").evaluate(doc)); String originalControlID = getOriginalControlId(connectorMessage); if (!StringUtils.equals(msa2, originalControlID)) { handleInvalidControlId(response, originalControlID, msa2); } else { response.setStatus(Status.SENT); } } else { response.setStatus(Status.SENT); } } } else { // ER7 response received if (serializationProperties.isConvertLineBreaks()) { responseData = StringUtil.convertLineBreaks(responseData, serializationSegmentDelimiter); } int index = -1; boolean valid = true; // Attempt to find the MSA segment using the segment delimiters in the serialization properties if ((index = responseData.indexOf(serializationSegmentDelimiter + "MSA")) >= 0) { // MSA found; add the length of the segment delimiter, MSA, and field separator to get to the index of MSA.1 index += serializationSegmentDelimiter.length() + 4; if (index < responseData.length()) { boolean rejected = startsWithAny(responseData, rejectedACKCodes, index); boolean error = rejected || startsWithAny(responseData, errorACKCodes, index); char fieldSeparator = responseData.charAt(index - 1); if (error || rejected) { String msa3 = null; String err1 = null; // Index of MSA.2 index = responseData.indexOf(fieldSeparator, index); if (index >= 0) { // Index of MSA.3 index = responseData.indexOf(fieldSeparator, index + 1); if (index >= 0) { // Find the next index of either the field separator or segment delimiter, and then the resulting substring String tempSegment = StringUtils.substring(responseData, index + 1); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { msa3 = StringUtils.substring(tempSegment, 0, index); } else { msa3 = StringUtils.substring(tempSegment, 0); } } } if ((index = responseData.indexOf(serializationSegmentDelimiter + "ERR")) >= 0) { // ERR found; add the length of the segment delimiter, ERR, and field separator to get to the index of ERR.1 index += serializationSegmentDelimiter.length() + 4; // Find the next index of either the field separator or segment delimiter, and then the resulting substring String tempSegment = StringUtils.substring(responseData, index); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { err1 = StringUtils.substring(tempSegment, 0, index); } else { err1 = StringUtils.substring(tempSegment, 0); } } handleNACK(response, rejected, msa3, err1); } else if (startsWithAny(responseData, successfulACKCodes, index)) { if (validateMessageControlId) { String msa2 = ""; index = responseData.indexOf(fieldSeparator, index); if (index >= 0) { String tempSegment = StringUtils.substring(responseData, index + 1); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { msa2 = StringUtils.substring(tempSegment, 0, index); } else { msa2 = StringUtils.substring(tempSegment, 0); } } String originalControlID = getOriginalControlId(connectorMessage); if (!StringUtils.equals(msa2, originalControlID)) { handleInvalidControlId(response, originalControlID, msa2); } else { response.setStatus(Status.SENT); } } else { response.setStatus(Status.SENT); } } else { valid = false; } } else { valid = false; } } else { valid = false; } if (!valid) { response.setStatus(Status.QUEUED); response.setStatusMessage("Invalid HL7 v2.x acknowledgement received."); response.setError(response.getStatusMessage()); } } } catch (Exception e) { response.setStatus(Status.QUEUED); response.setStatusMessage("Error validating response: " + e.getMessage()); response.setError(ErrorMessageBuilder.buildErrorMessage(this.getClass().getSimpleName(), response.getStatusMessage(), e)); } } else { response.setStatus(Status.QUEUED); response.setStatusMessage("Empty or blank response received."); response.setError(response.getStatusMessage()); } return response; }
From source file:com.ottogroup.bi.spqr.pipeline.queue.memory.InMemoryStreamingMessageQueue.java
/** * @see com.ottogroup.bi.spqr.pipeline.queue.StreamingMessageQueue#initialize(java.util.Properties) *//*from w ww.j av a 2 s. c o m*/ public void initialize(Properties properties) throws RequiredInputMissingException { //////////////////////////////////////////////////////////////////////////////// // extract and validate input if (properties == null) throw new RequiredInputMissingException("Missing required properties"); if (StringUtils.isBlank(this.id)) throw new RequiredInputMissingException("Missing required queue identifier"); this.queueWaitStrategy = getWaitStrategy( StringUtils.trim(properties.getProperty(CFG_QUEUE_MESSAGE_WAIT_STRATEGY))); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // initialize producer and consumer instances this.queueProducer = new InMemoryStreamingMessageQueueProducer(this.id, this.queue, this.queueWaitStrategy); this.queueConsumer = new InMemoryStreamingMessageQueueConsumer(this.id, this.queue, this.queueWaitStrategy); //////////////////////////////////////////////////////////////////////////////// logger.info("In-memory streaming message queue successfully initialized"); }
From source file:com.nridge.connector.fs.con_fs.core.CSVDocument.java
/** * Extracts the next row of fields and populates them into a newly * created data bag.//from www.j av a 2s . c o m * * ToDo: Support for multi-value. * * @return Data bag instance. * * @throws IOException Identifies an I/O error. */ public DataBag extractNext() throws IOException { Date cellDate; DataBag dataBag; String mvDelimiter; DataField dataField; String cellName, cellValue; Logger appLogger = mAppMgr.getLogger(this, "extractNext"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mCSVListReader == null) { dataBag = null; appLogger.error("The CSV Document has not been successfully opened for processing."); } else { List<String> rowCells = mCSVListReader.read(); if (rowCells == null) dataBag = null; else { dataBag = new DataBag(mBag); dataBag.resetValuesWithDefaults(); int colCount = rowCells.size(); for (int col = 0; col < colCount; col++) { cellValue = rowCells.get(col); cellName = StringUtils.trim(mColumnHeaders[col]); if ((StringUtils.isNotEmpty(cellName)) && (StringUtils.isNotEmpty(cellValue)) && (!Solr.isSolrReservedFieldName(cellName))) { dataField = dataBag.getFieldByName(cellName); if (dataField == null) { String msgStr = String.format("%s: Does not match any known fields.", cellName); throw new IOException(msgStr); } else { if (dataField.isMultiValue()) { mvDelimiter = dataField.getFeature(Field.FEATURE_MV_DELIMITER); if (StringUtils.isNotEmpty(mvDelimiter)) dataField.setValues(StrUtl.expandToList(cellValue, mvDelimiter.charAt(0))); else dataField.setValues(StrUtl.expandToList(cellValue, StrUtl.CHAR_PIPE)); } else { if (dataField.isTypeDateOrTime()) { cellDate = Field.createDate(cellValue, mCellDateFormat); dataField.setValue(cellDate); } else dataField.setValue(cellValue); } } } } } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return dataBag; }
From source file:com.smilonet.common.zk.InputMessageTextBox.java
private void createBox() { setWidth("350px"); setHeight("150px"); setTitle(Labels.getLabel("message.Information.PleaseInsertText")); setId("confBox"); setVisible(true);/*from ww w.j av a2 s .co m*/ setClosable(true); addEventListener("onOK", new OnCloseListener()); // Hbox hbox = new Hbox(); // hbox.setWidth("100%"); // hbox.setParent(this); // Checkbox cb = new Checkbox(); // cb.setLabel(Labels.getLabel("common.All")); // cb.setChecked(true); Separator sp = new Separator(); sp.setParent(this); textbox.setWidth("98%"); textbox.setHeight("80px"); textbox.setMultiline(true); textbox.setRows(5); textbox.setParent(this); Separator sp2 = new Separator(); sp2.setBar(true); sp2.setParent(this); Button btnSend = new Button(); btnSend.setLabel(Labels.getLabel("common.Send")); btnSend.setParent(this); btnSend.addEventListener("onClick", new EventListener() { @Override public void onEvent(Event event) throws Exception { // Check if empty, than do not send if (StringUtils.isEmpty(StringUtils.trim(textbox.getText()))) { onClose(); return; } msg = msg + ZkDateFormat.getDateTimeLongFormater().format(new Date()) + " / " + Labels.getLabel("common.Message.From") + " " + userName + ":" + "\n"; msg = msg + textbox.getText(); msg = msg + "\n" + "_____________________________________________________" + "\n"; onClose(); } }); try { doModal(); } catch (SuspendNotAllowedException e) { log.error("", e); } }