List of usage examples for java.util StringTokenizer countTokens
public int countTokens()
From source file:edu.ucla.stat.SOCR.chart.SuperDotChart.java
/** * reset dataTable to default (demo data), and refesh chart *///from ww w .ja va 2 s.c o m protected List createValueList(String in) { // System.out.println("in="+in); String 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 { for (int i = 0; i < count; i++) { double v = Double.parseDouble(values[i]); result.add(new Double(v)); } } catch (NumberFormatException e) { showMessageDialog("Data format error!"); return null; } return result; }
From source file:edu.ucla.stat.SOCR.chart.demo.BoxAndWhiskerChartDemo2.java
protected BoxAndWhiskerCategoryDataset createDataset(boolean isDemo) { if (isDemo) { SERIES_COUNT = 1;/*ww w .j av a 2s. co m*/ CATEGORY_COUNT = 1; VALUE_COUNT = 10; values_storage = new String[SERIES_COUNT][CATEGORY_COUNT]; DefaultBoxAndWhiskerCategoryDataset result = new DefaultBoxAndWhiskerCategoryDataset(); List values = createValueList(0, 20.0, VALUE_COUNT); values_storage[0][0] = vs; result.add(values, "", "Data"); raw_y = new String[VALUE_COUNT]; StringTokenizer st = new StringTokenizer(vs, DELIMITERS); data_count = st.countTokens(); for (int i = 0; i < data_count; i++) { raw_y[i] = st.nextToken(); } return result; } else { setArrayFromTable(); int row_count = xyLength; //System.out.println("row_count="+row_count); raw_y = new String[row_count]; data_count = 0; String v_list = new String(); independentVarLength = 1; for (int index = 0; index < independentVarLength; index++) for (int i = 0; i < xyLength; i++) { raw_y[i] = indepValues[i][index]; try { Double.parseDouble(raw_y[i]); data_count++; v_list += raw_y[i] + ","; } catch (Exception e) { System.out.println("Skipping " + raw_y[i]); } } // create the dataset... DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); SERIES_COUNT = 1; CATEGORY_COUNT = 1; values_storage = new String[SERIES_COUNT][CATEGORY_COUNT]; dataset.add(createValueList(v_list), "", independentHeaders[0]); values_storage[0][0] = vs; return dataset; } }
From source file:com.javielinux.utils.Utils.java
static public ArrayList<URLContent> urls2content(String urls) { /*Log.d(Utils.TAG, "urls: " + urls); urls = urls.replace("--", SEP_BLOCK); urls = urls.replace(";;", SEP_VALUES); Log.d(Utils.TAG, "urls: " + urls);*/ ArrayList<URLContent> out = new ArrayList<URLContent>(); StringTokenizer tokens = new StringTokenizer(urls, SEP_BLOCK); while (tokens.hasMoreTokens()) { try {/*from ww w.ja v a2s . com*/ String token = tokens.nextToken(); StringTokenizer hash = new StringTokenizer(token, SEP_VALUES); if (hash.countTokens() == 3 || hash.countTokens() == 5) { URLContent u = new URLContent(); u.normal = hash.nextToken(); u.display = hash.nextToken(); u.expanded = hash.nextToken(); if (hash.hasMoreTokens()) u.linkMediaThumb = hash.nextToken(); if (hash.hasMoreTokens()) u.linkMediaLarge = hash.nextToken(); if (u.linkMediaThumb != null && !u.linkMediaThumb.equals("")) { CacheData.getInstance().putURLMedia(u.expanded, u); } out.add(u); } } catch (Exception e) { e.printStackTrace(); } } return out; }
From source file:egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService.java
/** * Config ? ? Address /* w w w.j a v a 2 s . co m*/ * @param address * Config ? ? address * @throws FdlException * IP ?? */ public void setAddress(String address) throws FdlException { // this.address = address; byte[] addressBytes = new byte[6]; if (null == address) { logger.warn("IDGeneration Service : Using a random number as the " + "base for id's. This is not the best method for many " + "purposes, but may be adequate in some circumstances." + " Consider using an IP or ethernet (MAC) address if " + "available. "); for (int i = 0; i < 6; i++) { addressBytes[i] = (byte) (255 * Math.random()); } } else { if (address.indexOf(".") > 0) { // we should have an IP StringTokenizer stok = new StringTokenizer(address, "."); if (stok.countTokens() != 4) { throw new FdlException(ERROR_STRING); } addressBytes[0] = (byte) 255; addressBytes[1] = (byte) 255; int i = 2; try { while (stok.hasMoreTokens()) { addressBytes[i++] = Integer.valueOf(stok.nextToken(), 16).byteValue(); } } catch (Exception e) { throw new FdlException(ERROR_STRING); } } else if (address.indexOf(":") > 0) { // we should have a MAC StringTokenizer stok = new StringTokenizer(address, ":"); if (stok.countTokens() != 6) { throw new FdlException(ERROR_STRING); } int i = 0; try { while (stok.hasMoreTokens()) { addressBytes[i++] = Integer.valueOf(stok.nextToken(), 16).byteValue(); } } catch (Exception e) { throw new FdlException(ERROR_STRING); } } else { throw new FdlException(ERROR_STRING); } } mAddressId = Base64.encode(addressBytes); }
From source file:edu.vt.middleware.servlet.filter.RequestMethodFilter.java
/** * Initialize this filter./* w w w . ja va 2 s .com*/ * * @param config <code>FilterConfig</code> */ public void init(final FilterConfig config) { final Enumeration<?> e = config.getInitParameterNames(); while (e.hasMoreElements()) { final String name = (String) e.nextElement(); final String value = config.getInitParameter(name); final StringTokenizer st = new StringTokenizer(name); final String methodName = st.nextToken(); Object[] args = null; Class<?>[] params = null; if (st.countTokens() > 0) { args = new Object[st.countTokens()]; params = new Class[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { final String token = st.nextToken(); args[i] = token; params[i++] = token.getClass(); } } try { this.servletMethods.put(methodName, ServletRequest.class.getMethod(methodName, params)); if (LOG.isDebugEnabled()) { LOG.debug("Found method " + methodName + " for ServletRequest"); } } catch (NoSuchMethodException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Could not find method " + methodName + " for ServletRequest"); } } try { this.httpServletMethods.put(methodName, HttpServletRequest.class.getMethod(methodName, params)); if (LOG.isDebugEnabled()) { LOG.debug("Found method " + methodName + " for HttpServletRequest"); } } catch (NoSuchMethodException ex) { if (LOG.isDebugEnabled()) { LOG.debug("Could not find method " + methodName + " for HttpServletRequest"); } } this.arguments.put(methodName, args); this.patterns.put(methodName, Pattern.compile(value)); if (LOG.isDebugEnabled()) { if (this.arguments.get(methodName) != null) { if (LOG.isDebugEnabled()) { LOG.debug("Stored method name = " + methodName + ", pattern = " + value + " with these arguments " + Arrays.asList((Object[]) this.arguments.get(methodName))); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Stored method name = " + methodName + ", pattern = " + value + " with no arguments"); } } } } }
From source file:com.easytrack.component.system.LicenseCheck.java
private void parseKey(License l, String licenseKey) throws Exception { String digest = ""; StringTokenizer st = new StringTokenizer(licenseKey, ";"); int tokenCount = st.countTokens(); if (tokenCount > 4) { int cnt = 0; while (st.hasMoreTokens()) { cnt++;//from w w w .j a v a 2 s .c o m switch (cnt) { case 1: digest = st.nextToken(); break; case 2: l.setAdminEmail(st.nextToken()); break; case 3: l.setLicenseCount(Integer.parseInt(st.nextToken())); break; case 4: String companyName = st.nextToken(); if (l.getCompanyName() == null) l.setCompanyName(companyName); break; case 5: l.setLanguage(st.nextToken()); break; case 6: l.setExpiredDate(st.nextToken()); } } System.out.println(l.toString()); // if ((l.getExpiredDate() == null) || ("".equals(l.getExpiredDate()))) { //// List address = getPhysicalAddress(); // boolean hasMAC = false; // for (int i = 0; i < address.size(); i++) { // String mac = (String) address.get(i); // System.out.println(mac); // String calculatedDigest = CipherUtils.getInstance().digest( // mac); // if (calculatedDigest.equals(digest)) { // hasMAC = true; // break; // } // } // if (!hasMAC) { // l.setLicenseCount(0); // throw new CommonException("InvalidLicenseKey"); // } // } } else { throw new CommonException("InvalidLicenseKey"); } }
From source file:roommateapp.info.net.FileDownloader.java
/** * Parallel execution// w ww . j av a 2s. c o m */ @SuppressLint("UseValueOf") @Override protected Object doInBackground(Object... params) { if (!this.isHolidayFile) { /* Progressbar einblenden */ this.ac.runOnUiThread(new Runnable() { public void run() { toggleProgressbar(); } }); } boolean success = true; String eingabe = (String) params[0]; if (eingabe != null) { try { URL url = new URL(eingabe); // Get filename String fileName = eingabe; StringTokenizer tokenizer = new StringTokenizer(fileName, "/", false); int tokens = tokenizer.countTokens(); for (int i = 0; i < tokens; i++) { fileName = tokenizer.nextToken(); } // Create file this.downloadedFile = new File(this.roommateDirectory, fileName); // Download and write file try { // Password and username if it's HTACCESS String authData = new String(Base64.encode((username + ":" + pw).getBytes(), Base64.NO_WRAP)); URLConnection urlcon = url.openConnection(); // Authorisation if it's a userfile if (eingabe.startsWith(RoommateConfig.URL)) { urlcon.setRequestProperty("Authorization", "Basic " + authData); urlcon.setDoInput(true); } InputStream inputstream = urlcon.getInputStream(); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = inputstream.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(this.downloadedFile); fos.write(baf.toByteArray()); fos.close(); } catch (IOException e) { success = false; e.printStackTrace(); } } catch (MalformedURLException e) { success = false; e.printStackTrace(); } } else { success = false; } return new Boolean(success); }
From source file:com.javielinux.utils.Utils.java
static public String[] toHTMLTyped(Context cnt, String text, String urls, String underline) { // 1 normal/* w w w .j a v a 2s.c om*/ // 2 display // 3 Expanded int type = Integer.parseInt(Utils.getPreference(cnt).getString("prf_show_links", "2")); String[] out = new String[2]; if (urls == null || urls.equals("") || type == 1) { out[0] = text; out[1] = Utils.toHTML(cnt, text); return out; } //ArrayList<InfoURLEntity> ents = new ArrayList<InfoURLEntity>(); String normalText = text; String htmlText = Utils.toHTML(cnt, text, underline); StringTokenizer tokens = new StringTokenizer(urls, SEP_BLOCK); while (tokens.hasMoreTokens()) { try { String token = tokens.nextToken(); StringTokenizer hash = new StringTokenizer(token, SEP_VALUES); if (hash.countTokens() == 3 || hash.countTokens() == 5) { //InfoURLEntity e = new InfoURLEntity(); String url = hash.nextToken(); String urlDisplay = hash.nextToken(); String urlExpanded = hash.nextToken(); if (type == 2) { normalText = normalText.replace(url, urlDisplay); htmlText = htmlText.replace(url, urlDisplay); } else { normalText = normalText.replace(url, urlExpanded); htmlText = htmlText.replace(url, urlExpanded); } //ents.add(e); } } catch (Exception e) { e.printStackTrace(); } } out[0] = normalText; out[1] = htmlText; return out; }
From source file:org.alfresco.web.app.servlet.UploadContentServlet.java
/** * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// w w w . j av a2s. c o m protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (logger.isDebugEnabled() == true) { String queryString = req.getQueryString(); logger.debug("Authenticating request to URL: " + req.getRequestURI() + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); } AuthenticationStatus status = servletAuthenticate(req, res, false); if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } // Tokenise the URI String uri = req.getRequestURI(); uri = uri.substring(req.getContextPath().length()); StringTokenizer t = new StringTokenizer(uri, "/"); int tokenCount = t.countTokens(); t.nextToken(); // skip servlet name // get or calculate the noderef and filename to download as NodeRef nodeRef = null; String filename = null; QName propertyQName = null; if (tokenCount == 2) { // filename is the only token filename = t.nextToken(); } else if (tokenCount == 4 || tokenCount == 5) { // assume 'workspace' or other NodeRef based protocol for remaining URL // elements StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken()); String id = t.nextToken(); // build noderef from the appropriate URL elements nodeRef = new NodeRef(storeRef, id); if (tokenCount == 5) { // filename is last remaining token filename = t.nextToken(); } // get qualified of the property to get content from - default to // ContentModel.PROP_CONTENT propertyQName = ContentModel.PROP_CONTENT; String property = req.getParameter(ARG_PROPERTY); if (property != null && property.length() != 0) { propertyQName = QName.createQName(property); } } else { logger.debug("Upload URL did not contain all required args: " + uri); res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); return; } // get the services we need to retrieve the content ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext()); ContentService contentService = serviceRegistry.getContentService(); PermissionService permissionService = serviceRegistry.getPermissionService(); MimetypeService mimetypeService = serviceRegistry.getMimetypeService(); NodeService nodeService = serviceRegistry.getNodeService(); InputStream is = req.getInputStream(); BufferedInputStream inputStream = new BufferedInputStream(is); // Sort out the mimetype String mimetype = req.getParameter(ARG_MIMETYPE); if (mimetype == null || mimetype.length() == 0) { mimetype = MIMETYPE_OCTET_STREAM; if (filename != null) { MimetypeService mimetypeMap = serviceRegistry.getMimetypeService(); int extIndex = filename.lastIndexOf('.'); if (extIndex != -1) { String ext = filename.substring(extIndex + 1); mimetype = mimetypeService.getMimetype(ext); } } } // Get the encoding String encoding = req.getParameter(ARG_ENCODING); if (encoding == null || encoding.length() == 0) { // Get the encoding ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder(); Charset charset = charsetFinder.getCharset(inputStream, mimetype); encoding = charset.name(); } // Get the locale Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE)); if (locale == null) { locale = I18NUtil.getContentLocale(); if (nodeRef != null) { ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName); if (contentData != null) { locale = contentData.getLocale(); } } } if (logger.isDebugEnabled()) { if (nodeRef != null) { logger.debug("Found NodeRef: " + nodeRef.toString()); } logger.debug("For property: " + propertyQName); logger.debug("File name: " + filename); logger.debug("Mimetype: " + mimetype); logger.debug("Encoding: " + encoding); logger.debug("Locale: " + locale); } // Check that the user has the permissions to write the content if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) { if (logger.isDebugEnabled() == true) { logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString()); } if (logger.isDebugEnabled()) { logger.debug("Returning 403 Forbidden error..."); } res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Try and get the content writer ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true); if (writer == null) { if (logger.isDebugEnabled() == true) { logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString()); } res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED); return; } // Set the mimetype, encoding and locale writer.setMimetype(mimetype); writer.setEncoding(encoding); if (locale != null) { writer.setLocale(locale); } // Stream the content into the repository writer.putContent(inputStream); if (logger.isDebugEnabled() == true) { logger.debug("Content details: " + writer.getContentData().toString()); } // Set return status res.getWriter().write(writer.getContentData().toString()); res.flushBuffer(); if (logger.isDebugEnabled() == true) { logger.debug("UploadContentServlet done"); } }
From source file:net.lightbody.bmp.proxy.jetty.servlet.AdminServlet.java
private String doAction(HttpServletRequest request) throws IOException { String action = request.getParameter("A"); if ("exit all servers".equalsIgnoreCase(action)) { new Thread(new Runnable() { public void run() { try { Thread.sleep(1000); } catch (Exception e) { LogSupport.ignore(log, e); }// w w w . j a v a 2s. co m log.info("Stopping All servers"); Iterator s = _servers.iterator(); while (s.hasNext()) { HttpServer server = (HttpServer) s.next(); try { server.stop(); } catch (Exception e) { LogSupport.ignore(log, e); } } log.info("Exiting JVM"); System.exit(1); } }).start(); throw new HttpException(HttpResponse.__503_Service_Unavailable); } boolean start = "start".equalsIgnoreCase(action); String id = request.getParameter("ID"); StringTokenizer tok = new StringTokenizer(id, ":"); int tokens = tok.countTokens(); String target = null; try { target = tok.nextToken(); int t = Integer.parseInt(target); Iterator s = _servers.iterator(); HttpServer server = null; while (s.hasNext() && t >= 0) if (t-- == 0) server = (HttpServer) s.next(); else s.next(); if (tokens == 1) { // Server stop/start if (start) server.start(); else server.stop(); } else if (tokens == 3) { // Listener stop/start String l = tok.nextToken() + ":" + tok.nextToken(); HttpListener[] listeners = server.getListeners(); for (int i2 = 0; i2 < listeners.length; i2++) { HttpListener listener = listeners[i2]; if (listener.toString().indexOf(l) >= 0) { if (start) listener.start(); else listener.stop(); } } } else { String host = tok.nextToken(); if ("null".equals(host)) host = null; String contextPath = tok.nextToken(); target += ":" + host + ":" + contextPath; if (contextPath.length() > 1) contextPath += "/*"; int contextIndex = Integer.parseInt(tok.nextToken()); target += ":" + contextIndex; HttpContext context = server.getContext(host, contextPath, contextIndex); if (tokens == 4) { // Context stop/start if (start) context.start(); else context.stop(); } else if (tokens == 5) { // Handler stop/start int handlerIndex = Integer.parseInt(tok.nextToken()); HttpHandler handler = context.getHandlers()[handlerIndex]; if (start) handler.start(); else handler.stop(); } } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } catch (Error e) { log.warn(LogSupport.EXCEPTION, e); } return target; }