List of usage examples for java.util Scanner hasNext
public boolean hasNext()
From source file:com.rockhoppertech.music.DurationParser.java
public static List<Double> getDurationsAsList(String durations) { String token = null;/*from ww w . ja v a 2 s . c o m*/ List<Double> list = new ArrayList<Double>(); Scanner scanner = new Scanner(durations); if (durations.indexOf(',') != -1) { scanner.useDelimiter(","); } while (scanner.hasNext()) { if (scanner.hasNext(dpattern)) { token = scanner.next(dpattern); double d = getDottedValue(token); list.add(d); logger.debug("'{}' is dotted value is {}", token, d); } else if (scanner.hasNext(pattern)) { token = scanner.next(pattern); double d = durKeyMap.get(token); list.add(d); logger.debug("'{}' is not dotted value is {}", token, d); // } else if (scanner.hasNext(tripletPattern)) { // token = scanner.next(tripletPattern); // double d = durKeyMap.get(token); // ts.add(d); // System.out.println(String // .format("'%s' is not dotted value is %f", // token, // d)); } else if (scanner.hasNextDouble()) { double d = scanner.nextDouble(); list.add(d); logger.debug("{} is a double", d); } else { // just ignore it. or throw exception? String skipped = scanner.next(); logger.debug("skipped '{}'", skipped); } } scanner.close(); return list; }
From source file:org.apache.felix.http.itest.BaseIntegrationTest.java
protected static String slurpAsString(InputStream is) throws IOException { // See <weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html> Scanner scanner = new Scanner(is, "UTF-8"); try {/*from w ww. j av a 2 s .com*/ scanner.useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : null; } finally { try { scanner.close(); } catch (Exception e) { // Ignore... } } }
From source file:org.isource.util.CSVUtils.java
public static List<List> readCsv(String csvFile) { List<List> lines = new ArrayList<List>(); try {// w w w . ja v a 2s.c o m if (getFileExtension(csvFile).equalsIgnoreCase("csv")) { Scanner scanner = new Scanner(new File(csvFile)); while (scanner.hasNext()) { List<String> line = parseLine(scanner.nextLine()); lines.add(line); } scanner.close(); } else if (getFileExtension(csvFile).equalsIgnoreCase("xls")) { lines = readXls(csvFile); } } catch (FileNotFoundException ex) { Logger.getLogger(CSVUtils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CSVUtils.class.getName()).log(Level.SEVERE, null, ex); } return lines; }
From source file:com.aurel.track.dbase.UpdateDbSchema.java
/** * Run an SQL script/*from w w w .java 2 s . co m*/ * @param script */ @SuppressWarnings("resource") private static void runSQLScript(String script, int maxValue, String progressText) { String folderName = getDbScriptFolder(); int line = 0; int noOfLines = 0; int progress = 0; Connection cono = null; try { long start = new Date().getTime(); cono = InitDatabase.getConnection(); cono.setAutoCommit(false); Statement ostmt = cono.createStatement(); script = "/dbase/" + folderName + "/" + script; URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(script); InputStream in = populateURL.openStream(); java.util.Scanner s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); while (s.hasNext()) { ++noOfLines; s.nextLine(); } int mod = noOfLines / maxValue; in.close(); in = populateURL.openStream(); s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); String st = null; StringBuilder stb = new StringBuilder(); int modc = 0; progress = Math.round(new Float(mod) / new Float(noOfLines) * maxValue); LOGGER.info("Running SQL script " + script); while (s.hasNext()) { stb.append(s.nextLine().trim()); st = stb.toString(); ++line; ++modc; if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*") && !st.startsWith("#")) { if (st.trim().equalsIgnoreCase("go")) { try { cono.commit(); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } stb = new StringBuilder(); } else { if (st.endsWith(";")) { stb = new StringBuilder(); // clear buffer st = st.substring(0, st.length() - 1); // remove the semicolon try { if ("commit".equals(st.trim().toLowerCase()) || "go".equals(st.trim().toLowerCase())) { cono.commit(); } else { ostmt.executeUpdate(st); if (mod > 4 && modc >= mod) { modc = 0; ApplicationStarter.getInstance().actualizePercentComplete(progress, progressText); } } } catch (Exception exc) { if (!("Derby".equals(folderName) && exc.getMessage().contains("DROP TABLE") && exc.getMessage().contains("not exist"))) { LOGGER.error("Problem executing DDL statements: " + exc.getMessage()); LOGGER.error("Line " + line + ": " + st); } } } else { stb.append(" "); } } } else { stb = new StringBuilder(); } } in.close(); cono.commit(); cono.setAutoCommit(true); long now = new Date().getTime(); LOGGER.info("Database schema creation took " + (now - start) / 1000 + " seconds."); } catch (Exception e) { LOGGER.error("Problem upgrading database schema in line " + line + " of file " + script, e); } finally { try { if (cono != null) { cono.close(); } } catch (Exception e) { LOGGER.info("Closing the connection failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:com.android.idtt.http.client.util.URLEncodedUtils.java
/** * Adds all parameters within the Scanner to the list of * <code>parameters</code>, as encoded by <code>encoding</code>. For * example, a scanner containing the string <code>a=1&b=2&c=3</code> would * add the {@link org.apache.http.NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters.// w w w . j a va 2 s. c om * * @param parameters List to add parameters to. * @param scanner Input that contains the parameters to parse. * @param charset Encoding to use when decoding the parameters. */ public static void parse(final List<NameValuePair> parameters, final Scanner scanner, final String charset) { scanner.useDelimiter(PARAMETER_SEPARATOR); while (scanner.hasNext()) { String name = null; String value = null; String token = scanner.next(); int i = token.indexOf(NAME_VALUE_SEPARATOR); if (i != -1) { name = decodeFormFields(token.substring(0, i).trim(), charset); value = decodeFormFields(token.substring(i + 1).trim(), charset); } else { name = decodeFormFields(token.trim(), charset); } parameters.add(new BasicNameValuePair(name, value)); } }
From source file:com.hybris.mobile.model.product.Product.java
/** * This method parses the messages sent from OCC to create HTML with links recognised by the app. Note this code is * brittle and relies on very specific formatting in OCC. This method is specifoc to product promotions. * //ww w .j ava 2 s .c o m * @param p * The product * @return the HTML string to place as the promotions text */ public static String generatePromotionString(ProductPromotion productPromotion) { String promotionsString = productPromotion.getDescription(); /* * firedMessages trumps description */ if (productPromotion.getFiredMessages() != null && !productPromotion.getFiredMessages().isEmpty()) { promotionsString = productPromotion.getFiredMessages().get(0); promotionsString.replaceAll("<br>", "\n"); } /* * couldFireMessage trumps firedMessage */ if (productPromotion.getCouldFireMessages() != null && !productPromotion.getCouldFireMessages().isEmpty()) { promotionsString = productPromotion.getCouldFireMessages().get(0); promotionsString.replaceAll("<br>", "\n"); } /* * Builds links in the form http://m.hybris.com/123456 N.B. iOS builds links in the form appName://product/123456 * with the title as the product name */ ArrayList<String> links = new ArrayList<String>(); ArrayList<String> codes = new ArrayList<String>(); ArrayList<String> productNames = new ArrayList<String>(); Pattern codePattern = Pattern.compile("[0-9]{6,7}"); Scanner s1 = new Scanner(promotionsString); s1.useDelimiter("<a href="); while (s1.hasNext()) { String str = s1.next(); if (str.startsWith("$config")) { Scanner s2 = new Scanner(str); s2.useDelimiter("</a>"); String link = s2.next(); links.add(link); } } for (String link : links) { Scanner s3 = new Scanner(link); s3.useDelimiter("<b>"); s3.next(); while (s3.hasNext()) { String str = s3.next(); if (!str.startsWith("$")) { Scanner s4 = new Scanner(str); s4.useDelimiter("</b>"); String name = s4.next(); productNames.add(name); } } // Find the codes Matcher m = codePattern.matcher(link); while (m.find()) { String s = m.group(); codes.add(s); } } // Build the new links int position = 0; for (String link : links) { promotionsString = promotionsString.replace(link, String.format("\"http://m.hybris.com/%s\">%s", codes.get(position), productNames.get(position))); position++; } return promotionsString; }
From source file:com.groupon.odo.HttpUtilities.java
/** * Obtain collection of Parameters from request * * @param httpServletRequest/*w w w . j a v a2 s.c o m*/ * @return * @throws Exception */ public static Map<String, String[]> mapUrlEncodedParameters(HttpServletRequest httpServletRequest) throws Exception { InputStream body = httpServletRequest.getInputStream(); java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); Map<String, String[]> mapPostParameters = new HashMap<String, String[]>(); try { if (s.hasNext()) { String requestData = s.next(); String[] splitRequestData = requestData.split("&"); for (String requestPart : splitRequestData) { String[] parts = requestPart.split("="); ArrayList<String> values = new ArrayList<String>(); if (mapPostParameters.containsKey(parts[0])) { values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(parts[0]))); mapPostParameters.remove(parts[0]); } if (parts.length > 1) { values.add(parts[1]); } mapPostParameters.put(parts[0], values.toArray(new String[values.size()])); } } } catch (Exception e) { throw new Exception("Could not parse request data: " + e.getMessage()); } return mapPostParameters; }
From source file:configurator.Configurator.java
/** * Method for transform ip text to list of ip addresses. Check recording * method and select the method of conversion. * * @param ipText List of ip ranges, subnets and single ip * @return list of ip addresses// ww w .jav a2 s . com */ static List<String> parseIp(String ipText) { Scanner ipReader = new Scanner(ipText); List<String> ipList = new ArrayList<>(); String ipLine; while (ipReader.hasNext()) { ipLine = ipReader.nextLine().trim(); if (ipLine.contains("/")) { ipList.addAll(parseIpSubnet(ipLine)); } else if (ipLine.contains("-")) { ipList.addAll(parseIpRange(ipLine)); } else if (validateIP(ipLine)) { ipList.add(ipLine); } else { throw new NumberFormatException(); } } return ipList; }
From source file:org.envirocar.app.util.Util.java
public static CharSequence consumeInputStream(InputStream in) throws IOException { Scanner sc = new Scanner(in, "UTF-8"); StringBuilder sb = new StringBuilder(); String sep = System.getProperty("line.separator"); while (sc.hasNext()) { sb.append(sc.nextLine());// w ww . ja v a 2 s.c o m sb.append(sep); } sc.close(); return sb; }
From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java
/** * Adds all parameters within the Scanner to the list of * <code>parameters</code>, as encoded by <code>encoding</code>. For * example, a scanner containing the string <code>a=1&b=2&c=3</code> would * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters./*from ww w .ja v a 2 s . c o m*/ * * @param parameters * List to add parameters to. * @param scanner * Input that contains the parameters to parse. * @param charset * Encoding to use when decoding the parameters. */ public static void parse(final List<NameValuePair> parameters, final Scanner scanner, final String charset) { scanner.useDelimiter(PARAMETER_SEPARATOR); while (scanner.hasNext()) { String name = null; String value = null; String token = scanner.next(); int i = token.indexOf(NAME_VALUE_SEPARATOR); if (i != -1) { name = decodeFormFields(token.substring(0, i).trim(), charset); value = decodeFormFields(token.substring(i + 1).trim(), charset); } else name = decodeFormFields(token.trim(), charset); parameters.add(new BasicNameValuePair(name, value)); } }