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:com.hmsinc.epicenter.webapp.remoting.GeographyService.java
/** * Automagically completes a Geography name. * /*from w ww .j a va 2 s .c o m*/ * If entity is null, the current user's visible region is used as bounds. * * @param query * @return */ @Secured("ROLE_USER") @Transactional(readOnly = true) @RemoteMethod public Collection<GeographyDTO> autocompleteGeography(final Long orgId, String query) { logger.debug(query); Organization entity = null; if (orgId != null) { entity = permissionRepository.load(orgId, Organization.class); Validate.notNull(entity, "Invalid organization id: " + orgId); SpatialSecurity.checkPermission(getPrincipal(), entity); } final Set<Geography> geolist = new LinkedHashSet<Geography>(); if (query.equals("ALL")) { geolist.addAll(getVisibleRegions(entity)); } else { final String q = StringUtils.trimToNull(StringUtils.trimToEmpty(query).replaceAll(",+$", "")); if (q != null) { if (q.matches("^\\w\\w$")) { // match single state by abbreviatation final State state = geographyRepository.getStateByAbbreviation(q); if (state != null) { geolist.add(state); } } else if (q.matches("^\\w\\w,.*")) { // match something starting with state abbreviation final String[] fragments = q.split(","); final State state = geographyRepository.getStateByAbbreviation(fragments[0]); if (state != null) { if (fragments.length > 1 && StringUtils.trimToNull(fragments[1]) != null) { geolist.addAll(getGeographiesInState(state, fragments[1])); } else { geolist.add(state); } } } else if (q.matches("^\\w.*,\\s*\\w\\w$")) { // match something comma state abbreviation final String[] fragments = q.split(","); final String first = StringUtils.trimToNull(fragments[0]); if (first != null && fragments.length > 1) { final String second = StringUtils.trimToNull(fragments[1]); if (second != null) { final State state = geographyRepository.getStateByAbbreviation(second); if (state != null) { geolist.addAll(getGeographiesInState(state, first)); } } } } else if (q.matches("^\\w\\w\\w.*,\\s*\\w\\w\\w.*")) { // match something comma something, each part being > 2 // characters final String[] fragments = q.split(","); final String first = StringUtils.trimToNull(fragments[0]); if (first != null && fragments.length > 1) { final String second = StringUtils.trimToNull(fragments[1]); if (second != null) { String other = null; State state = null; // Find out which one is a state State s = geographyRepository.getGeography(first, State.class); if (s != null) { state = s; other = second; } else { s = geographyRepository.getGeography(second, State.class); if (s != null) { state = s; other = first; } } if (other != null && state != null) { geolist.addAll(getGeographiesInState(state, other)); } } } } else { // Match anything final List<Geography> g = new ArrayList<Geography>(); // Search region, state, county, zipcode if (StringUtils.isNumeric(q)) { g.addAll(geographyRepository.searchGeographies(q, Zipcode.class)); } else { g.addAll(geographyRepository.searchGeographies(q, Region.class)); if (g.size() != 1) { final List<State> states = geographyRepository.searchGeographies(q, State.class); if (states.size() == 1) { g.clear(); } g.addAll(states); } if (g.size() != 1) { g.addAll(geographyRepository.searchGeographies(stripCountyFromQuery(q), County.class)); } } geolist.addAll(g); } // If we have a single match, find the objects contained inside // it. if (geolist.size() == 1) { geolist.addAll(getContainedGeographies(geolist.iterator().next())); } if (entity == null) { for (Organization org : getPrincipal().getOrganizations()) { geolist.addAll(getVisibleRegions(org)); } } else { geolist.addAll(getVisibleRegions(entity)); } } } // Filter the list to the user's permissions // TODO: Unwind the collection and drill down if limited visibility. return entity == null ? filterSpatialCollection(getPrincipal(), geolist, true) : filterSpatialCollection(entity, geolist, true); }
From source file:de.willuhn.jameica.hbci.passports.pintan.server.PinTanConfigImpl.java
/** * @see de.willuhn.jameica.hbci.passports.pintan.rmi.PinTanConfig#getHBCIVersion() *//*w w w. j a v a 2 s . co m*/ public String getHBCIVersion() throws RemoteException { String ppVersion = StringUtils.trimToNull(passport.getHBCIVersion()); return settings.getString(getID() + ".hbciversion", ppVersion != null ? ppVersion : HBCIVersion.HBCI_300.getId()); }
From source file:com.bluexml.xforms.controller.mapping.MappingToolClassFormsToAlfresco.java
/** * Process association./* w ww. ja v a 2 s . co m*/ * * @param login * the login * @param associations * the associations * @param associationType * the association type * @param associationElement * the association element * @deprecated */ @Deprecated @SuppressWarnings("unused") private void processAssociation(AlfrescoTransaction transaction, GenericAssociations associations, AssociationType associationType, Element associationElement, Map<String, String> initParams) { String targetId = null; Element targetNode = null; targetNode = associationElement; if (targetNode != null) { if (isInline(associationType)) { targetId = processSave(transaction, targetNode, initParams); } else { Element specificElement = DOMUtil.getChild(targetNode, MsgId.INT_INSTANCE_SIDEID.getText()); if (specificElement != null) { targetId = StringUtils.trimToNull(specificElement.getTextContent()); targetId = controller.patchDataId(targetId); } } } if (targetId != null) { GenericAssociation association = alfrescoObjectFactory.createGenericAssociation(); association.setQualifiedName(associationType.getAlfrescoName()); association.setAction(AssociationActions.ADD); GenericClassReference target = alfrescoObjectFactory.createGenericClassReference(); target.setQualifiedName(associationType.getType().getAlfrescoName()); target.setValue(targetId); association.setTarget(target); associations.getAssociation().add(association); } }
From source file:com.opengamma.web.config.WebConfigsResource.java
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML)//from w ww.j av a2s.c o m public Response postHTML(@FormParam("name") String name, @FormParam("configxml") String xml, @FormParam("type") String typeName) { name = StringUtils.trimToNull(name); xml = StringUtils.trimToNull(xml); typeName = StringUtils.trimToNull(typeName); final Class<?> type = (typeName != null ? data().getTypeMap().get(typeName) : null); if (name == null || xml == null || type == null) { FlexiBean out = createRootData(); if (name == null) { out.put("err_nameMissing", true); } if (xml == null) { out.put("err_xmlMissing", true); } if (typeName == null) { out.put("err_typeMissing", true); } else if (type == null) { out.put("err_typeInvalid", true); } out.put("name", StringUtils.defaultString(name)); out.put("type", StringUtils.defaultString(typeName)); out.put("xml", StringUtils.defaultString(xml)); String html = getFreemarker().build(HTML_DIR + "config-add.ftl", out); return Response.ok(html).build(); } final Object configObj = parseXML(xml, type); ConfigItem<?> item = ConfigItem.of(configObj); item.setName(name); item.setType(type); ConfigDocument doc = new ConfigDocument(item); ConfigDocument added = data().getConfigMaster().add(doc); URI uri = data().getUriInfo().getAbsolutePathBuilder().path(added.getUniqueId().toLatest().toString()) .build(); return Response.seeOther(uri).build(); }
From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java
/** * Speichert den Kontoauszug in einer Datei. * @param ka der Kontoauszug.// ww w .j a v a 2 s .co m * @param target die Datei, in der der Kontoauszug gespeichert werden soll. * @throws ApplicationException */ public static void store(Kontoauszug ka, File target) throws ApplicationException { if (ka == null) throw new ApplicationException(i18n.tr("Bitte whlen Sie den zu speichernden Kontoauszug")); if (target == null) throw new ApplicationException(i18n.tr("Bitte whlen Sie die Zieldatei aus")); try { // Wenn ein Pfad und Dateiname angegeben ist, dann sollte die Datei // dort auch liegen final String path = StringUtils.trimToNull(ka.getPfad()); final String name = StringUtils.trimToNull(ka.getDateiname()); if (path != null && name != null) { File file = new File(path, name); Logger.info("trying to open pdf file from: " + file); if (!file.exists()) { Logger.error("file does not exist (anymore): " + file); throw new ApplicationException(i18n .tr("Datei \"{0}\" existiert nicht mehr. Wurde sie gelscht?", file.getAbsolutePath())); } if (!file.canRead()) { Logger.error("cannot read file: " + file); throw new ApplicationException(i18n.tr("Datei \"{0}\" nicht lesbar", file.getAbsolutePath())); } FileCopy.copy(file, target, true); Logger.info("copied " + file + " to " + target); return; } final String uuid = StringUtils.trimToNull(ka.getUUID()); Logger.info("trying to open pdf file using messaging, uuid: " + uuid); // Das kann eigentlich nicht sein. Dann wuerde ja alles fehlen if (uuid == null) throw new ApplicationException(i18n.tr("Ablageort des Kontoauszuges unbekannt")); QueryMessage qm = new QueryMessage(uuid, null); Application.getMessagingFactory().getMessagingQueue("jameica.messaging.get").sendSyncMessage(qm); byte[] data = (byte[]) qm.getData(); if (data == null) { Logger.error("got no data from messaging for uuid: " + uuid); throw new ApplicationException( i18n.tr("Datei existiert nicht mehr im Archiv. Wurde sie gelscht?")); } Logger.info("got " + data.length + " bytes from messaging for uuid: " + uuid); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(target)); IOUtil.copy(new ByteArrayInputStream(data), os); } finally { IOUtil.close(os); } Logger.info("copied messaging data into file: " + target); } catch (ApplicationException ae) { throw ae; } catch (Exception e) { Logger.error("unable to open file", e); throw new ApplicationException(i18n.tr("Fehler beim ffnen des Kontoauszuges: {0}", e.getMessage())); } }
From source file:com.opengamma.web.portfolio.WebPortfoliosResource.java
@POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML)// www .jav a 2s. c o m public Response postHTML(@FormParam("name") String name) { name = StringUtils.trimToNull(name); if (name == null) { FlexiBean out = createRootData(); out.put("err_nameMissing", true); String html = getFreemarker().build(HTML_DIR + "portfolios-add.ftl", out); return Response.ok(html).build(); } URI uri = createPortfolio(name); return Response.seeOther(uri).build(); }
From source file:ch.entwine.weblounge.contentrepository.impl.index.ContentRepositoryIndex.java
/** * Adds all relevant entries for the given resource uri to the index and * returns it, probably providing a newly created uri identifier. * //from w ww . ja v a2 s . c o m * @param url * the resource uri * @return the uri * @throws IOException * if writing to the index fails * @throws ContentRepositoryException * if adding to the index fails */ public synchronized ResourceURI add(Resource<?> resource) throws IOException, ContentRepositoryException { ResourceURI uri = resource.getURI(); String id = uri.getIdentifier(); String path = StringUtils.trimToNull(uri.getPath()); long version = uri.getVersion(); // Make sure we are not asked to add a resource to the index that has the // same id as an existing one if (id != null) { SearchQuery q = new SearchQueryImpl(site).withIdentifier(id).withPreferredVersion(version).withLimit(1) .withField(PATH); SearchResultItem[] items = searchIdx.getByQuery(q).getItems(); if (items.length > 0) { long versionInIndex = (Long) ((ResourceSearchResultItem) items[0]).getMetadataByKey(VERSION) .getValue(); if (items.length == 1 && versionInIndex == version) throw new ContentRepositoryException( "Resource '" + id + "' already exists in version " + version); if (path == null) { path = (String) ((ResourceSearchResultItem) items[0]).getMetadataByKey(PATH).getValue(); resource.getURI().setPath(path); } } } // Make sure we are not asked to add a resource to the index that has the // same path as an existing one if (path != null) { SearchQuery q = new SearchQueryImpl(site).withPath(path).withPreferredVersion(version).withLimit(1) .withField(RESOURCE_ID); SearchResultItem[] items = searchIdx.getByQuery(q).getItems(); if (items.length > 0) { long versionInIndex = (Long) ((ResourceSearchResultItem) items[0]).getMetadataByKey(VERSION) .getValue(); if (items.length == 1 && versionInIndex == version) throw new ContentRepositoryException( "Resource '" + id + "' already exists in version " + version); if (id == null) { id = (String) ((ResourceSearchResultItem) items[0]).getMetadataByKey(RESOURCE_ID).getValue(); resource.getURI().setIdentifier(id); } } } // Create an id if necessary. A missing id indicates that the resource // has never been added to the index before if (id == null) { id = UUID.randomUUID().toString(); resource.setIdentifier(id); uri.setIdentifier(id); } try { searchIdx.add(resource); } catch (ContentRepositoryException e) { throw e; } catch (Throwable t) { throw new ContentRepositoryException("Error adding " + resource + " to index", t); } return uri; }
From source file:com.bluexml.side.framework.alfresco.shareLanguagePicker.LanguageSetter.java
/** * //w w w.ja v a 2s .c o m * @param req * @return */ public static HttpServletRequest getMyRequestInstance(HttpServletRequest req) { // we dont use getLanguageFromLayoutParam because this may cause loop getLanguageFromLayoutParam -> alfrescoConnector -> getMyRequestInstance -> getLanguageFromLayoutParam String value = (String) req.getSession().getAttribute(LanguageSetter.SHARE_LANG); if (StringUtils.trimToNull(value) != null) { MyHttpRequestServletAdaptator myreq = new MyHttpRequestServletAdaptator(req); String key = ACCEPT_LANGUAGE; String replace = value.replace('_', '-'); logger.debug("getMyRequestInstance set Language to " + replace); myreq.setHeader(key, replace); return myreq; } else { logger.debug("getMyRequestInstance no language stored in session use "); } return req; }
From source file:com.opengamma.web.historicaltimeseries.WebAllHistoricalTimeSeriesResource.java
private FlexiBean createSearchResultData(PagingRequest pr, String identifier, String dataSource, String dataProvider, String dataField, String observationTime, String name, UriInfo uriInfo) { FlexiBean out = createRootData();/*from w w w .j a v a 2 s .c o m*/ HistoricalTimeSeriesInfoSearchRequest searchRequest = new HistoricalTimeSeriesInfoSearchRequest(); searchRequest.setPagingRequest(pr); searchRequest.setExternalIdValue(StringUtils.trimToNull(identifier)); searchRequest.setDataSource(StringUtils.trimToNull(dataSource)); searchRequest.setDataProvider(StringUtils.trimToNull(dataProvider)); searchRequest.setDataField(StringUtils.trimToNull(dataField)); searchRequest.setObservationTime(StringUtils.trimToNull(observationTime)); searchRequest.setName(StringUtils.trimToNull(name)); MultivaluedMap<String, String> query = uriInfo.getQueryParameters(); for (int i = 0; query.containsKey("idscheme." + i) && query.containsKey("idvalue." + i); i++) { ExternalId id = ExternalId.of(query.getFirst("idscheme." + i), query.getFirst("idvalue." + i)); searchRequest.addExternalId(id); } out.put("searchRequest", searchRequest); if (data().getUriInfo().getQueryParameters().size() > 0) { ExternalIdWithDatesDisplayComparator comparator = ExternalIdWithDatesDisplayComparatorUtils .getComparator(data().getConfigSource(), ExternalIdDisplayComparatorUtils.DEFAULT_CONFIG_NAME); HistoricalTimeSeriesInfoSearchResult searchResult = data().getHistoricalTimeSeriesMaster() .search(searchRequest); for (HistoricalTimeSeriesInfoDocument doc : searchResult.getDocuments()) { // replace ids with one's sorted the way we want. ExternalIdBundleWithDates withCustomIdOrdering = doc.getInfo().getExternalIdBundle() .withCustomIdOrdering(comparator); doc.getInfo().setExternalIdBundle(withCustomIdOrdering); } out.put("searchResult", searchResult); out.put("paging", new WebPaging(searchResult.getPaging(), data().getUriInfo())); } return out; }
From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java
/** * Speichert die Profile.//from w w w .jav a 2 s .com * @param format das Format. * @param profiles die zu speichernden Profile. */ public static void store(Format format, List<Profile> profiles) { if (format == null) { Application.getMessagingFactory().sendMessage( new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR)); return; } if (profiles == null) { Application.getMessagingFactory().sendMessage( new StatusBarMessage(i18n.tr("Keine Profile angegeben"), StatusBarMessage.TYPE_ERROR)); return; } // 2. Mal schauen, ob wir ein gespeichertes Profil fuer das Format haben File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(), "csv"); if (!dir.exists()) { Logger.info("creating dir: " + dir); if (!dir.mkdirs()) { Application.getMessagingFactory() .sendMessage(new StatusBarMessage( i18n.tr("Ordner {0} kann nicht erstellt werden", dir.getAbsolutePath()), StatusBarMessage.TYPE_ERROR)); return; } } File file = new File(dir, format.getClass().getName() + ".xml"); Logger.info("writing csv profile " + file); XMLEncoder encoder = null; try { encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file))); encoder.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception e) { throw new RuntimeException(e); } }); for (Profile p : profiles) { // Das System-Profil wird nicht mit gespeichert if (p.isSystem()) continue; // Ebenso Profile ohne Namen. if (StringUtils.trimToNull(p.getName()) == null) continue; encoder.writeObject(p); } } catch (Exception e) { Logger.error("unable to store profile " + file, e); } finally { if (encoder != null) { try { encoder.close(); } catch (Exception e) { /* useless */} } } }