List of usage examples for org.apache.commons.lang StringUtils trim
public static String trim(String str)
Removes control characters (char <= 32) from both ends of this String, handling null
by returning null
.
From source file:com.edgenius.wiki.render.macro.TableMacro.java
/** * If table/tr/th etc has default value(macroTable style in CSS). just remove them. * @param subnode/*from ww w . j a v a2s. c o m*/ */ private void removeDefaultStyleValue(HTMLNode subnode) { Map<String, String> styles = subnode.getStyle(); if (styles == null) return; if (SharedConstants.TABLE_BORDER_DEFAULT_WIDHT.equals(GwtUtils.removeUnit(styles.get("border-width")))) { subnode.removeStyle("border-width", "*"); } if (SharedConstants.TABLE_BORDER_DEFAULT_COLOR.equals(StringUtils.trim(styles.get("border-color")))) { subnode.removeStyle("border-color", "*"); } if (!StringUtils.isBlank(styles.get("border"))) { String[] borderAttr = parseBorder(styles.get("border").trim()); boolean defaultV = true; if (borderAttr[0] != null) { if (!SharedConstants.TABLE_BORDER_DEFAULT_WIDHT.equals(GwtUtils.removeUnit(borderAttr[0]))) { defaultV = false; } } if (defaultV && borderAttr[2] != null) { if (!SharedConstants.TABLE_BORDER_DEFAULT_COLOR.equals(borderAttr[2])) { defaultV = false; } } if (defaultV) { subnode.removeStyle("border", "*"); } } if ("table".equalsIgnoreCase(subnode.getTagName()) || "tr".equalsIgnoreCase(subnode.getTagName()) || "td".equalsIgnoreCase(subnode.getTagName())) { if (SharedConstants.TABLE_BG_DEFAULT_COLOR.equals(StringUtils.trim(styles.get("background-color"))) || "transparent".equalsIgnoreCase(StringUtils.trim(styles.get("background-color")))) { subnode.removeStyle("background-color", "*"); } } else if ("th".equalsIgnoreCase(subnode.getTagName())) { //TODO: does not check color(font) for th, which default value is SharedConstants.TABLE_TH_DEFAULT_COLOR if (SharedConstants.TABLE_TH_DEFAULT_BG_COLOR .equals(StringUtils.trim(styles.get("background-color")))) { subnode.removeStyle("background-color", "*"); } } }
From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Adds the resource content with language <code>language</code> to the * specified resource.// w ww. j a va 2 s .com * * @param request * the request * @param resourceId * the resource identifier * @param languageId * the language identifier * @param is * the input stream * @return the resource */ @POST @Path("/{resource}/content/{language}") @Produces(MediaType.MEDIA_TYPE_WILDCARD) public Response addFileContent(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId) { Site site = getSite(request); // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Extract the language Language language = LanguageUtils.getLanguage(languageId); if (language == null) { throw new WebApplicationException(Status.NOT_FOUND); } // Get the resource Resource<?> resource = loadResource(request, resourceId, null); if (resource == null || resource.contents().isEmpty()) { throw new WebApplicationException(Status.NOT_FOUND); } String fileName = null; String mimeType = null; File uploadedFile = null; try { // Multipart form encoding? if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload payload = new ServletFileUpload(); for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = Streams.asString(item.openStream()); if (StringUtils.isBlank(fieldValue)) continue; if (OPT_MIMETYPE.equals(fieldName)) { mimeType = fieldValue; } } else { // once the body gets read iter.hasNext must not be invoked // or the stream can not be read fileName = StringUtils.trim(item.getName()); mimeType = StringUtils.trim(item.getContentType()); uploadedFile = File.createTempFile("upload-", null); FileOutputStream fos = new FileOutputStream(uploadedFile); try { IOUtils.copy(item.openStream(), fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(fos); } } } } catch (FileUploadException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } // Octet binary stream else { try { fileName = StringUtils.trimToNull(request.getHeader("X-File-Name")); mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE)); } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } InputStream is = null; FileOutputStream fos = null; try { is = request.getInputStream(); if (is == null) throw new WebApplicationException(Status.BAD_REQUEST); uploadedFile = File.createTempFile("upload-", null); fos = new FileOutputStream(uploadedFile); IOUtils.copy(is, fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } // Has there been a file in the request? if (uploadedFile == null) throw new WebApplicationException(Status.BAD_REQUEST); // A mime type would be nice as well if (StringUtils.isBlank(mimeType)) { mimeType = detectMimeTypeFromFile(fileName, uploadedFile); if (mimeType == null) throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } // Get the current user User user = securityService.getUser(); if (user == null) throw new WebApplicationException(Status.UNAUTHORIZED); // Make sure the user has editing rights if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR)) throw new WebApplicationException(Status.UNAUTHORIZED); // Try to create the resource content InputStream is = null; ResourceContent content = null; ResourceContentReader<?> reader = null; ResourceSerializer<?, ?> serializer = serializerService .getSerializerByType(resource.getURI().getType()); try { reader = serializer.getContentReader(); is = new FileInputStream(uploadedFile); content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType); } catch (IOException e) { logger.warn("Error reading resource content {} from request", resource.getURI()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (ParserConfigurationException e) { logger.warn("Error configuring parser to read resource content {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { logger.warn("Error parsing udpated resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.BAD_REQUEST); } finally { IOUtils.closeQuietly(is); } URI uri = null; WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site, true); try { is = new FileInputStream(uploadedFile); resource = contentRepository.putContent(resource.getURI(), content, is); uri = new URI(resource.getURI().getIdentifier()); } catch (IOException e) { logger.warn("Error writing content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalStateException e) { logger.warn("Illegal state while adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.PRECONDITION_FAILED); } catch (ContentRepositoryException e) { logger.warn("Error adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (URISyntaxException e) { logger.warn("Error creating a uri for resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); } // Create the response ResponseBuilder response = Response.created(uri); response.type(MediaType.MEDIA_TYPE_WILDCARD); response.tag(ResourceUtils.getETagValue(resource)); response.lastModified(ResourceUtils.getModificationDate(resource, language)); return response.build(); } finally { FileUtils.deleteQuietly(uploadedFile); } }
From source file:com.greenline.guahao.web.module.home.controllers.mobile.user.MobileUserController.java
/** * ??// ww w .j av a 2s.c o m * * @param userDO * @param code * @param result * @return OperationJsonObject * @throws Exception */ @MethodRemark(value = "remark=??") @RequestMapping(value = "/mobile/b/updateCertNO") public String updateCertNO(HttpServletRequest request, ModelMap model, @ModelAttribute("userInfo") UserDO user) throws Exception { Long cuserId = UserCookieUtil.getUserId(request);// ?cookieuserId UserDO userDO = userManager.findUserByUserId(cuserId); boolean hasError = false; if (null == userDO) { model.put("message", ""); logger.error("cuserId=" + cuserId + "?"); return MobileConstants.M_ERROR; } if (StringUtils.isNotBlank(userDO.getCertNo()) && "15".equals(String.valueOf(userDO.getCertNo().length()))) { if (!RegexUtil.isIdCard(StringUtils.trim(user.getCertNo()))) { hasError = Boolean.TRUE; model.put("message", MobileMsgConstants.USER_CERNO_ERROR); } if (!hasError) { String certNO = UserUtil.getEighteenIDCard(userDO.getCertNo()); if (StringUtils.isNotBlank(certNO) && certNO.equals(user.getCertNo())) { // ?? UserResult ur = userManager.valiCertNo(cuserId, user.getCertNo(), userDO.getReg_type()); if (ur != null && ur.getUserDO() != null) { hasError = Boolean.TRUE; model.put("message", MobileMsgConstants.USER_CERNO_USERED); } } else { hasError = Boolean.TRUE; model.put("message", "???"); } } if (!hasError) { // certno user.setUserId(cuserId); user.setCertType("1"); UserResult r = userManager.modifyUserCertNO(user); if (r.isSystemError()) { hasError = Boolean.TRUE; model.put("message", r.getResponseDesc()); } } if (hasError) { return MobileConstants.M_UPDATE_CERTNO; } } if (userDO.getReg_type() == 3 && userDO.getLoginId().startsWith("alipay_") && userDO.getLoginId().substring(7, userDO.getLoginId().length()).length() == 16) { model.put("html5alipay", true); } userDO.setCertNo(user.getCertNo()); model.put("isPingan", DomainIndexEnum.PINGAN.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM))); model.put("isZFB", DomainIndexEnum.ZFB.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM))); model.put("isM58", DomainIndexEnum.M58.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM))); model.put("userInfo", userDO); model.put("hasUpdate", UserUtil.isUserProfileImperfection(userDO)); return MobileConstants.M_USERCENTER; }
From source file:ch.entwine.weblounge.contentrepository.impl.index.elasticsearch.ElasticSearchSearchQuery.java
/** * Stores <code>fieldValue</code> as a search term on the * <code>fieldName</code> field. * /*from w ww . j a va2s . c o m*/ * @param fieldName * the field name * @param fieldValue * the field value * @param clean * <code>true</code> to escape solr special characters in the field * value */ protected void and(String fieldName, Object fieldValue, boolean clean) { // Fix the field name, just in case fieldName = StringUtils.trim(fieldName); // Make sure the data structures are set up accordingly if (searchTerms == null) searchTerms = new HashMap<String, Set<Object>>(); Set<Object> termValues = searchTerms.get(fieldName); if (termValues == null) { termValues = new HashSet<Object>(); searchTerms.put(fieldName, termValues); } // Add the term termValues.add(fieldValue); }
From source file:com.haulmont.cuba.core.global.MetadataTools.java
/** * Return a collection of properties included into entity's name pattern (see {@link NamePattern}). * * @param metaClass entity metaclass/* w w w . j a va 2 s .co m*/ * @param useOriginal if true, and if the given metaclass doesn't define a {@link NamePattern} and if it is an * extended entity, this method tries to find a name pattern in an original entity * @return collection of the name pattern properties */ @Nonnull public Collection<MetaProperty> getNamePatternProperties(MetaClass metaClass, boolean useOriginal) { Collection<MetaProperty> properties = new ArrayList<>(); String pattern = (String) getMetaAnnotationAttributes(metaClass.getAnnotations(), NamePattern.class) .get("value"); if (pattern == null && useOriginal) { MetaClass original = metadata.getExtendedEntities().getOriginalMetaClass(metaClass); if (original != null) { pattern = (String) getMetaAnnotationAttributes(original.getAnnotations(), NamePattern.class) .get("value"); } } if (!StringUtils.isBlank(pattern)) { String value = StringUtils.substringAfter(pattern, "|"); String[] fields = StringUtils.splitPreserveAllTokens(value, ","); for (String field : fields) { String fieldName = StringUtils.trim(field); MetaProperty property = metaClass.getProperty(fieldName); if (property != null) { properties.add(metaClass.getProperty(fieldName)); } else { throw new DevelopmentException( String.format("Property '%s' is not found in %s", field, metaClass.toString()), "NamePattern", pattern); } } } return properties; }
From source file:com.greenline.guahao.web.module.home.controllers.my.reservation.ReservationProcess.java
/** * ?//from ww w .j av a 2s . co m * * @param json * @param jsonMap * @param patient * @param name */ private PatientInfoDO addPatient(OperationJsonObject json, Map<String, String> jsonMap, final PatientInfoDO patient, final String name) { PatientResult pa = new PatientResult(); // patient.setUser_id(UserCookieUtil.getUserId(request)); patient.setPatient_cert_no(StringUtils.trim(patient.getPatient_cert_no().toUpperCase())); patient.setPatient_birthday(patient.getPatient_birthday().replaceAll("-", "")); patient.setSource(UserPatientConstants.SOURCE_PORTAL); patient.setPatient_mobile(StringUtils.trim(patient.getPatient_mobile())); patient.setPatient_name(StringUtils.trim(patient.getPatient_name())); pa = patientManager.addPatient(patient); if (pa.isSystemError()) { // ? json.setHasError(Boolean.TRUE); json.setMessage(pa.getResponseDesc()); return null; } else { // ?id patient.setPatient_id(pa.getPatientInfoDO().getPatient_id()); // ????id? jsonMap.put(name + ".patient_id", String.valueOf(patient.getPatient_id())); return pa.getPatientInfoDO(); } }
From source file:eu.europeana.portal2.web.presentation.model.FullDocPage.java
/** * Returns the title of the page// w w w. ja v a2 s.co m * * @return page title */ @Override public String getPageTitle() { StringBuilder title = new StringBuilder(getBaseTitle()); String creator = getShortcutFirstValue("DcCreator"); if (creator != null) { // clean up creator first (..), [..], <..>, {..} creator = creator.replaceAll("[\\<({\\[].*?[})\\>\\]]", ""); // strip , from begin or end creator = StringUtils.strip(creator, ","); // strip spaces creator = StringUtils.trim(creator); if (StringUtils.isNotBlank(creator)) { title.append(" | ").append(creator); } } return StringUtils.left(title.toString(), 250); }
From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorBuilder.java
protected Resource loadResource(FilePath workspace) throws Exception { Resource resource = null;//ww w . ja v a2s . c o m String groovy = StringUtils.trim(this.getResourceGroovy()); String profileFromPath = getResourceFromFile(); if (StringUtils.isBlank(groovy) && StringUtils.isNotBlank(profileFromPath)) { FilePath profileGroovyFilePath = workspace.child(profileFromPath); groovy = IOUtils.toString(profileGroovyFilePath.read()); } if (StringUtils.isNotBlank(groovy)) { CompilerConfiguration compilerConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT); compilerConfiguration.setDebug(true); compilerConfiguration.setVerbose(true); compilerConfiguration.addCompilationCustomizers( new ImportCustomizer().addStarImports("org.eclipse.jetty.load.generator")); GroovyShell interpreter = new GroovyShell(Resource.class.getClassLoader(), // new Binding(), // compilerConfiguration); resource = (Resource) interpreter.evaluate(groovy); } return resource; }
From source file:com.openteach.diamond.service.DiamondServiceFactory.java
/** * /*from w w w. j a va 2s . c o m*/ * @param properties * @param handler * @return */ private static RPCProtocolProvider newRPCProtocolProvider(Properties properties, HSFNetworkServer.NetworkRequestHandler handler) { String factoryClassName = StringUtils.trim(properties.getProperty(RPC_PROVIDER_FACTORY)); if (StringUtils.isBlank(factoryClassName)) { throw new IllegalArgumentException(String.format("Please set %s", RPC_PROVIDER_FACTORY)); } try { Class<?> clazz = Class.forName(factoryClassName); RPCProtocolProviderFactory factory = (RPCProtocolProviderFactory) clazz.newInstance(); return factory.newRPCProtocolProvider(handler); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("OOPS, new addressing service failed", e); } catch (InstantiationException e) { throw new IllegalArgumentException("OOPS, new addressing service failed", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("OOPS, new addressing service failed", e); } }
From source file:ch.entwine.weblounge.contentrepository.impl.index.elasticsearch.ElasticSearchSearchQuery.java
/** * Stores <code>fieldValue</code> as a search term on the * <code>fieldName</code> field. * /*w w w. ja v a 2s . c o m*/ * @param fieldName * the field name * @param startDate * the start date * @param endDate * the end date */ protected void and(String fieldName, Date startDate, Date endDate) { // Fix the field name, just in case fieldName = StringUtils.trim(fieldName); // Make sure the data structures are set up accordingly if (dateRanges == null) dateRanges = new HashSet<DateRange>(); // Add the term DateRange dateRange = new DateRange(fieldName, startDate, endDate); dateRanges.add(dateRange); }