List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.pentaho.reporting.libraries.base.util.IOUtils.java
/** * Parses the given name and returns the name elements as List of Strings. * * @param name the name, that should be parsed. * @return the parsed name.// w w w . j a v a2s.co m */ private List<String> parseName(final String name) { final ArrayList<String> list = new ArrayList<String>(); final StringTokenizer strTok = new StringTokenizer(name, "/"); while (strTok.hasMoreElements()) { final String s = (String) strTok.nextElement(); if (s.length() != 0) { list.add(s); } } return list; }
From source file:org.wings.plaf.css.Utils.java
/** * Takes a string, tokenizes it and appends the wordSuffix on each word. * * @param words A list of words, may be <code>null</code>. * @param wordSuffix A suffix string to append to each word * @return modified string (<code>i.e. "slayout myclass","_box"</code> gets <code>"slayout_box myclass_box"</code>). *//*from w ww. j a v a 2 s . c o m*/ public static String appendSuffixesToWords(String words, String wordSuffix) { if (words == null || words.length() == 0 || wordSuffix == null || wordSuffix.length() == 0) { return words; } // trivial case if (words.indexOf(' ') < 0) { return words + wordSuffix; } // more than one word StringTokenizer tokenizer = new StringTokenizer(words, " "); StringBuilder returnValue = new StringBuilder(); while (tokenizer.hasMoreElements()) { returnValue.append(tokenizer.nextToken()).append(wordSuffix); if (tokenizer.hasMoreTokens()) { returnValue.append(' '); } } return returnValue.toString(); }
From source file:org.squale.welcom.taglib.button.ButtonTag.java
/** * retourne vrai si par defaut on a les acces read/write * // w w w . j a va 2 s .c o m * @param buttonName le nom du bouton * @return vrai si on force read/write */ public boolean checkIfInDefaultForceReadWrite(final String buttonName) { final String bouttonForceReadWrite = WelcomConfigurator .getMessageWithCfgChartePrefix(".bouton.default.forceReadWrite"); final StringTokenizer st = new java.util.StringTokenizer(bouttonForceReadWrite, ";", false); while (st.hasMoreElements()) { final String elements = (String) st.nextElement(); if (Util.isEquals(elements.toLowerCase(), buttonName.toLowerCase())) { return true; } } return false; }
From source file:org.squale.welcom.taglib.button.ButtonTag.java
/** * retourne vrai si par defaut on cause la validation * /* w w w .jav a 2 s . co m*/ * @param buttonName le nom du bouton * @return vrai si validation */ public boolean checkIfInDefaultCausesValidation(final String buttonName) { final String bouttonCausesValidation = WelcomConfigurator .getMessageWithCfgChartePrefix(".bouton.default.causesValidation"); final StringTokenizer st = new java.util.StringTokenizer(bouttonCausesValidation, ";", false); while (st.hasMoreElements()) { final String elements = (String) st.nextElement(); if (Util.isEquals(elements.toLowerCase(), buttonName.toLowerCase())) { return true; } } return false; }
From source file:it.unibo.alchemist.language.EnvironmentBuilder.java
private Position buildPosition(final Node son, final Map<String, Object> env) throws InstantiationException, IllegalAccessException, InvocationTargetException { if (positionClass == null) { L.error("position class not yet defined."); } else {/*ww w .j a va 2s . com*/ final NamedNodeMap attributes = son.getAttributes(); final Node posNode = attributes.getNamedItem("position"); if (posNode == null) { L.warn("a node has no position!"); } else { final String args = posNode.getNodeValue(); final StringTokenizer tk = new StringTokenizer(args, " ,;"); final ArrayList<String> arguments = new ArrayList<String>(); while (tk.hasMoreElements()) { arguments.add(tk.nextToken()); } arguments.trimToSize(); final List<Constructor<Position>> list = unsafeExtractConstructors(positionClass); return tryToBuild(list, arguments, env, random); } } return null; }
From source file:com.ibm.dbwkl.request.internal.LoggingHandler.java
@Override public STAFResult execute() { StringBuilder resultString = new StringBuilder(); // user for db logger String logdbuser = getRequestOption(Options.DB_USER); // password for db logger String logdbpassword = getRequestOption(Options.DB_PASSWORD); // URL for db logger String logdburl = getRequestOption(Options.DB_URL); if (hasRequestOption(Options.LOG_LOGTEST)) { for (int i = 0; i <= 25; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { //ignore }// w w w .j ava 2 s .c o m Logger.log("LOGTEST:" + i, LogLevel.Debug); } return new STAFResult(STAFResult.Ok, "Logtest at Loglevel Debug executed!"); } /* * everything went fine, thus do the changes and hope that all values are allowed */ // level if (hasRequestOption(Options.LOG_LEVEL)) { String level = getRequestOption(Options.LOG_LEVEL); try { Logger.logLevel = LogLevel.getLevel(level); resultString.append("Log Level set to " + level + "\n"); } catch (Exception e) { return new STAFResult(STAFResult.InvalidValue, "The value '" + level + "' is not allowed as log level. Use one of the following instead: Debug Info Warning Error"); } } // details if (hasRequestOption(Options.LOG_DETAILS)) { String details = getRequestOption(Options.LOG_DETAILS); try { Logger.details = new Boolean(details).booleanValue(); resultString.append("Log Details now " + (Logger.details == true ? "ON" : "OFF") + "\n"); } catch (Exception e) { return new STAFResult(STAFResult.InvalidValue, "The value '" + details + "' is not allowed as detailed logging settings. Use either true or false as value."); } } // Cleaning the logger if (hasRequestOption(Options.LOG_CLEAN)) { String clean = getRequestOption(Options.LOG_CLEAN).trim(); try { ILoggerService logger = getLoggerByName(clean); if (logger == null) return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!"); logger.term(); logger.clean(); Logger.registeredLoggers.remove(logger); logger = logger.getClass().newInstance(); Logger.addLogger(logger); resultString.append("Logger " + clean + " has been cleaned!"); } catch (Exception e) { return new STAFResult(STAFResult.InvalidValue, "The logger '" + clean + "' is unknown. Use one of the following: htmllogger filelogger dblogger sysout livelog livelogreceiver"); } } // remove logger else if (hasRequestOption(Options.LOG_REMOVE)) { String remove = getRequestOption(Options.LOG_REMOVE).trim(); try { if (remove.equalsIgnoreCase("LIVELOG")) { LiveLogger.getInstance().term(); Logger.registeredLoggers.remove(LiveLogger.getInstance()); resultString.append("Logger " + remove + " has been removed \n"); } else { ILoggerService logger = getLoggerByName(remove); if (logger == null) return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!"); logger.term(); Logger.registeredLoggers.remove(logger); resultString.append("Logger has been removed!"); } } catch (Exception e) { return new STAFResult(STAFResult.InvalidValue, "The logger '" + remove + "' to be removed is unknown."); } } // add logger else if (hasRequestOption(Options.LOG_ADD)) { String add = getRequestOption(Options.LOG_ADD); if (add.equalsIgnoreCase("FILELOGGER")) try { Logger.addLogger(new TextLogger()); } catch (IOException e1) { return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a FileLogger."); } else if (add.equalsIgnoreCase("DBLOGGER")) { try { Logger.addLogger(new DatabaseLogger(logdbuser, logdbpassword, logdburl)); } catch (IOException e) { return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a DBLogger: " + e.getMessage()); } catch (InterruptedException e) { // } } else if (add.equalsIgnoreCase("HTMLLOGGER")) try { Logger.addLogger(new HTMLLogger()); } catch (IOException e) { return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a HTMLLogger."); } else if (add.equalsIgnoreCase("LIVELOG")) { if (hasRequestOption(Options.SOCKET_HOST)) { if (getRequestOption(Options.SOCKET_HOST).length() != 0) { LiveLogger liveLogger = LiveLogger.getInstance(); if (!Logger.getCopyOfLoggers().contains(liveLogger)) Logger.addLogger(liveLogger); liveLogger.openServer(getRequestOption(Options.SOCKET_HOST).trim()); return new STAFResult(STAFResult.Ok, "LiveLogger added, it will now accept a live logging connection!"); } } Logger.log("Adding LiveLog not possible: Invalid Host", LogLevel.Error); return new STAFResult(STAFResult.JavaError, "Adding LiveLog not possible: Invalid Host"); } else { Logger.log("Adding Logger failed: no such logger to add found: " + add, LogLevel.Error); return new STAFResult(STAFResult.JavaError, "Adding Logger failed: no such logger to add found: " + add); } resultString.append("Logger " + add + " has been added \n"); } else if (hasRequestOption(Options.LOG_SCHEMA)) { String xsd = null; try { xsd = XMLSerializer.createXMLSchema(LoggerEntry.class); } catch (IOException e) { Logger.log(e.getMessage(), LogLevel.Error); return new STAFResult(STAFResult.JavaError, e.getMessage()); } catch (JAXBException e) { Logger.log(e.getMessage(), LogLevel.Error); return new STAFResult(STAFResult.JavaError, e.getMessage()); } if (xsd != null) return new STAFResult(STAFResult.Ok, xsd); return new STAFResult(STAFResult.JavaError, "Error while creating the Schema"); } // LIST shows logs on the console // schema: // LIST <what> [FILTER <filter>] [COLUMNS <columns>] // <what> = { , n} (empty=all, n=last n) // <filter> = {LEVEL={DEBUG, INFO, WARNING, ERROR}*;REQID=<reqid>} // <columns> = {REQUEST, THREAD, LOGLEVEL, MESSAGE} else if (hasRequestOption(Options.LOG_LIST)) { //read <what> String listValue = getRequestOption(Options.LOG_LIST); //the number of latest entries to retrieve int n = 0; if (listValue.equalsIgnoreCase("")) { //when n<=0, all entries are retrieved n = 0; } else { try { n = Integer.parseInt(listValue); } catch (NumberFormatException e) { return new STAFResult(STAFResult.InvalidValue, "List option needs to be a positive number or empty"); } if (n <= 0) { return new STAFResult(STAFResult.InvalidValue, "List option needs to be a positive number or empty"); } } //read <filter> String levels[] = null; int reqid = 0; if (hasRequestOption(Options.LOG_LIST_FILTER)) { String filter = getRequestOption(Options.LOG_LIST_FILTER).toLowerCase(); StringTokenizer tokenizer = new StringTokenizer(filter, ";"); while (tokenizer.hasMoreElements()) { String option = (String) tokenizer.nextElement(); // an option is of the form key=value if (option.contains("=")) { String key = option.substring(0, option.indexOf("=")); //read LEVEL={DEBUG,INFO,WARNING,ERROR}* if (key.equalsIgnoreCase("level")) { levels = option.substring(option.indexOf("=") + 1).split(","); //Check if the given levels are supported. if (!StringUtility.arrayContainsOnlyIgnoreCase(levels, LogLevel.Debug.toString().trim(), LogLevel.Warning.toString().trim(), LogLevel.Error.toString().trim(), LogLevel.Info.toString().trim())) { return new STAFResult(STAFResult.InvalidValue, "Supporting only Log Levels: " + LogLevel.Debug.toString().trim() + "," + LogLevel.Warning.toString().trim() + "," + LogLevel.Error.toString().trim() + "," + LogLevel.Info.toString().trim()); } //read REQID=<reqid> } else if (key.equals("reqid")) { try { reqid = Integer.parseInt(option.substring(option.indexOf("=") + 1)); } catch (NumberFormatException e) { return new STAFResult(STAFResult.InvalidValue, "REQID needs to be a positive number."); } if (reqid <= 0) { return new STAFResult(STAFResult.InvalidValue, "REQID needs to be a positive number."); } } else { //option is not level= or reqid= return new STAFResult(STAFResult.InvalidValue, "Invalid option in the filter: " + option); } } else { //option doesn't have '=' return new STAFResult(STAFResult.InvalidValue, "Invalid requestOptions in the filter: " + option); } } } //read <columns> String[] cols = null; if (hasRequestOption(Options.LOG_LIST_COL)) { cols = getRequestOption(Options.LOG_LIST_COL).toLowerCase().split(","); if (!StringUtility.arrayContainsOnlyIgnoreCase(cols, "request", "thread", "level", "message")) return new STAFResult(STAFResult.InvalidValue, "Supporting only Columns: Request, Thread, Level, Message."); } // filter the entries accordingly List<LoggerEntry> logEntries = null; if (levels == null || levels.length == 0) { if (reqid == 0) { logEntries = Logger.getLogEntries(n); } else { logEntries = Logger.getLogEntries(n, reqid); } } else { if (reqid == 0) { logEntries = Logger.getLogEntries(n, levels); } else { logEntries = Logger.getLogEntries(n, levels, reqid); } } // print the lines, with selected columns. String ALLCOLUMNS[] = { "Request", "Thread", "Level", "Message" }; String formats[] = { "%1$-8s", " %2$-12s", " %3$-7s", " %4$-100s" }; //if no columns is set, display all columns if (cols == null || cols.length == 0) { cols = ALLCOLUMNS; } //check is one of the four columns exists, and construct the format string. boolean[] colExists = new boolean[ALLCOLUMNS.length]; String format = ""; for (int i = 0; i < ALLCOLUMNS.length; i++) { if (StringUtility.arrayContainsIgnoreCase(cols, ALLCOLUMNS[i])) { colExists[i] = true; format += formats[i]; } } format += "\n"; //print the table head resultString.append(String.format(format, colExists[0] ? "Request" : "", colExists[1] ? "Thread" : "", colExists[2] ? "Level" : "", colExists[3] ? "Message" : "")); resultString.append(String.format(format, colExists[0] ? "-------" : "", colExists[1] ? "------" : "", colExists[2] ? "-----" : "", colExists[3] ? "-------" : "")); //print the log entries for (LoggerEntry logEntry : logEntries) { if (colExists[3]) { //number of chars per row in the message column int charsPerRow = 100; //in case the message contains multiple lines. String msg = logEntry.getMessage(); String[] lines = msg.split("\\n"); for (int i = 0; i < lines.length; i++) { //other columns should only appear once on the first row. String formatedString = String.format(format, (i == 0 && colExists[0]) ? logEntry.getRequestName() : "", (i == 0 && colExists[1]) ? logEntry.getThread() : "", (i == 0 && colExists[2]) ? logEntry.getLevel() : "", StringUtils.left(lines[i], charsPerRow)); resultString.append(formatedString); //if the line is longer than 'charsPerRow', split it into multiple rows if (lines[i].length() > charsPerRow) { //cut every 'charsPerRow' chars out, and put it in a new row. String txt = ""; int j = 1; while ((txt = StringUtils.mid(lines[i], charsPerRow * j, charsPerRow)).length() != 0) { resultString.append(String.format(format, "", "", "", txt)); j++; } } } } else { String formatedString = String.format(format, colExists[0] ? logEntry.getRequestName() : "", colExists[1] ? logEntry.getThread() : "", colExists[2] ? logEntry.getLevel() : "", ""); resultString.append(formatedString); } } } return new STAFResult(STAFResult.Ok, resultString.toString()); }
From source file:org.yamj.core.service.mediaimport.FilenameScanner.java
public void scan(FilenameDTO dto) { // CHECK FOR USE_PARENT_PATTERN matches if (useParentRegex && useParentPattern.matcher(dto.getName()).find()) { // Just go up one parent dto.setRest(dto.getParentName()); LOG.debug("UseParentPattern matched for {} - Using parent folder name: {}", dto.getName(), dto.getParentName());//from w w w. j av a 2s. c om } else { dto.setRest(dto.getName()); } // EXTENSION AND CONTAINER if (dto.isDirectory()) { dto.setContainer("DVD"); dto.setVideoSource("DVD"); } else { // Extract and strip extension String ext = FilenameUtils.getExtension(dto.getRest()); if (ext.length() > 0) { dto.setRest(FilenameUtils.removeExtension(dto.getRest())); dto.setContainer(ext.toUpperCase()); } } dto.setRest(cleanUp(dto.getRest())); // Detect incomplete filenames and add parent folder name to parser for (Pattern pattern : PARENT_FOLDER_PART_PATTERNS) { final Matcher matcher = pattern.matcher(dto.getRest()); if (matcher.find()) { final String parentName = dto.getParentName(); if (parentName == null) { break; } dto.setRest(cleanUp(parentName) + "./." + dto.getRest()); break; } } // Remove version info for (Pattern pattern : movieVersionPatterns) { Matcher matcher = pattern.matcher(dto.getRest()); if (matcher.find()) { dto.setMovieVersion(matcher.group(0)); } dto.setRest(pattern.matcher(dto.getRest()).replaceAll("./.")); } // EXTRAS (Including Trailers) for (Pattern pattern : extraPatterns) { Matcher matcher = pattern.matcher(dto.getRest()); if (matcher.find()) { dto.setExtra(Boolean.TRUE); dto.setPartTitle(matcher.group(1)); dto.setRest(cutMatch(dto.getRest(), matcher, "./EXTRA/.")); break; } } dto.setFps(seekPatternAndUpdateRest(FPS_MAP, dto.getFps(), dto)); dto.setAudioCodec(seekPatternAndUpdateRest(AUDIO_CODEC_MAP, dto.getAudioCodec(), dto)); dto.setVideoCodec(seekPatternAndUpdateRest(VIDEO_CODEC_MAP, dto.getVideoCodec(), dto)); dto.setHdResolution(seekPatternAndUpdateRest(HD_RESOLUTION_MAP, dto.getHdResolution(), dto)); dto.setVideoSource(seekPatternAndUpdateRest(videoSourceMap, dto.getVideoSource(), dto, PART_PATTERNS)); // SEASON + EPISODES { final Matcher matcher = TV_PATTERN.matcher(dto.getRest()); if (matcher.find()) { // logger.finest("It's a TV Show: " + group0); dto.setRest(cutMatch(dto.getRest(), matcher, "./TVSHOW/.")); final Matcher smatcher = SEASON_PATTERN.matcher(matcher.group(0)); smatcher.find(); int season = Integer.parseInt(smatcher.group(1)); dto.setSeason(season); final Matcher ematcher = EPISODE_PATTERN.matcher(matcher.group(0)); while (ematcher.find()) { dto.getEpisodes().add(Integer.parseInt(ematcher.group(1))); } } } // PART { for (Pattern pattern : PART_PATTERNS) { final Matcher matcher = pattern.matcher(dto.getRest()); if (matcher.find()) { dto.setRest(cutMatch(dto.getRest(), matcher, " /PART/ ")); dto.setPart(Integer.parseInt(matcher.group(1))); break; } } } // SETS { for (;;) { final Matcher matcher = SET_PATTERN.matcher(dto.getRest()); if (!matcher.find()) { break; } dto.setRest(cutMatch(dto.getRest(), matcher, PatternUtils.SPACE_SLASH_SPACE)); FilenameDTO.SetDTO set = new FilenameDTO.SetDTO(); dto.getSets().add(set); String n = matcher.group(1); Matcher nmatcher = SET_INDEX_PATTERN.matcher(n); if (nmatcher.find()) { set.setIndex(Integer.parseInt(nmatcher.group(1))); n = cutMatch(n, nmatcher); } set.setTitle(n.trim()); } } // Movie ID detection { Matcher matcher = ID_PATTERN.matcher(dto.getRest()); if (matcher.find()) { dto.setRest(cutMatch(dto.getRest(), matcher, " /ID/ ")); String idString[] = matcher.group(1).split("[-\\s+]"); if (idString.length == 2) { dto.setId(idString[0].toLowerCase(), idString[1]); } else { LOG.debug("Error decoding ID from filename: {}", matcher.group(1)); } } else { matcher = IMDB_PATTERN.matcher(dto.getRest()); if (matcher.find()) { dto.setRest(cutMatch(dto.getRest(), matcher, " /ID/ ")); dto.setId("imdb", matcher.group(1)); } } } // LANGUAGES if (languageDetection) { for (;;) { String language = seekPatternAndUpdateRest(this.languageTools.getStrictLanguageMap(), null, dto); if (language == null) { break; } dto.getLanguages().add(language); } } // TITLE { String rest = dto.getRest(); int iextra = dto.isExtra() ? rest.indexOf("/EXTRA/") : rest.length(); int itvshow = dto.getSeason() >= 0 ? rest.indexOf("/TVSHOW/") : rest.length(); int ipart = dto.getPart() >= 0 ? rest.indexOf("/PART/") : rest.length(); { int min = iextra < itvshow ? iextra : itvshow; min = min < ipart ? min : ipart; // Find first token before trailer, TV show and part // Name should not start with '-' (exclude wrongly marked part/episode titles) String title = ""; StringTokenizer t = new StringTokenizer(rest.substring(0, min), "/[]"); while (t.hasMoreElements()) { String token = t.nextToken(); token = cleanUpTitle(token); if (token.length() >= 1 && token.charAt(0) != '-') { title = token; break; } } boolean first = Boolean.TRUE; while (t.hasMoreElements()) { String token = t.nextToken(); token = cleanUpTitle(token); // Search year (must be next to a non-empty token) if (first) { if (token.length() > 0) { try { int year = Integer.parseInt(token); if (year >= 1800 && year <= 3000) { dto.setYear(year); } } catch (NumberFormatException error) { } } first = Boolean.FALSE; } if (!languageDetection) { break; } // Loose language search if (token.length() >= 2 && token.indexOf('-') < 0) { for (Map.Entry<String, Pattern> e : this.languageTools.getLooseLanguageMap().entrySet()) { Matcher matcher = e.getValue().matcher(token); if (matcher.find()) { dto.getLanguages().add(e.getKey()); } } } } // Search year within title (last 4 digits or 4 digits in parenthesis) if (dto.getYear() < 0) { Matcher ymatcher = MOVIE_YEAR_PATTERN.matcher(title); if (ymatcher.find()) { int year = Integer.parseInt(ymatcher.group(1)); if (year >= 1919 && year <= 2099) { dto.setYear(year); title = cutMatch(title, ymatcher); } } } dto.setTitle(title); } // EPISODE TITLE if (dto.getSeason() >= 0) { itvshow += 8; Matcher matcher = SECOND_TITLE_PATTERN.matcher(rest.substring(itvshow)); while (matcher.find()) { String title = cleanUpTitle(matcher.group(1)); if (title.length() > 0) { if (!skipEpisodeTitle) { dto.setEpisodeTitle(title); } break; } } } // PART TITLE // Just do this for no extra, already named. if ((dto.getPart() >= 0) && !dto.isExtra()) { ipart += 6; Matcher matcher = SECOND_TITLE_PATTERN.matcher(rest.substring(ipart)); while (matcher.find()) { String title = cleanUpTitle(matcher.group(1)); if (title.length() > 0) { dto.setPartTitle(title); break; } } } } }
From source file:org.kchine.rpf.PoolUtils.java
public static URL[] getURLS(String urlsStr) { StringTokenizer st = new StringTokenizer(urlsStr, " "); Vector<URL> result = new Vector<URL>(); while (st.hasMoreElements()) { try {/*w w w. j a v a2s . c om*/ result.add(new URL((String) st.nextElement())); } catch (Exception e) { e.printStackTrace(); } } return (URL[]) result.toArray(new URL[0]); }
From source file:com.serena.rlc.provider.servicenow.ServiceNowBaseServiceProvider.java
private FieldInfo createSelectionList(String fieldName, String selectionValues) { logger.debug("Creating selection list from: {} - {}", fieldName, selectionValues); StringTokenizer st = new StringTokenizer(selectionValues, ",;"); FieldInfo fieldInfo = new FieldInfo(fieldName); List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value;//from w ww . ja v a 2 s.c o m String status; while (st.hasMoreElements()) { status = (String) st.nextElement(); status = status.trim(); value = new FieldValueInfo(status, status); values.add(value); } fieldInfo.setValues(values); return fieldInfo; }
From source file:org.kchine.rpf.PoolUtils.java
public static HashMap<String, String> getParameters(String parametersStr) { StringTokenizer st = new StringTokenizer(parametersStr, "~/~"); HashMap<String, String> result = new HashMap<String, String>(); while (st.hasMoreElements()) { try {/*from w w w . ja va2 s. c o m*/ String element = (String) st.nextElement(); int p = element.indexOf('='); if (p == -1) { result.put(element, null); } else { result.put(element.substring(0, p).trim(), element.substring(p + 1, element.length()).trim()); } } catch (Exception e) { e.printStackTrace(); } } return result; }