List of usage examples for org.springframework.util StringUtils hasLength
public static boolean hasLength(@Nullable String str)
From source file:org.encuestame.mvc.validator.ValidateOperations.java
/** * * @param email//from w w w . j av a2s. co m * @return */ public Boolean validateEmail(final String email) { log.debug("email validateEmail " + email); Boolean valid = false; if (emailPattern.matcher(email).matches() && StringUtils.hasLength(email)) { log.warn("email valid"); getMessages().put("email", "email good format"); valid = true; } else { log.debug("email format not valid"); getMessages().put("email", "email wrong valid"); } return valid; }
From source file:org.fao.geonet.kernel.KeywordBean.java
/** * Creates thesaurus name element./* ww w. jav a2 s .com*/ * * @param kb * @return */ private static Element createThesaurusNameElt(KeywordBean kb) { Element thesaurusName = new Element("thesaurusName", Namespaces.GMD); Element citation = new Element("CI_Citation", Namespaces.GMD); Element title = new Element("title", Namespaces.GMD); Element cs = new Element("CharacterString", Namespaces.GCO); Element date = new Element("date", Namespaces.GMD); cs.setText(kb.thesaurusTitle); if (StringUtils.hasLength(kb.thesaurusDate)) { Element ciDateEl = new Element("CI_Date", Namespaces.GMD); Element ciDateDateEl = new Element("date", Namespaces.GMD); Element ciDateDateGcoDateEl = new Element("Date", Namespaces.GCO); ciDateDateGcoDateEl.setText(kb.thesaurusDate); Element ciDateDatetypeEl = new Element("dateType", Namespaces.GMD); Element ciDateDatetypeCodeEl = new Element("CI_DateTypeCode", Namespaces.GMD); ciDateDatetypeCodeEl.setAttribute("codeList", "http://standards.iso.org/ittf/PubliclyAvailableStandards/ISO_19139_Schemas/resources/Codelist/ML_gmxCodelists.xml#CI_DateTypeCode"); ciDateDatetypeCodeEl.setAttribute("codeListValue", "publication"); ciDateDatetypeEl.addContent(ciDateDatetypeCodeEl); ciDateDateEl.addContent(ciDateDateGcoDateEl); ciDateEl.addContent(0, ciDateDateEl); ciDateEl.addContent(1, ciDateDatetypeEl); date.addContent(ciDateEl); } else { date.setAttribute("nilReason", "unknown", Namespaces.GCO); } title.addContent((Content) cs.clone()); Element id = createIdentifier("geonetwork.thesaurus." + kb.thesaurusKey, kb.downloadUrl); citation.addContent(0, title); citation.addContent(1, date); citation.addContent(2, id); thesaurusName.addContent(citation); return thesaurusName; }
From source file:org.georchestra.console.ws.backoffice.users.UsersController.java
/** * Create a new account from the body request. * * @param is//from w w w . j a v a2s . co m * @return * @throws IOException */ private Account createAccountFromRequestBody(ServletInputStream is) throws IllegalArgumentException, IOException { JSONObject json; try { json = new JSONObject(FileUtils.asString(is)); } catch (JSONException e) { LOG.error(e.getMessage()); throw new IOException(e); } String givenName = RequestUtil.getFieldValue(json, UserSchema.GIVEN_NAME_KEY); String surname = RequestUtil.getFieldValue(json, UserSchema.SURNAME_KEY); String email = RequestUtil.getFieldValue(json, UserSchema.MAIL_KEY); String postalAddress = RequestUtil.getFieldValue(json, UserSchema.POSTAL_ADDRESS_KEY); String postOfficeBox = RequestUtil.getFieldValue(json, UserSchema.POST_OFFICE_BOX_KEY); String postalCode = RequestUtil.getFieldValue(json, UserSchema.POSTAL_CODE_KEY); String street = RequestUtil.getFieldValue(json, UserSchema.STREET_KEY); String locality = RequestUtil.getFieldValue(json, UserSchema.LOCALITY_KEY); String phone = RequestUtil.getFieldValue(json, UserSchema.TELEPHONE_KEY); String facsimile = RequestUtil.getFieldValue(json, UserSchema.FACSIMILE_KEY); String title = RequestUtil.getFieldValue(json, UserSchema.TITLE_KEY); String description = RequestUtil.getFieldValue(json, UserSchema.DESCRIPTION_KEY); String manager = RequestUtil.getFieldValue(json, UserSchema.MANAGER_KEY); String context = RequestUtil.getFieldValue(json, UserSchema.CONTEXT_KEY); String org = RequestUtil.getFieldValue(json, UserSchema.ORG_KEY); if (givenName == null) throw new IllegalArgumentException("First Name is required"); if (surname == null) throw new IllegalArgumentException("Last Name is required"); if (email == null) throw new IllegalArgumentException("EMail is required"); // Use specified login if not empty String uid = RequestUtil.getFieldValue(json, UserSchema.UID_KEY); if (!StringUtils.hasLength(uid)) try { uid = createUid(givenName, surname); } catch (DataServiceException e) { LOG.error(e.getMessage()); throw new IOException(e); } String commonName = AccountFactory.formatCommonName(givenName, surname); Account a = AccountFactory.createFull(uid, commonName, surname, givenName, email, title, phone, description, postalAddress, postalCode, "", postOfficeBox, "", street, locality, facsimile, "", "", "", "", manager, context, org); String shadowExpire = RequestUtil.getFieldValue(json, UserSchema.SHADOW_EXPIRE_KEY); if (StringUtils.hasLength(shadowExpire)) { try { a.setShadowExpire((new SimpleDateFormat("yyyy-MM-dd")).parse(shadowExpire)); } catch (ParseException e) { LOG.error(e.getMessage()); throw new IllegalArgumentException(e); } } return a; }
From source file:org.geoserver.security.IncludeQueryStringAntPathRequestMatcher.java
/** * Creates a matcher with the supplied pattern which will match all HTTP methods. * * @param pattern the ant pattern to use for matching * @param httpMethod the HTTP method. The {@code matches} method will return false if the incoming request doesn't * have the same method.//w w w . j av a 2 s . c o m */ public IncludeQueryStringAntPathRequestMatcher(String pattern, String httpMethod) { Assert.hasText(pattern, "Pattern cannot be null or empty"); String queryStringPattern = ""; String originalPattern = pattern; // check for querystring pattern existance if (pattern.contains(QUERYSTRING_SEPARATOR)) { queryStringPattern = pattern.substring(pattern.indexOf(QUERYSTRING_SEPARATOR) + 1); pattern = pattern.substring(0, pattern.indexOf(QUERYSTRING_SEPARATOR)); } if (pattern.equals(MATCH_ALL) || pattern.equals("**")) { pattern = MATCH_ALL; matcher = null; } else { pattern = pattern.toLowerCase(); // If the pattern ends with {@code /**} and has no other wildcards, then optimize to a sub-path match if (pattern.endsWith(MATCH_ALL) && pattern.indexOf('?') == -1 && pattern.indexOf("*") == pattern.length() - 2) { matcher = new SubpathMatcher(pattern.substring(0, pattern.length() - 3)); } else { matcher = new SpringAntMatcher(pattern); } } this.pattern = originalPattern; // build query string matcher if needed if (StringUtils.hasLength(queryStringPattern)) { queryStringMatcher = new QueryStringMatcher(queryStringPattern); } else { queryStringMatcher = null; } this.httpMethod = StringUtils.hasText(httpMethod) ? HttpMethod.valueOf(httpMethod) : null; }
From source file:org.geoserver.security.ldap.GeoserverLdapBindAuthenticator.java
/** * If userFilter is defined we extract user data using the filter and * dnPattern (if defined) to transform username for authentication. * // w w w. j a v a 2 s . c o m * @param authentication * @return */ protected DirContextOperations authenticateUsingFilter(Authentication authentication) { DirContextOperations user = null; Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); // format given username if required if (userFormat != null && !userFormat.equals("")) { username = MessageFormat.format(userFormat, username); } if (!StringUtils.hasLength(password)) { logger.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } DirContext ctx = null; String userDnStr = ""; try { ctx = getContextSource().getContext(username, password); // Check for password policy control PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx); logger.debug("Retrieving user object using filter..."); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); user = SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, "", userFilter, new Object[] { username }); userDnStr = user.getDn().toString(); if (ppolicy != null) { user.setAttributeValue(ppolicy.getID(), ppolicy); } } catch (NamingException e) { // This will be thrown if an invalid user name is used and the // method may // be called multiple times to try different names, so we trap the // exception // unless a subclass wishes to implement more specialized behaviour. if ((e instanceof org.springframework.ldap.AuthenticationException) || (e instanceof org.springframework.ldap.OperationNotSupportedException)) { handleBindException(userDnStr, username, e); } else { throw e; } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { LdapUtils.closeContext(ctx); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:org.geoserver.security.PropertyAuthenticationKeyMapper.java
@Override synchronized public GeoServerUser getUser(String key) throws IOException { checkProperties();/*from w ww. j a va 2 s .c o m*/ if (authKeyProps == null) { synchronize(); } if (fileWatcher.isStale()) // reload if necessary authKeyProps = fileWatcher.getProperties(); String userName = authKeyProps.getProperty(key); if (StringUtils.hasLength(userName) == false) { LOGGER.warning("Cannot find user for auth key: " + key); return null; } GeoServerUser theUser = null; try { theUser = (GeoServerUser) getUserGroupService().loadUserByUsername(userName); } catch (UsernameNotFoundException ex) { LOGGER.warning( "Cannot find user: " + userName + " in user/group service: " + getUserGroupServiceName()); return null; } if (theUser.isEnabled() == false) { LOGGER.info("Found user " + theUser.getUsername() + " for key " + key + ", but this user is disabled"); return null; } return theUser; }
From source file:org.hopen.framework.rewrite.CachedIntrospectionResults.java
PropertyDescriptor getPropertyDescriptor(String name) { PropertyDescriptor pd = this.propertyDescriptorCache.get(name); if (pd == null && StringUtils.hasLength(name)) { // Same lenient fallback checking as in PropertyTypeDescriptor... pd = this.propertyDescriptorCache.get(name.substring(0, 1).toLowerCase() + name.substring(1)); if (pd == null) { pd = this.propertyDescriptorCache.get(name.substring(0, 1).toUpperCase() + name.substring(1)); }/*from w w w.j a va2s . com*/ } return (pd == null || pd instanceof GenericTypeAwarePropertyDescriptor ? pd : buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd)); }
From source file:org.kuali.continuity.security.SecurityUtil.java
/** * Sets the cookie on the response/* w w w. j a v a2 s . c o m*/ * * @param tokens the tokens which will be encoded to make the cookie value. * @param maxAge the value passed to {@link Cookie#setMaxAge(int)} * @param request the request * @param response the response to add the cookie to. */ public static void setCookie(String[] tokens, int maxAge, String key, HttpServletRequest request, HttpServletResponse response) { String cookieValue = encodeCookie(tokens); Cookie cookie = new Cookie(key, cookieValue); cookie.setMaxAge(maxAge); cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath() : "/"); response.addCookie(cookie); }
From source file:org.openmrs.api.impl.LocationServiceImpl.java
/** * @see org.openmrs.api.LocationService#saveLocation(org.openmrs.Location) *///from ww w. j av a 2s. c o m public Location saveLocation(Location location) throws APIException { if (location.getName() == null) { throw new APIException("Location.name.required", (Object[]) null); } // Check for transient tags. If found, try to match by name and overwrite, otherwise throw exception. if (location.getTags() != null) { for (LocationTag tag : location.getTags()) { // only check transient (aka non-precreated) location tags if (tag.getLocationTagId() == null) { if (!StringUtils.hasLength(tag.getName())) { throw new APIException("Location.tag.name.required", (Object[]) null); } LocationTag existing = Context.getLocationService().getLocationTagByName(tag.getName()); if (existing != null) { location.removeTag(tag); location.addTag(existing); } else { throw new APIException("Location.cannot.add.transient.tags", (Object[]) null); } } } } CustomDatatypeUtil.saveAttributesIfNecessary(location); return dao.saveLocation(location); }
From source file:org.openmrs.api.impl.LocationServiceImpl.java
/** * @see org.openmrs.api.LocationService#getAddressTemplate() */// www .j a va 2 s .c o m @Override @Transactional(readOnly = true) public String getAddressTemplate() throws APIException { String addressTemplate = Context.getAdministrationService() .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ADDRESS_TEMPLATE); if (!StringUtils.hasLength(addressTemplate)) { addressTemplate = OpenmrsConstants.DEFAULT_ADDRESS_TEMPLATE; } return addressTemplate; }