List of usage examples for java.util Scanner next
public String next()
From source file:controllers.IndexServlet.java
private static void Track(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) { String userAddress = request.getParameter("userAddress"); String fileName = request.getParameter("fileName"); String storagePath = DocumentManager.StoragePath(fileName, userAddress); String body = ""; try {//from w w w.ja v a 2 s . c o m Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A"); body = scanner.hasNext() ? scanner.next() : ""; } catch (Exception ex) { writer.write("get request.getInputStream error:" + ex.getMessage()); return; } if (body.isEmpty()) { writer.write("empty request.getInputStream"); return; } JSONParser parser = new JSONParser(); JSONObject jsonObj; try { Object obj = parser.parse(body); jsonObj = (JSONObject) obj; } catch (Exception ex) { writer.write("JSONParser.parse error:" + ex.getMessage()); return; } long status = (long) jsonObj.get("status"); if (status == 2 || status == 3)//MustSave, Corrupted { String downloadUri = (String) jsonObj.get("url"); int saved = 1; try { URL url = new URL(downloadUri); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); InputStream stream = connection.getInputStream(); if (stream == null) { throw new Exception("Stream is null"); } File savedFile = new File(storagePath); try (FileOutputStream out = new FileOutputStream(savedFile)) { int read; final byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } connection.disconnect(); } catch (Exception ex) { saved = 0; } } writer.write("{\"error\":0}"); }
From source file:IO.java
public static double[][] readDoubleMat(File file, int row, int col) { double[][] data = new double[row][col]; try {/*from w ww . j ava 2 s . c o m*/ Scanner sc = new Scanner(file); sc.useDelimiter(",|\\n"); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) { data[i][j] = Double.parseDouble(sc.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } return data; }
From source file:it.mb.whatshare.SendToGCMActivity.java
/** * Loads the ID and name of the paired device in use to share content when * Whatsapp is not installed on this device. * /*www . jav a 2 s. c o m*/ * @param activity * the calling activity * @return the device loaded from file if any is configured, * <code>null</code> otherwise * @throws OptionalDataException * @throws ClassNotFoundException * @throws IOException */ static Pair<PairedDevice, String> loadOutboundPairing(Context activity) throws OptionalDataException, ClassNotFoundException, IOException { FileInputStream fis = activity.openFileInput("pairing"); Scanner scanner = new Scanner(fis).useDelimiter("\\Z"); JSONObject json; try { json = new JSONObject(scanner.next()); String name = json.getString("name"); String type = json.getString("type"); String assignedID = json.getString("assignedID"); return new Pair<PairedDevice, String>(new PairedDevice(assignedID, name, type), assignedID); } catch (JSONException e) { e.printStackTrace(); } return null; }
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;//from www .j ava 2s .c o m try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }
From source file:org.wso2.carbon.la.core.utils.LogPatternExtractor.java
public static Map<String, String> processDelimiter(String logLine, String delimiter) { String value = null;//from ww w. j a v a2 s . c o m String delemiterConf = null; Map<String, String> logEvent = new HashMap<>(); switch (delimiter) { case "space": delemiterConf = LAConstants.DELIMITER_SPACE; break; case "comma": delemiterConf = LAConstants.DELIMITER_COMMA; break; case "pipe": delemiterConf = LAConstants.DELIMITER_PIPE; break; case "tab": delemiterConf = LAConstants.DELIMITER_TAB; break; default: delemiterConf = delimiter; break; } // Initialize Scanner object Scanner scan = new Scanner(logLine.trim()); // initialize the string delimiter scan.useDelimiter(delemiterConf.trim()); int fieldIndex = 0; while (scan.hasNext()) { String fieldName = "field" + fieldIndex; logEvent.put(fieldName, scan.next()); fieldIndex++; } // closing the scanner stream scan.close(); return logEvent; }
From source file:IO.java
public static double[] readDoubleVec(File file, int nDim) { Scanner sc; double[] wavelength = new double[nDim]; try {/*from w w w .ja v a 2 s. c om*/ sc = new Scanner(file); sc.useDelimiter(",|\\n"); for (int i = 0; i < nDim; i++) { wavelength[i] = Double.parseDouble(sc.next()); //System.out.print(wavelength[i]+"\t"); } } catch (FileNotFoundException e) { System.out.println("Wavelength file not found\n" + e); System.exit(0); } return wavelength; }
From source file:ch.ethz.inf.vs.hypermedia.client.Utils.java
public static <T extends Enum<T>> T selectFromEnum(Class<T> enumType, Scanner scanner, String prompt) { T[] consts = enumType.getEnumConstants(); String options = Stream.of(consts).map(x -> x.ordinal() + ": " + x).collect(Collectors.joining(", ")); int index = -1; do {// w w w . j ava2s. c o m System.out.printf("%s (%s): %n", prompt, options); String val = scanner.next().trim(); try { index = Integer.parseInt(val); } catch (NumberFormatException e) { } } while (!(index >= 0 && index < consts.length)); return consts[index]; }
From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationPassword.java
/** * Static factory method to create an instance from a line from a Properties * file and the Properties object it lives in. * * @param props/* ww w .j a v a 2s . c o m*/ * @param configFileLine * @return */ public static ConfigurationPassword createFromLine(final Properties props, final String configFileLine) { // Parse the password prefix from the given config file line Scanner scanner = null; String prefix = null; try { scanner = new Scanner(configFileLine); scanner.useDelimiter("\\.password="); prefix = scanner.next(); // get prefix } finally { if (scanner != null) { scanner.close(); } } return new ConfigurationPassword(props, prefix); }
From source file:cn.newgxu.android.bbs.util.NewgxuUtils.java
public static final String get(String url, String charset) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Accept", "application/json"); HttpResponse response = null;//w w w. j a v a 2s .c om HttpEntity entity = null; Scanner scanner = null; try { response = client.execute(get); entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream in = entity.getContent(); scanner = new Scanner(in, charset == null ? "utf-8" : charset).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : null; } } catch (ClientProtocolException e) { Log.wtf(TAG, e); } catch (IOException e) { Log.wtf(TAG, e); } finally { try { if (entity != null) { entity.consumeContent(); } } catch (IOException e) { Log.wtf(TAG, e); } } return null; }
From source file:com.sina.cloudstorage.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 NameValuePair NameValuePairs} a=1, b=2, and c=3 to the * list of parameters./*from w ww. j a v a 2 s. com*/ * * @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 = decode(token.substring(0, i).trim(), charset); value = decode(token.substring(i + 1).trim(), charset); } else { name = decode(token.trim(), charset); } parameters.add(new BasicNameValuePair(name, value)); } }