List of usage examples for java.util StringTokenizer countTokens
public int countTokens()
From source file:OverwriteProperties.java
/** Description of the Method */ public void execute() throws FileNotFoundException, IOException, SecurityException { if (verbose) { System.out.println("Merging into file " + getBaseProperties() + " file " + getProperties()); }//from www . j a va 2 s . c om if (!getBaseProperties().exists()) { throw new FileNotFoundException("Could not find file:" + getBaseProperties()); } if (!getProperties().exists()) { throw new FileNotFoundException("Could not find file:" + getProperties()); } if (!getIncludeRoot().exists() || !getIncludeRoot().isDirectory()) { throw new FileNotFoundException("Could not find directory:" + getIncludeRoot()); } BufferedReader reader = new BufferedReader(new FileReader(baseProperties)); int index = 0; String key = null; String line = null; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line, "="); baseArray.add(index, line); if (verbose) { System.out.println("While reading baseArray[" + index + "] = " + line); } if (tokenizer.countTokens() >= 1 && !line.startsWith("#") && !line.startsWith("include") && !line.startsWith("module.packages")) { key = tokenizer.nextToken().trim(); if (key != null && key.length() > 0) { baseMap.put(key, new Integer(index)); if (verbose) { System.out.println("baseMap[" + key + "," + index + "]"); } } } index++; } reader.close(); if (verbose) { System.out.println("\nOverwrite with Delta\n"); } readProperties(properties, index); boolean flags[] = removeProperties(); baseArray.trimToSize(); writeToFile(flags); }
From source file:edu.ucla.stat.SOCR.chart.demo.PowerTransformHistogramChart.java
public void setDataTable(String input) { hasExample = true;//from w ww.j av a2 s . co m StringTokenizer lnTkns = new StringTokenizer(input, "#,"); String line; int lineCt = lnTkns.countTokens(); resetTableRows(lineCt); resetTableColumns(1); int r = 0; while (lnTkns.hasMoreTokens()) { line = lnTkns.nextToken(); dataTable.setValueAt(line, r, 0); r++; } // this will update the mapping panel resetTableColumns(dataTable.getColumnCount()); }
From source file:edu.ucla.stat.SOCR.chart.SuperIntervalXYChart_Time.java
public void setDataTable(String input) { hasExample = true;//ww w . ja v a2 s . c om StringTokenizer lnTkns = new StringTokenizer(input, "#"); String line; int lineCt = lnTkns.countTokens(); resetTableRows(lineCt); int r = 0; while (lnTkns.hasMoreTokens()) { line = lnTkns.nextToken(); // String tb[] =line.split("\t"); StringTokenizer cellTkns = new StringTokenizer(line, " \t\f,");// IE use "space" Mac use tab as cell separator int cellCnt = cellTkns.countTokens(); String tb[] = new String[cellCnt]; int r1 = 0; while (cellTkns.hasMoreTokens()) { tb[r1] = cellTkns.nextToken(); r1++; } //System.out.println("tb.length="+tb.length); int colCt = tb.length; resetTableColumns(colCt); for (int i = 0; i < tb.length; i++) { //System.out.println(tb[i]); if (tb[i].length() == 0) tb[i] = "0"; dataTable.setValueAt(tb[i], r, i); } r++; } // this will update the mapping panel resetTableColumns(dataTable.getColumnCount()); // comment out, let setXLabel and setYLabel take care of this /* resetTableColumns(dataTable.getColumnCount()); TableColumnModel columnModel= dataTable.getColumnModel(); dataTable.setTableHeader(new EditableHeader(columnModel)); System.out.println(dataTable.getColumnCount() +" "+dataTable.getRowCount()); int seriesCount = dataTable.getColumnCount()/2; for (int i=0; i<seriesCount; i++){ addButtonIndependent(); addButtonDependent(); }*/ }
From source file:com.netxforge.oss2.core.utilsII.ExecRunner.java
/** * The <code>exec(String, PrintWriter, PrintWriter)</code> method runs a * process inside of a watched thread. It returns the client's exit code and * feeds its STDOUT and STDERR to the passed-in streams. * * @return The command's return code// ww w . jav a 2s .co m * @param command * The program or command to run * @param stdoutWriter * java.io.PrintWriter * @param stderrWriter * java.io.PrintWriter * @throws java.io.IOException * thrown if a problem occurs * @throws java.lang.InterruptedException * thrown if a problem occurs */ public int exec(final String command, final PrintWriter stdoutWriter, final PrintWriter stderrWriter) throws IOException, InterruptedException { // Default exit value is non-zero to indicate a problem. int exitVal = 1; // ////////////////////////////////////////////////////////////// final Runtime rt = Runtime.getRuntime(); Process proc; String[] cmd = null; // First get the start time & calculate comparison numbers final Date startTime = new Date(); final long startTimeMs = startTime.getTime(); final long maxTimeMs = startTimeMs + (maxRunTimeSecs * 1000); // ////////////////////////////////////////////////////////////// // First determine the OS to build the right command string final String osName = System.getProperty("os.name"); if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equals("Windows ME")) { cmd = new String[3]; cmd[0] = WINDOWS_9X_ME_COMMAND_1; cmd[1] = WINDOWS_9X_ME_COMMAND_2; cmd[2] = command; } else if (osName.contains("Windows")) { // "Windows NT", "Windows 2000", etc. cmd = new String[3]; cmd[0] = WINDOWS_NT_2000_COMMAND_1; cmd[1] = WINDOWS_NT_2000_COMMAND_2; cmd[2] = command; } else { // Linux (and probably other *nixes) prefers to be called // with each argument supplied separately, so we first // Tokenize it across spaces as the boundary. final StringTokenizer st = new StringTokenizer(command, " "); cmd = new String[st.countTokens()]; int token = 0; while (st.hasMoreTokens()) { String tokenString = st.nextToken(); cmd[token++] = tokenString; } } // Execute the command and start the two output gobblers if (cmd != null && cmd.length > 0) { proc = rt.exec(cmd); } else { throw new IOException("Insufficient commands!"); } final StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), stdoutWriter); final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), stderrWriter); outputGobbler.start(); errorGobbler.start(); // Wait for the program to finish running and return the // exit value obtained from the executable while (true) { try { exitVal = proc.exitValue(); break; } catch (final IllegalThreadStateException e) { // If we get this exception, then the process isn't // done executing and we determine if our time is up. if (maxRunTimeSecs > 0) { final Date endTime = new Date(); final long endTimeMs = endTime.getTime(); if (endTimeMs > maxTimeMs) { // Time's up - kill the process and the gobblers and // return proc.destroy(); maxRunTimeExceeded = true; stderrWriter.println(MAX_RUN_TIME_EXCEEDED_STRING); outputGobbler.quit(); errorGobbler.quit(); return exitVal; } else { // Time is not up yet so wait 100 ms before testing // again Thread.sleep(POLL_DELAY_MS); } } } } // ////////////////////////////////////////////////////////////// // Wait for output gobblers to finish forwarding the output while (outputGobbler.isAlive() || errorGobbler.isAlive()) { } // ////////////////////////////////////////////////////////////// // All done, flush the streams and return the exit value stdoutWriter.flush(); stderrWriter.flush(); return exitVal; }
From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java
/** * delete files form target//from w ww . jav a 2s . c om * @param parameters * @param target * @param changeSet */ protected void deleteFromTarget(Map<String, String> parameters, PublishingTarget target, PublishedChangeSet changeSet) { String deletedList = parameters.get(PARAM_DELETED_FILES); String site = parameters.get(PARAM_SITE); if (deletedList != null) { StringTokenizer tokens = new StringTokenizer(deletedList, FILES_SEPARATOR); List<String> deletedFiles = new ArrayList<String>(tokens.countTokens()); while (tokens.hasMoreElements()) { String contentLocation = tokens.nextToken(); contentLocation = StringUtils.trimWhitespace(contentLocation); String root = target.getParameter(CONFIG_ROOT); String fullPath = root + File.separator + target.getParameter(CONFIG_CONTENT_FOLDER) + contentLocation; if (LOGGER.isInfoEnabled()) { LOGGER.info("deleting " + fullPath); } if (StringUtils.hasText(site)) { fullPath = fullPath.replaceAll(CONFIG_MULTI_TENANCY_VARIABLE, site); } File file = new File(fullPath); if (file.exists()) { if (file.isFile()) { file.delete(); deletedFiles.add(contentLocation); } else { deleteChildren(file.list(), fullPath, contentLocation, deletedFiles); file.delete(); } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug(fullPath + " is not deleted since it does not exsit."); } } fullPath = root + '/' + target.getParameter(CONFIG_METADATA_FOLDER) + contentLocation + CONFIG_METADATA_FILENAME_SUFFIX; if (LOGGER.isDebugEnabled()) { LOGGER.debug("deleting " + fullPath); } if (StringUtils.hasText(site)) { fullPath = fullPath.replaceAll(CONFIG_MULTI_TENANCY_VARIABLE, site); } file = new File(fullPath); if (file.exists()) { file.delete(); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug(fullPath + " is not deleted since it does not exsit."); } } changeSet.setDeletedFiles(deletedFiles); } }
From source file:edu.ucla.stat.SOCR.chart.SuperBoxAndWhiskerChart.java
/** * /*w w w .j a v a 2s . c o m*/ * @param in * @return */ protected List createValueList(String in) { vs = in; // String[] values = in.split("( *)+,+( *)"); // int count = java.lang.reflect.Array.getLength(values); StringTokenizer st = new StringTokenizer(in, DELIMITERS); int count = st.countTokens(); String[] values = new String[count]; for (int i = 0; i < count; i++) values[i] = st.nextToken(); List<Double> result = new java.util.ArrayList<Double>(); try { double v; for (int i = 0; i < count; i++) { if (values[i] != null && values[i].length() != 0) { v = Double.parseDouble(values[i]); result.add(new Double(v)); } } } catch (NumberFormatException e) { showMessageDialog("Data format error!"); return null; } return result; }
From source file:com.silverpeas.form.displayers.CheckBoxDisplayer.java
/** * Prints the HTML value of the field. The displayed value must be updatable by the end user. The * value format may be adapted to a local language. The fieldName must be used to name the html * form input. Never throws an Exception but log a silvertrace and writes an empty string when : * <ul>/*from ww w . j a va2 s.c om*/ * <li>the field type is not a managed type.</li> * </ul> * * @param out * @param field * @param template * @param PagesContext * @throws FormException */ @Override public void display(PrintWriter out, TextField field, FieldTemplate template, PagesContext PagesContext) throws FormException { String selectedValues = ""; List<String> valuesFromDB = new ArrayList<String>(); String keys = ""; String values = ""; StringBuilder html = new StringBuilder(); int cols = 1; String language = PagesContext.getLanguage(); String fieldName = template.getFieldName(); Map<String, String> parameters = template.getParameters(language); if (!field.isNull()) { selectedValues = field.getValue(language); } StringTokenizer st = new StringTokenizer(selectedValues, "##"); while (st.hasMoreTokens()) { valuesFromDB.add(st.nextToken()); } if (parameters.containsKey("keys")) { keys = parameters.get("keys"); } if (parameters.containsKey("values")) { values = parameters.get("values"); } String cssClass = null; if (parameters.containsKey("class")) { cssClass = parameters.get("class"); if (StringUtil.isDefined(cssClass)) { cssClass = "class=\"" + cssClass + "\""; } } try { if (parameters.containsKey("cols")) { cols = Integer.valueOf(parameters.get("cols")); } } catch (NumberFormatException nfe) { SilverTrace.error("form", "CheckBoxDisplayer.display", "form.EX_ERR_ILLEGAL_PARAMETER_COL", parameters.get("cols")); cols = 1; } // if either keys or values is not filled // take the same for keys and values if ("".equals(keys) && !"".equals(values)) { keys = values; } if ("".equals(values) && !"".equals(keys)) { values = keys; } StringTokenizer stKeys = new StringTokenizer(keys, "##"); StringTokenizer stValues = new StringTokenizer(values, "##"); int nbTokens = getNbHtmlObjectsDisplayed(template, PagesContext); if (stKeys.countTokens() != stValues.countTokens()) { SilverTrace.error("form", "CheckBoxDisplayer.display", "form.EX_ERR_ILLEGAL_PARAMETERS", "Nb keys=" + stKeys.countTokens() + " & Nb values=" + stValues.countTokens()); } else { html.append("<table border=\"0\">"); int col = 0; for (int i = 0; i < nbTokens; i++) { if (col == 0) { html.append("<tr>"); } col++; html.append("<td>"); String optKey = stKeys.nextToken(); String optValue = stValues.nextToken(); html.append("<input type=\"checkbox\" id=\"").append(fieldName).append("_").append(i); html.append("\" name=\"").append(fieldName).append("\" value=\"").append(optKey).append("\" "); if (StringUtil.isDefined(cssClass)) { html.append(cssClass); } if (template.isDisabled() || template.isReadOnly()) { html.append(" disabled=\"disabled\" "); } if (valuesFromDB.contains(optKey)) { html.append(" checked=\"checked\" "); } html.append("/> ").append(optValue); // last checkBox if (i == nbTokens - 1) { if (template.isMandatory() && !template.isDisabled() && !template.isReadOnly() && !template.isHidden() && PagesContext.useMandatory()) { html.append(Util.getMandatorySnippet()); } } html.append("</td>"); html.append("\n"); if (col == cols) { html.append("</tr>"); col = 0; } } if (col != 0) { html.append("</tr>"); } html.append("</table>"); } out.println(html); }
From source file:org.apache.ctakes.lvg.ae.LvgAnnotator.java
/** * Helper method that loads a Norm cache file. * /* www . java 2s . co m*/ * @param location */ private void loadCmdCacheFile(String cpLocation) throws FileNotFoundException, IOException { try (InputStream inStream = getClass().getResourceAsStream(cpLocation); BufferedReader br = new BufferedReader(new InputStreamReader(inStream));) { // initialize map normCacheMap = new HashMap<>(); String line = br.readLine(); while (line != null) { StringTokenizer st = new StringTokenizer(line, "|"); if (st.countTokens() == 7) { int freq = Integer.parseInt(st.nextToken()); if (freq > cmdCacheFreqCutoff) { String origWord = st.nextToken(); String normWord = st.nextToken(); if (!normCacheMap.containsKey(origWord)) { // if there are duplicates, then only have the first // occurrence in the map normCacheMap.put(origWord, normWord); } } else { logger.debug("Discarding norm cache line due to frequency cutoff: " + line); } } else { logger.warn("Invalid LVG norm cache " + "line: " + line); } line = br.readLine(); } } }
From source file:net.ontopia.topicmaps.webed.taglibs.form.FormTag.java
/** * Renders the input form element with it's content. *//*from w w w . j a v a 2 s . c o m*/ @Override public int doAfterBody() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); TagUtils.setCurrentFormTag(request, null); VelocityContext vc = TagUtils.getVelocityContext(pageContext); // attributes of the form element vc.put("name", NAME); String id = idattr; if (id == null) id = requestId; // Use requestId by default, to make sure there always is an id. vc.put("idattr", id); // -- class if (klass != null) vc.put("class", klass); validationRules = getFieldValidationRules(); if (!validationRules.isEmpty()) { vc.put("performFieldValidation", Boolean.TRUE); vc.put("validationRules", validationRules); vc.put("onsubmit", "return validate('" + id + "');"); } else vc.put("onsubmit", "return true;"); vc.put("outputSubmitFunc", getOutputSubmitFunc()); // reset the outputSubmitFunc variable setOutputSubmitFunc(false); // -- action String context_name = request.getContextPath(); String default_action = context_name + "/" + Constants.PROCESS_SERVLET; vc.put("action", (action_uri != null) ? action_uri : default_action); ActionRegistryIF registry = TagUtils.getActionRegistry(pageContext); // -- target (only in the case of a multi framed web app) if (registry == null) throw new JspException( "No action registry available! Check actions.xml for errors; see log for details."); vc.put("target", target); // -- enctype if (enctype != null) vc.put("enctype", enctype); // -- nested if (nested != null) vc.put("nested", nested); if (lockVarname != null) vc.put(Constants.RP_LOCKVAR, lockVarname); NavigatorPageIF contextTag = FrameworkUtils.getContextTag(pageContext); // add hidden parameter value pairs to identify the request String topicmap_id = request.getParameter(Constants.RP_TOPICMAP_ID); if (topicmap_id == null && contextTag != null) { // if not set try to retrieve it from the nav context NavigatorApplicationIF navApp = contextTag.getNavigatorApplication(); TopicMapIF tm = contextTag.getTopicMap(); if (tm != null) topicmap_id = navApp.getTopicMapRefId(tm); } vc.put(Constants.RP_TOPICMAP_ID, topicmap_id); vc.put(Constants.RP_TOPIC_ID, request.getParameter(Constants.RP_TOPIC_ID)); vc.put(Constants.RP_ASSOC_ID, request.getParameter(Constants.RP_ASSOC_ID)); vc.put(Constants.RP_ACTIONGROUP, actiongroup); vc.put(Constants.RP_REQUEST_ID, requestId); // FIXME: Do we really need this line? Probably not, since each control // should now itself be responisible for determining whether it should be // readonly. Hence the individual control can overrule the form setting. // vc.put("readonly", TagUtils.isFormReadOnly(request)); // content inside the form element BodyContent body = getBodyContent(); vc.put("content", body.getString()); // render JavaScript to set the input focus (if required) if (focus != null) { String focus_elem = focus; StringBuilder focus_ref = new StringBuilder("["); if (focus_elem.indexOf('[') > 0) { StringTokenizer st = new StringTokenizer(focus_elem, "["); if (st.countTokens() == 2) { focus_elem = st.nextToken(); focus_ref.append(st.nextToken()); } } vc.put("focus_elem", focus_elem); if (focus_ref.length() > 1) vc.put("focus_ref", focus_ref.toString()); else vc.put("focus_ref", ""); } // all variables are now set, proceed with outputting TagUtils.processWithVelocity(pageContext, TEMPLATE_FILE, getBodyContent().getEnclosingWriter(), vc); // clear read-only state request.removeAttribute(Constants.OKS_FORM_READONLY); return SKIP_BODY; }
From source file:org.apache.ctakes.lvg.ae.LvgAnnotator.java
/** * Sets configuration parameters with values from the descriptor. *///from w w w . j a va2 s. c o m private void configInit() { skipSegmentsSet = new HashSet<>(); for (int i = 0; i < skipSegmentIDs.length; i++) { skipSegmentsSet.add(skipSegmentIDs[i]); } // Load Xerox Treebank tagset map xeroxTreebankMap = new HashMap<>(); for (int i = 0; i < xtMaps.length; i++) { StringTokenizer tokenizer = new StringTokenizer(xtMaps[i], "|"); if (tokenizer.countTokens() == 2) { String xTag = tokenizer.nextToken(); String tTag = tokenizer.nextToken(); xeroxTreebankMap.put(xTag, tTag); } } exclusionSet = new HashSet<>(); for (int i = 0; i < wordsToExclude.length; i++) { exclusionSet.add(wordsToExclude[i]); } }