List of usage examples for org.apache.commons.lang3 StringUtils isNumeric
public static boolean isNumeric(final CharSequence cs)
Checks if the CharSequence contains only Unicode digits.
From source file:form.house.NewHouseForm.java
private Long stringToLong(String number) { if (!StringUtils.isNumeric(number)) return 0l; Double result = Double.valueOf(number) * 100; return result.longValue(); }
From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.deploy.ops.DeployCloudFoundryServerGroupAtomicOperation.java
@Nullable static Integer convertToMb(String field, @Nullable String size) { if (size == null) { return null; } else if (StringUtils.isNumeric(size)) { return Integer.parseInt(size); } else if (size.toLowerCase().endsWith("g")) { String value = size.substring(0, size.length() - 1); if (StringUtils.isNumeric(value)) return Integer.parseInt(value) * 1024; } else if (size.toLowerCase().endsWith("m")) { String value = size.substring(0, size.length() - 1); if (StringUtils.isNumeric(value)) return Integer.parseInt(value); }//from w w w. j a v a2 s . c o m throw new IllegalArgumentException("Invalid size for application " + field + " = '" + size + "'"); }
From source file:com.aol.one.patch.DefaultPatcher.java
private void invokeReplaceMethod(Object object, String fieldName, JsonNode valueNode) throws IllegalAccessException, InvocationTargetException, PatchException { if (object instanceof Patchable) { Patchable patchable = (Patchable) object; patchable.replaceValue(fieldName, valueNode); return;//w ww. j a v a2 s .c om } boolean isFieldNameNumeric = StringUtils.isNumeric(fieldName); if (isFieldNameNumeric && object instanceof java.util.List) { List tmpList = (List) object; // WARN: inserting JsonNode into list // NOTE: not add, but set. tmpList.set(Integer.parseInt(fieldName), valueNode); return; } if (isFieldNameNumeric && object instanceof java.util.Map) { Map tmpMap = (Map) object; // WARN: removing string key from Map, key type of Map not known. tmpMap.remove(fieldName); // WARN: adding JsonNode into Map tmpMap.put(fieldName, valueNode); return; } // first try to find replace+CapitalizedField List<String> methodNames = new ArrayList<>(); methodNames.add("replace" + StringUtils.capitalize(fieldName)); // next, set + capitalizedField methodNames.add("set" + StringUtils.capitalize(fieldName)); List<MethodData> methodDataList = generateMethodData(methodNames, valueNode); // final try, standard method List<Class<?>> argTypes = new ArrayList<>(); argTypes.add(String.class); argTypes.add(JsonNode.class); List<Object> params = new ArrayList<>(); params.add(fieldName); params.add(valueNode); MethodData standardMethodData = new MethodData(STANDARD_REPLACE_METHOD, argTypes, params); methodDataList.add(standardMethodData); invokeMethodFromMethodDataList(object, methodDataList); }
From source file:controllers.UserApp.java
private static User getUserFromSession() { String userId = session().get(SESSION_USERID); if (userId == null) { return User.anonymous; }/* w w w. ja v a 2 s. c om*/ if (!StringUtils.isNumeric(userId)) { return invalidSession(); } User user = User.find.byId(Long.valueOf(userId)); if (user == null) { return invalidSession(); } return user; }
From source file:com.glaf.core.util.RequestUtils.java
public static String getCurrentSystem(HttpServletRequest request) { String currentSystem = null;//w w w .ja v a2 s. c o m String paramValue = request.getParameter(Constants.SYSTEM_NAME); if (StringUtils.isNotEmpty(paramValue)) { return paramValue; } String ip = getIPAddress(request); ip = DigestUtils.md5Hex(ip); HttpSession session = request.getSession(false); if (session != null) { String value = (String) session.getAttribute(Constants.LOGIN_INFO); Map<String, String> cookieMap = decodeValues(ip, value); if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) { currentSystem = cookieMap.get(Constants.SYSTEM_NAME); } } if (currentSystem == null) { Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) { String value = cookie.getValue(); Map<String, String> cookieMap = decodeValues(ip, value); if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) { String time = cookieMap.get(Constants.TS); long now = Long.MAX_VALUE - System.currentTimeMillis(); if (StringUtils.isNumeric(time) && (Long.parseLong(time) - now) < COOKIE_LIVING_SECONDS * 1000) { currentSystem = cookieMap.get(Constants.SYSTEM_NAME); break; } } } } } } return currentSystem; }
From source file:com.mijecu25.sqlplus.SQLPlus.java
/** * Create an SQLPlusConnection by taking the credentials from the user. * * @throws IOException if there is an I/O error while reading input from the user. * @throws SQLException if there is an error while establishing a connection. *///ww w . j ava 2 s .c om private static void createSQLPlusConnection() throws IOException, SQLException { if (false) { System.out.println("You will now enter the credentials to connect to your database"); // Add credentials System.out.print(SQLPlus.PROMPT + "Host(default " + SQLPlusConnection.getDefaultHost() + "): "); String host = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("User entered host:" + host); // TODO validate host // if(!host.isEmpty()) { // // The Console object for the JVM could not be found. Alert the user and throw a // // NullPointerException that the caller will handle // SQLPlus.logger.fatal(Messages.FATAL + "The user wants to use a host that is not supported"); // System.out.println(Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the host that you entered"); // // SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the " // + "calling class"); // throw new IllegalArgumentException(); // } System.out.print(SQLPlus.PROMPT + "Database(default " + SQLPlusConnection.getDefaultDatabase() + "): "); String database = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("User entered database:" + database); if (database.isEmpty()) { database = SQLPlusConnection.getDefaultDatabase(); SQLPlus.logger.info("Using default database:" + database); } String port = ""; // While the port is not numeric while (!StringUtils.isNumeric(port)) { System.out.print(SQLPlus.PROMPT + "Port (default " + SQLPlusConnection.getDefaultPort() + "): "); port = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("Port entered: " + port); SQLPlus.logger.info("Port string length: " + port.length()); // If the port is empty if (port.isEmpty()) { // Assume that the user wants to use the default port. Continue to the next step break; } // If the port has more than 5 numbers or is not numberic if (port.length() > 5 || !StringUtils.isNumeric(port)) { SQLPlus.logger.warn("The user provided an invalid port number: " + port); System.out.println( Messages.WARNING + "You need to provided a valid port number " + "from 0 to 65535"); // Set the port to the empty string to ask the user again port = ""; } } SQLPlus.logger.info("User entered port:" + port); String username = ""; // While the username is empty while (username.isEmpty()) { System.out.print(SQLPlus.PROMPT + "Username: "); username = SQLPlus.console.readLine().trim(); // If the username is empty if (username.isEmpty()) { SQLPlus.logger.warn("The user did not provide a username"); System.out.println(Messages.WARNING + "You cannot have an empty username"); } } SQLPlus.logger.info("User entered username:" + username); // Reset the jline console since we are going to use the regular console to securely get the password SQLPlus.resetConsole(); // Get the console for safe password entry Console javaConsole = System.console(); // If the console is null if (javaConsole == null) { // The Console object for the JVM could not be found. Alert the user and throw a // NullPointerException that the caller will handle SQLPlus.logger.fatal("A JVM Console object to enter a password was not found"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. " + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line."); SQLPlus.logger.info( "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class"); throw new NullPointerException(); } // Read the password without echoing the result char[] password = javaConsole.readPassword("%s", SQLPlus.PROMPT + "Password:"); // If the password is null if (password == null) { // The Console object for the JVM could not be found. Alert the user and throw a // NullPointerException that the caller will handle SQLPlus.logger.fatal("The password captured by the JVM Console object returned null"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to get the password you entered from" + "your JVM's Console object. Try running " + SQLPlus.PROGRAM_NAME + " from the command line or a different" + "terminal program"); SQLPlus.logger.info( "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class"); throw new NullPointerException(); } SQLPlus.logger.info("User entered some password"); System.out.println(); // Create a connection based on the database system switch (database) { case SQLPlusMySQLConnection.MYSQL: // If the default port and host are used if (port.isEmpty() && host.isEmpty()) { SQLPlus.logger.info("Connection with username, password"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password); } // If the default port is used else if (port.isEmpty()) { SQLPlus.logger.info("Connection with username, password, and host"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host); } // All the values were provided by the user else { SQLPlus.logger.info("Connection with all credentials"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host, port); } break; default: // Database entered is not supported SQLPlus.logger.fatal(Messages.FATAL + "The database system " + database + " is not supported"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the database that you entered"); SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the " + "calling class"); throw new IllegalArgumentException(); } // Delete any traces of password in memory by filling the password array with with random characters // to minimize the lifetime of sensitive data in memory. Then call the garbage collections java.util.Arrays.fill(password, Character.MIN_VALUE); System.gc(); // Recreate the jline console SQLPlus.console = new ConsoleReader(); SQLPlus.console.setHandleUserInterrupt(true); } // TODO remove this which is for testing SQLPlus.logger.info("Connection with username, password, and host"); SQLPlusConnection sqlPlusConnection = SQLPlusMySQLConnection.getConnection("sqlplus", new char[0], SQLPlusConnection.getDefaultHost()); // TODO this does have to be in the final code SQLPlus.logger.info("Created and returning a SQLPlusConnection " + sqlPlusConnection); SQLPlus.sqlPlusConnection = sqlPlusConnection; }
From source file:com.glaf.survey.web.springmvc.SurveyController.java
@ResponseBody @RequestMapping("/saveSurvey") public byte[] saveSurvey(HttpServletRequest request) { User user = RequestUtils.getUser(request); String actorId = user.getActorId(); Map<String, Object> params = RequestUtils.getParameterMap(request); logger.debug("params:" + params); Survey survey = new Survey(); try {//from w ww . j a v a 2s . c o m Tools.populate(survey, params); survey.setTitle(request.getParameter("title")); survey.setContent(request.getParameter("content")); survey.setIcon(request.getParameter("icon")); survey.setKeywords(request.getParameter("keywords")); survey.setStatus(RequestUtils.getInt(request, "status")); survey.setShowIconFlag(RequestUtils.getInt(request, "showIconFlag")); survey.setSignFlag(RequestUtils.getInt(request, "signFlag")); survey.setMultiFlag(RequestUtils.getInt(request, "multiFlag")); survey.setLimitFlag(RequestUtils.getInt(request, "limitFlag")); survey.setLimitTimeInterval(RequestUtils.getInt(request, "limitTimeInterval")); survey.setResultFlag(RequestUtils.getInt(request, "resultFlag")); survey.setStartDate(RequestUtils.getDate(request, "startDate")); survey.setEndDate(RequestUtils.getDate(request, "endDate")); survey.setRelationIds(request.getParameter("relationIds")); survey.setCreateBy(actorId); Map<Integer, SurveyItem> dataMap = new java.util.HashMap<Integer, SurveyItem>(); String[] titleArray = request.getParameterValues("item_title"); if (titleArray != null && titleArray.length > 0) { int index = 0; for (String t : titleArray) { SurveyItem item = new SurveyItem(); item.setName(t); item.setValue(String.valueOf(index)); survey.addItem(item); dataMap.put(index, item); index++; } } String[] sortArray = request.getParameterValues("item_sort"); if (sortArray != null && sortArray.length > 0) { int index = 0; for (String sort : sortArray) { SurveyItem item = dataMap.get(index++); if (item != null && StringUtils.isNotEmpty(sort) && StringUtils.isNumeric(sort)) { item.setSort(Integer.parseInt(sort)); } } } this.surveyService.save(survey); return ResponseUtils.responseJsonResult(true); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } return ResponseUtils.responseJsonResult(false); }
From source file:com.caved_in.commons.utilities.StringUtil.java
public static boolean isNumericAt(String[] strs, int index) { return strs.length > index && StringUtils.isNumeric(strs[index]); }
From source file:de.micromata.genome.gwiki.plugin.vfolder_1_0.GWikiVFolderUtils.java
public static GWikiVFolderCachedFileInfos readCache(GWikiVFolderNode node) { GWikiVFolderCachedFileInfos ret = new GWikiVFolderCachedFileInfos(); if (node.getFileSystem().exists(VFOLDERCACHEFILE) == false) { return ret; }/* www . j av a2s .c o m*/ String content = node.getFileSystem().readTextFile(VFOLDERCACHEFILE); List<String> lines = Converter.parseStringTokens(content, "\n", false); for (String line : lines) { int idx = line.indexOf(':'); if (idx == -1) { continue; } String localName = line.substring(0, idx); String rest = line.substring(idx + 1); Map<String, String> atts = PipeValueList.decode(rest); GWikiProps props = new GWikiSettingsProps(); props.setMap(atts); // TODO set meta template GWikiElementInfo ei = new GWikiElementInfo(props, null); ret.addElement(localName, ei); } if (node.getFileSystem().exists(VFOLDERSTATUSFILE) == true) { String tc = node.getFileSystem().readTextFile(VFOLDERSTATUSFILE); Map<String, String> m = PipeValueList.decode(tc); if (StringUtils.isNumeric(m.get("fsmodcounter")) == true) { ret.setLastFsModifiedCounter(NumberUtils.createLong(m.get("fsmodcounter"))); } } return ret; }
From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java
/** * a method that returns a number of random urls * @param path SWebRank output directory * @param numOfQueries the number of queries * @param numOfpages the number of urls per query * @return a list of urls/*from ww w . ja v a 2 s.c o m*/ */ private ArrayList<String> getSuggestions(String path, int numOfQueries, int numOfpages, String[] history) { List<String> historyUrls = Arrays.asList(history); ArrayList<String> randomQueries = getQueries(path, numOfQueries); //for each query select a number of random urls //for now it only works for bing search engine ArrayList<String> suggestions = new ArrayList<>(); for (String s : randomQueries) { File level = new File(s + "\\" + "bing" + "\\"); File[] docPaths = level.listFiles(); List<String> urls = new ArrayList<>(); for (File f : docPaths) { String str = f.getAbsolutePath(); if (StringUtils.isNumeric(str.substring(str.lastIndexOf("\\") + 1))) { File webPagePath = new File(str + "\\current_url.txt"); try { String url = FileUtils.readFileToString(webPagePath); urls.add(url); } catch (IOException ex) { Logger.getLogger(ProfileAnalysis.class.getName()).log(Level.SEVERE, null, ex); } } } if (numOfpages > urls.size()) { for (String ur : urls) { if (!suggestions.contains(ur) && !historyUrls.contains(ur)) suggestions.add(ur); } continue; } int totalUrls = urls.size() - 1; Random randomPage = new Random(); int count = 0; while (count < numOfpages) { String val = urls.get(randomPage.nextInt(totalUrls)); if (!suggestions.contains(val) && !historyUrls.contains(val)) { suggestions.add(val); count++; } } } return suggestions; }