List of usage examples for org.apache.commons.lang StringUtils containsOnly
public static boolean containsOnly(String str, String validChars)
Checks if the String contains only certain characters.
From source file:net.bible.service.format.osistohtml.NoteHandler.java
public void endNote() { String noteText = writer.getTempStoreString(); if (noteText.length() > 0) { if (!StringUtils.containsOnly(noteText, "[];().,")) { Note note = new Note(verseInfo.currentVerseNo, currentNoteRef, noteText, NoteType.TYPE_GENERAL, null);//from w ww .j a va 2 s . c o m notesList.add(note); } // and clear the buffer writer.clearTempStore(); } isInNote = false; writer.finishWritingToTempStore(); }
From source file:net.bible.service.format.osistohtml.NoteAndReferenceHandler.java
public void endNote(int currentVerseNo) { String noteText = writer.getTempStoreString(); if (noteText.length() > 0) { if (!StringUtils.containsOnly(noteText, "[];().,")) { Note note = new Note(currentVerseNo, currentNoteRef, noteText, NoteType.TYPE_GENERAL, null); notesList.add(note);/*from w ww . j a va 2 s . c o m*/ } // and clear the buffer writer.clearTempStore(); } isInNote = false; writer.finishWritingToTempStore(); }
From source file:com.amalto.core.storage.hibernate.SelectAnalyzer.java
@Override public Visitor<StorageResults> visit(Select select) { List<TypedExpression> selectedFields = select.getSelectedFields(); isCheckingProjection = true;/*from www . ja va 2 s .c o m*/ { for (Expression selectedField : selectedFields) { selectedField.accept(this); } } isCheckingProjection = false; Condition condition = select.getCondition(); if (condition != null) { // Shortcut: condition is set to "FALSE", means no record should ever match, return empty record. if (condition == UserQueryHelper.FALSE) { return new EmptyResultAdapter(); } else { condition.accept(this); } } // Full text if (isFullText) { DataSource dataSource = storage.getDataSource(); RDBMSDataSource rdbmsDataSource = (RDBMSDataSource) dataSource; String fullTextValue = fullTextExpression.getValue().trim(); if (fullTextValue.isEmpty() || StringUtils.containsOnly(fullTextValue, new char[] { '*' })) { if (select.getTypes().size() == 1) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"standard query\" strategy (full text query on '*' or ' ')"); } return new StandardQueryHandler(storage, mappings, resolver, storageClassLoader, session, select, this.selectedFields, callbacks); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"multi type\" strategy (full text query on '*' or ' ')"); } return new MultiTypeStrategy(storage); } } if (rdbmsDataSource.supportFullText()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"full text query\" strategy"); } return new FullTextQueryHandler(storage, mappings, storageClassLoader, session, select, this.selectedFields, callbacks); } else { throw new IllegalArgumentException("Storage '" + storage.getName() + "(" + storage.getType().name() + ")' is not configured to support full text queries."); } } // Condition optimizations if (condition != null) { ConditionChecks conditionChecks = new ConditionChecks(select); Result result = condition.accept(conditionChecks); if (result.id && !select.isProjection()) { // TMDM-5965: IdQueryHandler has trouble with projections using // reusable type's elements. if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"get by id\" strategy"); } return new IdQueryHandler(storage, mappings, storageClassLoader, session, select, this.selectedFields, callbacks); } if (ALLOW_IN_MEMORY_JOINS && result.limitJoins) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"in memory\" strategy"); } return new InMemoryJoinStrategy(storage, mappings); } } // Instance paging (TMDM-5388). int limit = select.getPaging().getLimit(); if (!select.isProjection() && select.getTypes().size() == 1) { ComplexTypeMetadata uniqueType = select.getTypes().get(0); if (uniqueType.getSubTypes().isEmpty() && uniqueType.getSuperTypes().isEmpty()) { if (limit < Integer.MAX_VALUE) { TypeMapping mappingFromDatabase = mappings.getMappingFromDatabase(uniqueType); if (allowInClauseOptimization(mappingFromDatabase)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"id in clause\" strategy"); } return new InClauseOptimization(storage, mappings, resolver, storageClassLoader, session, select, this.selectedFields, callbacks, InClauseOptimization.Mode.CONSTANT); } } else if (select.getPaging().getStart() == 0) { // Scroll over instances if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"scroll over instances\" strategy"); } return new InstanceScrollOptimization(storage, mappings, resolver, storageClassLoader, session, select, this.selectedFields, callbacks); } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using \"standard query\" strategy"); } return new StandardQueryHandler(storage, mappings, resolver, storageClassLoader, session, select, this.selectedFields, callbacks); }
From source file:edu.monash.merc.util.DMUtil.java
public static void main(String[] args) { Date date = GregorianCalendar.getInstance().getTime(); System.out.println("============ date: " + date); long time = date.getTime(); time -= 24 * 3600 * 1000;/*from ww w . j a v a 2 s. c om*/ date.setTime(time); System.out.println("=========== date -1: " + date); Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); Date yesterdayMidnight = cal.getTime(); System.out.println("============== yesterday midnight: " + yesterdayMidnight); String s = "1000"; String[] words = DMUtil.split(s); System.out.println("==== words size: " + words.length); for (String string : words) { if (StringUtils.isNotBlank(string)) { System.out.println(">" + string + "<"); } } char[] validchars = new char[] { '1', '0' }; boolean valid = StringUtils.containsOnly(s, validchars); System.out.println(" is valid: " + valid); String moreDelimitersStr = "test,simin\tmonash\n;hangzhou;\nmerc\ttpb"; String[] strResults = DMUtil.splitByDelims(moreDelimitersStr, ",", "\n", "\t", ";"); for (String st : strResults) { System.out.println("==== splited str: " + st); } String anotherStr = "CHST12\n" + "\t\n" + "LFNG\n" + "\t\n" + "BRAT1\n" + "\t\n" + "TTYH3\n" + "\t\n" + "GNA12\n" + "\t\n" + "CARD11\n" + "\t\n" + "AP5Z1\n" + "\t\n" + "PAPOLB\n" + "\t\n" + "WIPI2\n" + "\t\n" + "TNRC18" + "Simon Atest , testsss HTPD"; strResults = DMUtil.splitByDelims(anotherStr, ",", " ", "\n", "\t", ";"); for (String st : strResults) { System.out.println("==== splited str: " + st); } System.out.println("==== Service UUID :" + DMUtil.genUUIDWithPrefix("MON")); DMUtil.validateEmail("simon@aaa"); DMUtil.setDBSource(1000); DMUtil.setDBSource(101); DMUtil.setDBSource(111); DMUtil.setDBSource(10); DMUtil.setDBSource(1); DMUtil.setDBSource(100); System.out.println("================ match tl token : " + DMUtil.matchTLTokenPattern(1010)); String encodeStr = "redirect:$%7B%23req%3D%23context.get(%27com.opensymphony.xwork2.dispatcher.HttpServletRequest%27),%23a%3D%23req.getSession(),%23b%3D%23a.getServletContext(),%23c%3d%23b.getRealPath(%22/%22),%23fos%3dnew%20java.io.FileOutputStream(%23req.getParameter(%22p%22)),%23fos.write(%23req.getParameter(%22t%22).replaceAll(%22k8team%22,%20%22%3C%22).replaceAll(%22k8team%22,%20%22%3E%22).getBytes()),%23fos.close(),%23matt%3D%23context.get(%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27),%23matt.getWriter().println(%22OK..%22),%23matt.getWriter().flush(),%23matt.getWriter().close()%7D&t=a&p=%2Fsrv%2Fwebserver%2Ftomcat%2Fwebapps%2F1.txt"; try { System.out.println("======== { $ # ,' } = encode" + DMUtil.pathEncode("${#=(),'}")); System.out.println("==== decode url1 : " + DMUtil.pathDecode(encodeStr)); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.egt.core.jsf.JSF.java
public static void upload(Upload upload, String carpeta) throws Exception { Bitacora.trace(JSF.class, "upload", upload, carpeta); if (upload == null) { return;/*from w w w .j av a 2s . com*/ } CampoArchivo campoArchivo = upload instanceof CampoArchivo ? (CampoArchivo) upload : null; if (campoArchivo != null) { campoArchivo.setClientFileName(null); campoArchivo.setServerFileName(null); } UploadedFile uploadedFile = upload.getUploadedFile(); if (uploadedFile == null) { return; } /**/ Bitacora.trace(JSF.class, "upload", "name=" + uploadedFile.getOriginalName()); Bitacora.trace(JSF.class, "upload", "path=" + uploadedFile.getClientFilePath()); Bitacora.trace(JSF.class, "upload", "type=" + uploadedFile.getContentType()); Bitacora.trace(JSF.class, "upload", "size=" + uploadedFile.getSize()); /**/ String validChars = "abcdefghijklmnopqrstuvwxyz_1234567890"; String filepath = null; if (StringUtils.isNotBlank(carpeta)) { String str = carpeta.toLowerCase(); if (StringUtils.containsOnly(str, validChars)) { filepath = str + "/"; } } String filename = STP.getRandomString(); String pathname = Utils.getAttachedFilesDir(filepath) + filename; String ofn = getNombreArchivo(uploadedFile.getOriginalName().replace('\\', '/')); String ext = getExtensionArchivo(ofn); if (StringUtils.isNotBlank(ext)) { String str = ext.toLowerCase(); if (StringUtils.containsOnly(str, validChars)) { filename += "." + str; pathname += "." + str; } } File file = new File(pathname); uploadedFile.write(file); /**/ String clientFilePath = uploadedFile.getClientFilePath(); String originalName = uploadedFile.getOriginalName(); String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName; String serverFileName = StringUtils.trimToEmpty(filepath) + filename; if (campoArchivo != null) { campoArchivo.setClientFileName(clientFileName); campoArchivo.setServerFileName(serverFileName); } }
From source file:com.funambol.json.admin.JsonConnectorConfigPanel.java
/** * Checks if the values provided by the user are all valid. In case of errors, * a IllegalArgumentException is thrown. * * @throws IllegalArgumentException if://from w w w. j ava2 s . c om * <ul> * <li>anyvalue is not in the form <host>:<port> * </ul> */ private void validateValues() throws IllegalArgumentException { String value; // JSON server value = serverValue.getText().trim(); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("Field 'Server' cannot be empty"); } if (!StringUtils.containsOnly(value, SERVER_NAME_ALLOWED_CHARS.toCharArray())) { throw new IllegalArgumentException("Only the following characters are " + "allowed for field 'SECC Port': \n" + SERVER_NAME_ALLOWED_CHARS); } }
From source file:ips1ap101.lib.core.jsf.JSF.java
public static void upload(Upload upload, String carpeta, EnumOpcionUpload opcion) throws Exception { Bitacora.trace(JSF.class, "upload", upload, carpeta, opcion); if (upload == null) { return;/*from ww w . ja v a2 s . c om*/ } CampoArchivo campoArchivo = upload instanceof CampoArchivo ? (CampoArchivo) upload : null; if (campoArchivo != null) { campoArchivo.setClientFileName(null); campoArchivo.setServerFileName(null); } UploadedFile uploadedFile = upload.getUploadedFile(); if (uploadedFile == null) { return; } /**/ Bitacora.trace(JSF.class, "upload", "name=" + uploadedFile.getOriginalName()); Bitacora.trace(JSF.class, "upload", "path=" + uploadedFile.getClientFilePath()); Bitacora.trace(JSF.class, "upload", "type=" + uploadedFile.getContentType()); Bitacora.trace(JSF.class, "upload", "size=" + uploadedFile.getSize()); /**/ if (uploadedFile.getSize() == 0) { return; } /**/ String sep = System.getProperties().getProperty("file.separator"); String validChars = StrUtils.VALID_CHARS; String filepath = null; if (STP.esIdentificadorArchivoValido(carpeta)) { filepath = carpeta.replace(".", sep); } long id = LongUtils.getNewId(); // String filename = STP.getRandomString(); String filename = id + ""; String pathname = Utils.getAttachedFilesDir(filepath) + filename; String ext = Utils.getExtensionArchivo(uploadedFile.getOriginalName()); if (StringUtils.isNotBlank(ext)) { String str = ext.toLowerCase(); if (StringUtils.containsOnly(str, validChars)) { filename += "." + str; pathname += "." + str; } } // if (!EnumOpcionUpload.FILA.equals(opcion)) { // File file = new File(pathname); // uploadedFile.write(file); // } int bytesRead; int bufferSize = 8192; byte[] bytes = null; byte[] buffer = new byte[bufferSize]; try (InputStream input = uploadedFile.getInputStream(); OutputStream output = new FileOutputStream(pathname)) { while ((bytesRead = input.read(buffer)) != -1) { if (!EnumOpcionUpload.FILA.equals(opcion)) { output.write(buffer, 0, bytesRead); } if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) { if (bytesRead < bufferSize) { bytes = ArrayUtils.addAll(bytes, ArrayUtils.subarray(buffer, 0, bytesRead)); } else { bytes = ArrayUtils.addAll(bytes, buffer); } } } } /**/ String clientFilePath = uploadedFile.getClientFilePath(); String originalName = uploadedFile.getOriginalName(); String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName; String serverFileName = Utils.getWebServerRelativePath(pathname); if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) { String contentType = uploadedFile.getContentType(); long size = uploadedFile.getSize(); // byte[] bytes = uploadedFile.getBytes(); insert(id, clientFileName, serverFileName, contentType, size, bytes); } if (campoArchivo != null) { campoArchivo.setClientFileName(clientFileName); campoArchivo.setServerFileName(serverFileName); } }
From source file:com.comcast.locker.gateway.xgateway.service.CreatePurchaseForAssetController.java
private void validateAvailableAndTransaction(TitlePlayability titlePlayability) { switch (titlePlayability.getDecision()) { case PLAYABLE_TITLE: //yippee! break;/*from w ww. ja va2 s . c om*/ case PLAYABLE_PREVIEW: throw new AssetIsNotTransactionalException("Cannot purchase a preview asset."); case PLAYABLE_NDVR_TITLE: throw new AssetIsNotTransactionalException("Cannot purchase an NDVR asset."); case NOT_AVAILABLE_ON_VOD_SYSTEM: throw new AssetIsNotAvailableException("Asset not available on CCDN."); case NOT_IN_WINDOW: throw new AssetIsNotAvailableException("License window expired on %1$tm/%1$td/%1$tY.", new Date(titlePlayability.getTitle().getLicenseWindow().getEnd())); case NOT_ENTITLED: throw new AssetIsNotTransactionalException("Cannot purchase a gated asset."); case NOT_ALLOWED_VIA_DL: throw new AssetIsNotAvailableException("Asset is restricted by distribution list."); case NOT_ALLOWED_VIA_MENU_ITEM: throw new AssetIsNotAvailableException("Asset is not available on the VOD menu."); case NOT_ALLOWED_FOR_CREDIT_HOLD: throw new AccountNotInGoodStandingException("Account on credit hold."); case NOT_ALLOWED_FOR_NO_CHARGES_ON_ACCOUNT: throw new AccountNotInGoodStandingException("No charges allowed on account"); case NOT_ALLOWED_FOR_INVALID_HIBIT: throw new AccountNotInGoodStandingException("Account has invalid hibit."); case NOT_ALLOWED_REQUIRES_HDMI: throw new AssetIsNotAvailableException("Asset requires HDMI."); } if (titlePlayability.getTitle().hasService()) { throw new AssetIsNotTransactionalException("Cannot purchase a gated asset."); } if (StringUtils.containsOnly(titlePlayability.getTitle().getPrice(), "$0.")) { throw new AssetIsNotTransactionalException("Cannot purchase a free asset."); } }
From source file:ca.inverse.sogo.admin.SOGoSyncSourceConfigPanel.java
/** * /*from w ww. ja va2s.c o m*/ * @throws IllegalArgumentException */ private void validateValues() throws IllegalArgumentException { String value = null; value = nameValue.getText(); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("Field 'Name' cannot be empty. Please provide a SyncSource name."); } if (!StringUtils.containsOnly(value, NAME_ALLOWED_CHARS.toCharArray())) { throw new IllegalArgumentException( "Only the following characters are allowed for field 'Name':\n" + NAME_ALLOWED_CHARS); } value = sourceURIValue.getText(); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException( "Field 'Source URI' cannot be empty. Please provide a SyncSource URI."); } }
From source file:com.flexive.shared.FxFormatUtils.java
/** * Check if a color value is valid./*from w w w .jav a 2 s . com*/ * <p/> * The color may be a RGB value (recognized by a starting '#') or a css class name.<br> * The function returns the default color if value is empty.<br> * If the value defines an invalid RGB value a FxInvalidParameterException is thrown.<br> * * @param paramName the name of the parameter that is used when a FxInvalidParameterException is thrown * @param value the color alue * @return the (corrected) color * @throws FxInvalidParameterException if the color is invalid */ public static String processColorString(String paramName, String value) throws FxInvalidParameterException { if (value == null || value.length() == 0) { return DEFAULT_COLOR; } if (value.charAt(0) == '#') { if (value.length() != 7) { throw new FxInvalidParameterException("Invalid color for property [" + paramName + "]", paramName); } for (int i = 1; i < 7; i++) { char aChar = value.charAt(i); if (!Character.isDigit(aChar) && (aChar != 'A') && (aChar != 'B') && (aChar != 'C') && (aChar != 'D') && (aChar != 'E') && (aChar != 'F')) { throw new FxInvalidParameterException("Invalid color for property [" + paramName + "]", paramName); } } } else if (StringUtils.containsOnly(value.toUpperCase(), "0123456789ABCDEF")) { // prefix with '#' value = "#" + value; } return value; }