List of usage examples for org.apache.commons.lang3 StringUtils split
public static String[] split(final String str, final String separatorChars, final int max)
Splits the provided text into an array with a maximum length, separators specified.
The separator is not included in the returned String array.
From source file:com.github.rvesse.airline.parser.options.MaybePairValueOptionParser.java
protected final List<String> getValues(String list) { return AirlineUtils.arrayToList(StringUtils.split(list, new String(new char[] { this.separator }), 2)); }
From source file:io.stallion.utils.ResourceHelpers.java
public static List<String> listFilesInDirectory(String plugin, String path) { String ending = ""; String starting = ""; if (path.contains("*")) { String[] parts = StringUtils.split(path, "*", 2); String base = parts[0];/*from w w w.j a v a 2 s .c o m*/ if (!base.endsWith("/")) { path = new File(base).getParent(); starting = FilenameUtils.getName(base); } else { path = base; } ending = parts[1]; } Log.info("listFilesInDirectory Parsed Path {0} starting:{1} ending:{2}", path, starting, ending); URL url = PluginRegistry.instance().getJavaPluginByName().get(plugin).getClass().getResource(path); Log.info("URL: {0}", url); List<String> filenames = new ArrayList<>(); URL dirURL = getClassForPlugin(plugin).getResource(path); Log.info("Dir URL is {0}", dirURL); // Handle file based resource folder if (dirURL != null && dirURL.getProtocol().equals("file")) { String fullPath = dirURL.toString().substring(5); File dir = new File(fullPath); // In devMode, use the source resource folder, rather than the compiled version if (Settings.instance().getDevMode()) { String devPath = fullPath.replace("/target/classes/", "/src/main/resources/"); File devFolder = new File(devPath); if (devFolder.exists()) { dir = devFolder; } } Log.info("List files from folder {0}", dir.getAbsolutePath()); List<String> files = list(); for (String name : dir.list()) { if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } filenames.add(path + name); } return filenames; } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = null; try { jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); } catch (IOException e) { throw new RuntimeException(e); } if (path.startsWith("/")) { path = path.substring(1); } Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); Log.finer("Jar file entry: {0}", name); if (name.startsWith(path)) { //filter according to the path String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } if (!empty(ending) && !name.endsWith(ending)) { continue; } if (!empty(starting) && !name.endsWith("starting")) { continue; } // Skip special files, hidden files if (name.startsWith(".") || name.startsWith("~") || name.startsWith("#") || name.contains("_flymake.")) { continue; } result.add(entry); } } return new ArrayList<>(result); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); /* try { URL url1 = getClassForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url1); if (url1 != null) { Log.info("From class folder contents {0}", IOUtils.toString(url1)); Log.info("From class folder contents as stream {0}", IOUtils.toString(getClassForPlugin(plugin).getResourceAsStream(path))); } URL url2 = getClassLoaderForPlugin(plugin).getResource(path); Log.info("URL1 {0}", url2); if (url2 != null) { Log.info("From classLoader folder contents {0}", IOUtils.toString(url2)); Log.info("From classLoader folder contents as stream {0}", IOUtils.toString(getClassLoaderForPlugin(plugin).getResourceAsStream(path))); } } catch (IOException e) { Log.exception(e, "error loading path " + path); } // Handle jar based resource folder try( InputStream in = getResourceAsStream(plugin, path); BufferedReader br = new BufferedReader( new InputStreamReader( in ) ) ) { String resource; while( (resource = br.readLine()) != null ) { Log.finer("checking resource for inclusion in directory scan: {0}", resource); if (!empty(ending) && !resource.endsWith(ending)) { continue; } if (!empty(starting) && !resource.endsWith("starting")) { continue; } // Skip special files, hidden files if (resource.startsWith(".") || resource.startsWith("~") || resource.startsWith("#") || resource.contains("_flymake.")) { continue; } Log.finer("added resource during directory scan: {0}", resource); filenames.add(path + resource); } } catch (IOException e) { throw new RuntimeException(e); } return filenames; */ }
From source file:io.stallion.boot.Booter.java
public void boot(String[] args, StallionJavaPlugin[] plugins) throws Exception { // Load the plugin jars, to get additional actions String targetPath = new File(".").getAbsolutePath(); for (String arg : args) { if (arg.startsWith("-targetPath=")) { targetPath = StringUtils.split(arg, "=", 2)[1]; }//from ww w. j a va 2s . c o m } if (!new File(targetPath).isDirectory() || empty(targetPath) || targetPath.equals("/") || targetPath.equals("/.")) { throw new CommandException( "You ran stallion with the target path " + targetPath + " but that is not a valid folder."); } PluginRegistry.loadWithJavaPlugins(targetPath, plugins); List<StallionRunAction> actions = new ArrayList(builtinActions); actions.addAll(PluginRegistry.instance().getAllPluginDefinedStallionRunActions()); // Load the action executor StallionRunAction action = null; for (StallionRunAction anAction : actions) { if (empty(anAction.getActionName())) { throw new UsageException( "The action class " + anAction.getClass().getName() + " has an empty action name"); } if (args.length > 0 && anAction.getActionName().equals(args[0])) { action = anAction; } } if (action == null) { String msg = "\n\nError! You must pass in a valid action as the first command line argument. For example:\n\n" + ">stallion serve -port=8090 -targetPath=~/my-stallion-site\n"; if (args.length > 0) { msg += "\n\nYou passed in '" + args[0] + "', which is not a valid action.\n"; } msg += "\nAllowed actions are:\n\n"; for (StallionRunAction anAction : actions) { //Log.warn("Action: {0} {1} {2}", action, action.getActionName(), action.getHelp()); msg += anAction.getActionName() + " - " + anAction.getHelp() + "\n"; } msg += "\n\nYou can get help about an action by running: >stallion <action> help\n\n"; System.err.println(msg); System.exit(1); } // Load the command line options CommandOptionsBase options = action.newCommandOptions(); CmdLineParser parser = new CmdLineParser(options); if (args.length > 1 && "help".equals(args[1])) { System.out.println(action.getActionName() + " - " + action.getHelp() + "\n\n"); System.out.println("\n\nOptions for command " + action.getActionName() + "\n\n"); parser.printUsage(System.out); System.exit(0); } try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("\n\nError!\n\n" + e.getMessage()); System.err.println("\n\nAllowed options: \n"); parser.printUsage(System.err); System.err.println("\n"); System.exit(1); } options.setExtraPlugins(Arrays.asList(plugins)); if (!empty(options.getLogLevel())) { try { Log.setLogLevel(Level.parse(options.getLogLevel())); } catch (IllegalArgumentException e) { System.err.println("\nError! Invalid log level: " + options.getLogLevel() + "\n\n" + CommandOptionsBase.ALLOWED_LEVELS); System.exit(1); } } if (empty(options.getTargetPath())) { options.setTargetPath(new File(".").getAbsolutePath()); } // Shutdown hooks Thread shutDownHookThread = new Thread() { public void run() { try { Unirest.shutdown(); } catch (IOException e) { e.printStackTrace(); } } }; shutDownHookThread.setName("stallion-shutdown-hook"); Runtime.getRuntime().addShutdownHook(shutDownHookThread); // Execute the action action.loadApp(options); for (StallionJavaPlugin plugin : PluginRegistry.instance().getJavaPluginByName().values()) { plugin.preExecuteAction(action.getActionName(), options); } action.execute(options); if (!AppContextLoader.isNull()) { AppContextLoader.shutdown(); } }
From source file:io.stallion.users.OAuthApprovalController.java
public OAuthUserLogin tokenToUser(String accessToken, boolean ignoreExpires) { if (!accessToken.contains("-")) { throw new ClientException("Invalid access token format"); }/*from w ww. j av a 2s. c om*/ String[] parts = StringUtils.split(accessToken, "-", 2); if (!StringUtils.isNumeric(parts[0])) { throw new ClientException("Invalid access token format"); } long userId = Long.parseLong(parts[0]); IUser user = UserController.instance().forId(userId); if (user == null) { throw new ClientException("User not found for access token"); } String decrypted = Encrypter.decryptString(user.getEncryptionSecret(), parts[1]); OAuthAccesTokenData data = JSON.parse(decrypted, OAuthAccesTokenData.class); if (data.getUserId() != userId) { throw new ClientException("Invalid access token"); } if (!ignoreExpires && data.getExpires() < mils()) { throw new ClientException("Access token has expired"); } if (Settings.instance().getoAuth().getAlwaysCheckAccessTokenValid()) { OAuthApproval approval = OAuthApprovalController.instance().forId(data.getApprovalId()); if (approval == null || approval.isRevoked() || (!ignoreExpires && approval.getAccessTokenExpiresAt() < mils())) { throw new ClientException("Invalid approval"); } } OAuthUserLogin login = new OAuthUserLogin().setScoped(data.isScoped()).setUser(user) .setApprovalId(data.getApprovalId()).setScopes(data.getScopes()); return login; }
From source file:com.act.lcms.db.io.parser.PlateCompositionParser.java
public void processFile(File inFile) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(inFile))) { String line;/* w w w .ja v a 2s . c o m*/ boolean readingCompositionTable = false; String compositionTableName = null; List<String> compositionTableColumns = null; int rowIndexInCompositionTable = 0; while ((line = br.readLine()) != null) { if (line.startsWith(">>")) { // TODO: add max table width based on plate type. String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, "\t"); readingCompositionTable = true; if (fields.length < 2) { throw new RuntimeException( String.format("Found malformed composition table header: %s", line)); } compositionTableColumns = Arrays.asList(fields); compositionTableName = fields[0].replaceFirst("^>>", ""); rowIndexInCompositionTable = 0; } else if (line.startsWith(">")) { String[] fields = StringUtils.split(line, "\t", 2); // Found a plate attribute. if (fields.length != 2) { System.err.format("Too few fields: %s\n", StringUtils.join(fields, ", ")); System.err.flush(); throw new RuntimeException(String.format("Found malformed plate attribute line: %s", line)); } plateProperties.put(fields[0].replaceFirst("^>", ""), fields[1]); } else if (line.trim().length() == 0) { // Assume a blank line terminates a composition table. readingCompositionTable = false; compositionTableName = null; compositionTableColumns = null; rowIndexInCompositionTable = 0; } else if (readingCompositionTable) { // This split method with a very long name preserves blanks and doesn't merge consecutive delimiters. String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, "\t"); // The split ^^ preserves blanks, so we can exactly compare the lengths. if (fields.length != compositionTableColumns.size()) { throw new RuntimeException(String.format( "Found %d fields where %d were expected in composition table line:\n '%s'\n", fields.length, compositionTableColumns.size(), line)); } for (int i = 1; i < fields.length; i++) { String val = compositionTableColumns.get(i); // No need to store empty values; if (val == null || val.isEmpty()) { continue; } Pair<String, String> coordinates = Pair.of(fields[0], val); // Note: assumes every row appears in each composition table (even empty ones). coordinatesToIndices.put(coordinates, Pair.of(rowIndexInCompositionTable, i - 1)); Map<Pair<String, String>, String> thisTable = compositionTables.get(compositionTableName); if (thisTable == null) { thisTable = new HashMap<>(); compositionTables.put(compositionTableName, thisTable); } // TODO: add paranoid check for repeated keys? Shouldn't be possible unless tables are repeated. thisTable.put(coordinates, fields[i]); } rowIndexInCompositionTable++; } } } }
From source file:jp.mathes.databaseWiki.wiki.NewPlugin.java
@SuppressWarnings("unchecked") @Override/*ww w .ja v a 2s .c o m*/ public void process(final Document doc, final String fieldname, final String user, final String password, final Backend backend) throws PluginException { Field<String> field = doc.getAllFields().get(fieldname); String renderedText = field.getValue(); Matcher matcher = NewPlugin.REGEX.matcher(renderedText); while (matcher.find()) { String target = ""; String param = ""; if (StringUtils.isEmpty(matcher.group(1))) { target = String.format("../../%s/_new", matcher.group(2)); param = matcher.group(3); } else { target = String.format("../../../%s/%s/_new", matcher.group(1), matcher.group(2)); param = matcher.group(3); } try { Configuration conf = new Configuration(); conf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX); Template template = new Template("name", new StringReader(param), new Configuration()); HashMap<String, Object> data = new HashMap<String, Object>(); data.put("doc", doc); data.put("fields", doc.getAllFields()); StringWriter sw = new StringWriter(); template.process(data, sw); param = sw.getBuffer().toString(); } catch (IOException e) { throw new PluginException(e); } catch (TemplateException e) { throw new PluginException(e); } // match a comma except if it is preceeded by a backslash String[] split = param.split("(?<!\\\\),"); StringBuilder sbForm = new StringBuilder( "<form method=\"post\" class=\"new\" action=\"%s\"><input type=\"text\" name=\"name\" />"); for (String oneParameter : split) { String[] oneParameterSplit = StringUtils.split(oneParameter, "(?<!\\\\)=", 2); if (oneParameterSplit.length == 2) { sbForm.append(String.format("<input type=\"hidden\" name=\"%s\" value=\"%s\"/>", oneParameterSplit[0], oneParameterSplit[1])); } } sbForm.append("<input type=\"submit\" value=\"create\"/></form>"); String formString = String.format(sbForm.toString(), target); renderedText = renderedText.replace(matcher.group(0), formString); field.setValue(renderedText); } }
From source file:com.sludev.commons.vfs2.provider.s3.SS3FileObject.java
/** * Convenience method that returns the container ( i.e. "bucket ) and path from the current URL. * //from w w w . jav a 2 s .com * @return A tuple containing the bucket name and the path. */ private Pair<String, String> getContainerAndPath() { Pair<String, String> res = null; try { URLFileName currName = (URLFileName) getName(); String currPathStr = currName.getPath(); currPathStr = StringUtils.stripStart(currPathStr, "/"); if (StringUtils.isBlank(currPathStr)) { log.warn(String.format("getContainerAndPath() : Path '%s' does not appear to be valid", currPathStr)); return null; } // Deal with the special case of the container root. if (StringUtils.contains(currPathStr, "/") == false) { // Container and root return new ImmutablePair<>(currPathStr, "/"); } String[] resArray = StringUtils.split(currPathStr, "/", 2); res = new ImmutablePair<>(resArray[0], resArray[1]); } catch (Exception ex) { log.error(String.format("getContainerAndPath() : Path does not appear to be valid"), ex); } return res; }
From source file:com.sludev.commons.vfs2.provider.azure.AzFileObject.java
/** * Convenience method that returns the container and path from the current URL. * //from w ww . ja va2s.c o m * @return A tuple containing the container name and the path. */ protected Pair<String, String> getContainerAndPath() { Pair<String, String> res = null; try { URLFileName currName = (URLFileName) getName(); String currNameStr = currName.getPath(); currNameStr = StringUtils.stripStart(currNameStr, "/"); if (StringUtils.isBlank(currNameStr)) { log.warn(String.format("getContainerAndPath() : Path '%s' does not appear to be valid", currNameStr)); return null; } // Deal with the special case of the container root. if (StringUtils.contains(currNameStr, "/") == false) { // Container and root return new ImmutablePair<>(currNameStr, "/"); } String[] resArray = StringUtils.split(currNameStr, "/", 2); res = new ImmutablePair<>(resArray[0], resArray[1]); } catch (Exception ex) { log.error(String.format("getContainerAndPath() : Path does not appear to be valid"), ex); } return res; }
From source file:com.threewks.thundr.http.URLEncoder.java
/** * Decodes the given query parameter string into key value pairs. * /*www.ja v a2s .c o m*/ * If the given string begins with '?', it will be stripped off. Pairs are decoded before being returned. * * @param query * @return */ public static Map<String, List<String>> decodeQueryString(String query) { query = StringUtils.trimToEmpty(query); query = StringUtils.removeStart(query, "?"); Map<String, List<String>> results = new LinkedHashMap<>(); if (StringUtils.isNotBlank(query)) { for (String pair : query.split("&")) { String[] parts = StringUtils.split(pair, "=", 2); String key = unescape(parts[0]); String value = parts.length > 1 ? unescape(parts[1]) : null; List<String> existing = results.get(key); if (existing == null) { existing = new ArrayList<>(); results.put(key, existing); } existing.add(value); } } return results; }
From source file:es.molabs.properties.NodeProperties.java
protected void processProperties() { // Clears the cache clearCache();/* ww w . j a va 2 s. c om*/ // Process the loaded properties Set<String> keySet = properties.stringPropertyNames(); String[] splitedKey = null; String key = null; TreeNode treeNode = root; Node currentNode = null; // For each key Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { key = iterator.next(); treeNode = root; currentNode = null; // Splits the key by nodes splitedKey = StringUtils.split(key, SEPARATOR_CHARACTER, this.nodes + 1); // For each node of the splited key for (int i = 0; i < splitedKey.length; i++) { currentNode = treeNode.getNode(splitedKey[i]); // If it does not exists if (currentNode == null) { // If its the last node then is a key/value pair if (i + 1 == splitedKey.length) { currentNode = new ValueNode(splitedKey[i], properties.getProperty(key)); } // Else is a tree node else { currentNode = new TreeNode(splitedKey[i]); } // Adds it to the level treeNode.addNode(currentNode); } if (currentNode instanceof TreeNode) { treeNode = (TreeNode) currentNode; } } } }