List of usage examples for org.apache.commons.lang StringUtils trimToNull
public static String trimToNull(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:mitm.common.dlp.impl.TextNormalizerImpl.java
@Override public void normalize(Reader input, Writer output) throws IOException { Check.notNull(input, "input"); Check.notNull(output, "output"); WordIterator wi = new WordIterator(input); String word;/*from w w w. j a va 2 s. c om*/ while ((word = wi.nextWord()) != null) { word = StringUtils.trimToNull(word); if (word != null) { /* * Unicode normalize the word to make sure the word only has one form */ word = Normalizer.normalize(word.toLowerCase(), Normalizer.Form.NFC); if (wordSkipper == null || !wordSkipper.isSkip(word)) { output.append(word).append(' '); } } } }
From source file:com.bluexml.xforms.servlets.ReadServlet.java
/** * Read./*from ww w . j a v a 2 s . c o m*/ * * @param req * the req * @param resp * the resp * * @throws ServletException * the servlet exception */ protected void read(HttpServletRequest req, HttpServletResponse resp) throws ServletException { AlfrescoController controller = AlfrescoController.getInstance(); String dataType = StringUtils.trimToNull(req.getParameter(DATA_TYPE)); if (dataType != null) { dataType = dataType.replace('_', '.'); } String dataId = StringUtils.trimToNull(req.getParameter(DATA_ID)); dataId = controller.patchDataId(dataId); String skipIdStr = StringUtils.trimToNull(req.getParameter(ID_AS_SERVLET)); boolean idAsServlet = !StringUtils.equals(skipIdStr, "false"); try { String userName = req.getParameter(MsgId.PARAM_USER_NAME.getText()); AlfrescoTransaction transaction = createTransaction(controller, userName); Document node = controller.getMappingAgent().getInstanceClass(transaction, dataType, dataId, false, idAsServlet); Source xmlSource = new DOMSource(node); Result outputTarget = new StreamResult(resp.getOutputStream()); documentTransformer.transform(xmlSource, outputTarget); } catch (Exception e) { throw new ServletException(e); } }
From source file:mitm.application.djigzo.james.matchers.IsRecipient.java
@Override public void init() { getLogger().info("Initializing matcher: " + getMatcherName()); pattern = Pattern.compile(StringUtils.defaultString(StringUtils.trimToNull(getCondition()))); }
From source file:com.novartis.pcs.ontology.rest.servlet.SynonymsServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mediaType = getExpectedMediaType(request); String pathInfo = StringUtils.trimToNull(request.getPathInfo()); if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) { response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); response.setContentLength(0);//from w w w. jav a 2s . c o m } else if (pathInfo == null || pathInfo.length() == 1) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setContentLength(0); } else { String datasourceAcronym = null; String vocabRefId = null; boolean pending = Boolean.parseBoolean(request.getParameter("pending")); int i = pathInfo.indexOf('/', 1); if (i != -1) { datasourceAcronym = pathInfo.substring(1, i); vocabRefId = pathInfo.substring(i + 1); } else { datasourceAcronym = pathInfo.substring(1); } serialize(datasourceAcronym, vocabRefId, pending, response); } }
From source file:com.bluexml.side.Integration.eclipse.branding.enterprise.wizards.migration.pages.GeneralProjectMigration.java
public void createFieldsControls(Composite composite) { this.values.put(Fields.newName.toString(), DEFAULT_VALUE_NEWNAME + projectName); createAlfrescoLibComboBox(composite, Fields.library.toString()); final Button createBooleanFieldControl = createBooleanFieldControl2(composite, "copy project", Fields.copybefore.toString(), true); final Text createTextFieldControl = createTextFieldControl(composite, "new project name", Fields.newName.toString());/*from www. j a v a 2 s .co m*/ createBooleanFieldControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { boolean selection = createBooleanFieldControl.getSelection(); createTextFieldControl.setEnabled(selection); if (!selection) { GeneralProjectMigration.this.values.put(Fields.newName.toString(), DEFAULT_VALUE_NEWNAME + projectName); checkPageComplite(); } else { GeneralProjectMigration.this.values.put(Fields.newName.toString(), StringUtils.trimToNull(createTextFieldControl.getText())); checkPageComplite(); } } }); }
From source file:com.hmsinc.epicenter.integrator.service.event.DischargeService.java
public Discharge handleEvent(HL7Message message, PatientDetail details) throws Exception { Validate.notNull(message);// w w w . j a va2 s. c o m Validate.notNull(details); // Make sure we have a patientId if (details.getPatient().getPatientId() == null) { throw new IncompleteDataException("No patient ID in message.", IncompleteDataType.PATIENT_ID); } final Discharge discharge = new Discharge(); configureInteraction(message, discharge, details); Validate.isTrue(message.getMessage() instanceof ADT_A03); final ADT_A03 adt = (ADT_A03) message.getMessage(); // Visit number (PV1-19) - REQUIRED FOR DISCHARGE discharge.setVisitNumber(StringUtils.trimToNull(adt.getPV1().getVisitNumber().getIDNumber().getValue())); if (discharge.getVisitNumber() == null) { throw new IncompleteDataException("No visit number in message.", IncompleteDataType.VISIT_NUMBER); } // Disposition (PV1-36) final IS disposition = adt.getPV1().getDischargeDisposition(); if (disposition == null) { throw new IncompleteDataException("No discharge disposition in message.", IncompleteDataType.DISCHARGE_DISPOSITION); } discharge.setDisposition(disposition.getValue()); // Parse integer since that's the main thing we'll use here. if (StringUtils.isNumeric(discharge.getDisposition())) { discharge.setDisposition(Integer.valueOf(discharge.getDisposition()).toString()); } // Discharge date (PV1-44) discharge.setInteractionDate(extractDate(adt.getPV1().getDischargeDateTime(0).getTime(), message)); if (logger.isDebugEnabled()) { logger.debug(discharge.toString()); } return discharge; }
From source file:mp.platform.cyclone.webservices.access.AccessWebServiceImpl.java
public ChangeCredentialsStatus changeCredentials(final ChangeCredentialsParameters params) { // Get and validate the parameters final String principal = params == null ? null : StringUtils.trimToNull(params.getPrincipal()); final String oldCredentials = params == null ? null : StringUtils.trimToNull(params.getOldCredentials()); final String newCredentials = params == null ? null : StringUtils.trimToNull(params.getNewCredentials()); if (principal == null || oldCredentials == null || newCredentials == null) { throw new ValidationException(); }//from w w w. j av a 2s .c o m final Channel channel = WebServiceContext.getChannel(); // Only login password and pin can be changed from here final Credentials credentials = channel.getCredentials(); if (credentials != Credentials.LOGIN_PASSWORD && credentials != Credentials.PIN) { throw new PermissionDeniedException(); } final PrincipalType principalType = channelHelper.resolvePrincipalType(params.getPrincipalType()); // Load the member Member member; try { member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.GROUP, Element.Relationships.USER); } catch (final Exception e) { return ChangeCredentialsStatus.MEMBER_NOT_FOUND; } // Check the current credentials try { accessService.checkCredentials(channel, member.getMemberUser(), oldCredentials, WebServiceContext.getRequest().getRemoteAddr(), WebServiceContext.getMember()); } catch (final InvalidCredentialsException e) { return ChangeCredentialsStatus.INVALID_CREDENTIALS; } catch (final BlockedCredentialsException e) { return ChangeCredentialsStatus.BLOCKED_CREDENTIALS; } // The login password is numeric depending on settings. Others, are always numeric boolean numericPassword; if (credentials == Credentials.LOGIN_PASSWORD) { numericPassword = settingsService.getAccessSettings().isNumericPassword(); } else { numericPassword = true; } if (numericPassword && !StringUtils.isNumeric(newCredentials)) { return ChangeCredentialsStatus.INVALID_CHARACTERS; } // Change the password try { accessService.changeMemberCredentialsByWebService(member.getMemberUser(), WebServiceContext.getClient(), newCredentials); } catch (final ValidationException e) { if (CollectionUtils.isNotEmpty(e.getGeneralErrors())) { // Actually, the only possible general error is that it is the same as another credential. // In this case, we return CREDENTIALS_ALREADY_USED return ChangeCredentialsStatus.CREDENTIALS_ALREADY_USED; } // There is a property error. Let's scrap it to determine which is it try { final ValidationError error = e.getErrorsByProperty().values().iterator().next().iterator().next(); final String key = error.getKey(); if (key.endsWith("obvious")) { // The password is too simple return ChangeCredentialsStatus.TOO_SIMPLE; } else { // Either must be numeric / must contain letters and numbers / must contain letters, numbers and special throw new Exception(); } } catch (final Exception e1) { // If there is some kind of unexpected validation result, just return as invalid return ChangeCredentialsStatus.INVALID_CHARACTERS; } } catch (final CredentialsAlreadyUsedException e) { return ChangeCredentialsStatus.CREDENTIALS_ALREADY_USED; } return ChangeCredentialsStatus.SUCCESS; }
From source file:com.opengamma.web.exchange.WebExchangeResource.java
@PUT @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML)//from w w w . j a v a 2s .c om public Response putHTML(@FormParam("name") String name, @FormParam("idscheme") String idScheme, @FormParam("idvalue") String idValue, @FormParam("regionscheme") String regionScheme, @FormParam("regionvalue") String regionValue) { if (data().getExchange().isLatest() == false) { return Response.status(Status.FORBIDDEN).entity(getHTML()).build(); } name = StringUtils.trimToNull(name); idScheme = StringUtils.trimToNull(idScheme); idValue = StringUtils.trimToNull(idValue); if (name == null || idScheme == null || idValue == null) { FlexiBean out = createRootData(); if (name == null) { out.put("err_nameMissing", true); } if (idScheme == null) { out.put("err_idschemeMissing", true); } if (idValue == null) { out.put("err_idvalueMissing", true); } if (regionScheme == null) { out.put("err_regionschemeMissing", true); } if (regionValue == null) { out.put("err_regionvalueMissing", true); } String html = getFreemarker().build(HTML_DIR + "exchange-update.ftl", out); return Response.ok(html).build(); } URI uri = updateExchange(name, idScheme, idValue, regionScheme, regionValue); return Response.seeOther(uri).build(); }
From source file:com.hmsinc.epicenter.classifier.SimpleMapClassifier.java
public List<String> classify(String text) { final List<String> result = new ArrayList<String>(); if (text != null) { final String filtered = StringUtils.trimToNull(text); if (filtered != null && classifier.containsKey(filtered)) { result.add(classifier.get(filtered)); }/*from w w w .j a v a 2 s. co m*/ } return result; }
From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java
/** * Laedt die vorhandenen Profile fuer das Format. * @param format das Format./*from w w w . j a va 2s . c o m*/ * @return die Liste der Profile. */ public static List<Profile> read(Format format) { List<Profile> result = new ArrayList<Profile>(); if (format == null) { Logger.warn("no format given"); Application.getMessagingFactory().sendMessage( new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR)); return result; } final Profile dp = format.getDefaultProfile(); result.add(dp); // System-Profil wird immer vorn einsortiert // 1. Mal schauen, ob wir gespeicherte Profil fuer das Format haben File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(), "csv"); if (!dir.exists()) return result; File file = new File(dir, format.getClass().getName() + ".xml"); if (!file.exists() || !file.canRead()) return result; Logger.info("reading csv profile " + file); XMLDecoder decoder = null; try { decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(file))); decoder.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { throw new RuntimeException(e); } }); // Es ist tatsaechlich so, dass "readObject()" nicht etwa NULL liefert, wenn keine Objekte mehr in der // Datei sind sondern eine ArrayIndexOutOfBoundsException wirft. try { for (int i = 0; i < 1000; ++i) { Profile p = (Profile) decoder.readObject(); // Migration aus der Zeit vor dem Support mulitpler Profile: // Da konnte der User nur das eine existierende Profil aendern, es wurde automatisch gespeichert // Das hatte gar keinen Namen. Falls also ein Profil ohne Name existiert (inzwischen koennen keine // mehr ohne Name gespeichert werden), dann ist es das vom User geaenderte Profil. Das machen wir // automatisch zum ersten User-spezifischen Profil if (StringUtils.trimToNull(p.getName()) == null) { p.setName(dp.getName() + " 2"); p.setSystem(false); } result.add(p); } } catch (ArrayIndexOutOfBoundsException e) { // EOF } Logger.info("read " + (result.size() - 1) + " profiles from " + file); Collections.sort(result); // Der User hat beim letzten Mal eventuell nicht alle Spalten zugeordnet. // Die wuerden jetzt hier in dem Objekt fehlen. Daher nehmen wir // noch die Spalten aus dem Default-Profil und haengen die fehlenden noch an. } catch (Exception e) { Logger.error("unable to read profile " + file, e); Application.getMessagingFactory().sendMessage(new StatusBarMessage( i18n.tr("Laden der Profile fehlgeschlagen: {0}", e.getMessage()), StatusBarMessage.TYPE_ERROR)); } finally { if (decoder != null) { try { decoder.close(); } catch (Exception e) { /* useless */} } } return result; }