Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

In this page you can find the example usage for java.util Scanner hasNext.

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Read home.json from Server/* w  w  w .  ja  v a  2s.c o m*/
 * 
 * @param URL
 * @return
 * @throws IOException
 *             , MalformedURLException, JSONException
 */
public void getHomeStatus() throws IOException, MalformedURLException, JSONException {
    // Set URL
    // Connect to Intel Galileo get Device Status
    HttpURLConnection httpCon = (HttpURLConnection) homeJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readStream = httpCon.getInputStream();
    Scanner scan = new Scanner(readStream).useDelimiter("\\A");
    // Set stream to String
    String jsonFile = scan.hasNext() ? scan.next() : "";
    // Initialize serveFile as read string
    homeInfo = new JSONObject(jsonFile);
    httpCon.disconnect();
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

private String fileToString(String fileName) throws FileNotFoundException {
    FileInputStream fileStream = new FileInputStream(new File(fileName));
    java.util.Scanner scanner = new java.util.Scanner(fileStream).useDelimiter("\\A");
    String inputAsString = scanner.hasNext() ? scanner.next() : "";
    return inputAsString.replaceAll("[\uFEFF-\uFFFF]", "");
}

From source file:com.android.ddmuilib.log.event.DisplaySync.java

/**
 * Generates the tooltips text for an event.
 * This method decodes the cryptic details string.
 * @param auth The authority associated with the event
 * @param details The details string/*  w ww. java2  s .c  o m*/
 * @param eventSource server, poll, etc.
 * @return The text to display in the tooltips
 */
private String getTextFromDetails(int auth, String details, int eventSource) {

    StringBuffer sb = new StringBuffer();
    sb.append(AUTH_NAMES[auth]).append(": \n");

    Scanner scanner = new Scanner(details);
    Pattern charPat = Pattern.compile("[a-zA-Z]");
    Pattern numPat = Pattern.compile("[0-9]+");
    while (scanner.hasNext()) {
        String key = scanner.findInLine(charPat);
        int val = Integer.parseInt(scanner.findInLine(numPat));
        if (auth == GMAIL && "M".equals(key)) {
            sb.append("messages from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "L".equals(key)) {
            sb.append("labels from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "C".equals(key)) {
            sb.append("check conversation requests from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "A".equals(key)) {
            sb.append("attachments from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "U".equals(key)) {
            sb.append("op updates from server: ").append(val).append("\n");
        } else if (auth == GMAIL && "u".equals(key)) {
            sb.append("op updates to server: ").append(val).append("\n");
        } else if (auth == GMAIL && "S".equals(key)) {
            sb.append("send/receive cycles: ").append(val).append("\n");
        } else if ("Q".equals(key)) {
            sb.append("queries to server: ").append(val).append("\n");
        } else if ("E".equals(key)) {
            sb.append("entries from server: ").append(val).append("\n");
        } else if ("u".equals(key)) {
            sb.append("updates from client: ").append(val).append("\n");
        } else if ("i".equals(key)) {
            sb.append("inserts from client: ").append(val).append("\n");
        } else if ("d".equals(key)) {
            sb.append("deletes from client: ").append(val).append("\n");
        } else if ("f".equals(key)) {
            sb.append("full sync requested\n");
        } else if ("r".equals(key)) {
            sb.append("partial sync unavailable\n");
        } else if ("X".equals(key)) {
            sb.append("hard error\n");
        } else if ("e".equals(key)) {
            sb.append("number of parse exceptions: ").append(val).append("\n");
        } else if ("c".equals(key)) {
            sb.append("number of conflicts: ").append(val).append("\n");
        } else if ("a".equals(key)) {
            sb.append("number of auth exceptions: ").append(val).append("\n");
        } else if ("D".equals(key)) {
            sb.append("too many deletions\n");
        } else if ("R".equals(key)) {
            sb.append("too many retries: ").append(val).append("\n");
        } else if ("b".equals(key)) {
            sb.append("database error\n");
        } else if ("x".equals(key)) {
            sb.append("soft error\n");
        } else if ("l".equals(key)) {
            sb.append("sync already in progress\n");
        } else if ("I".equals(key)) {
            sb.append("io exception\n");
        } else if (auth == CONTACTS && "g".equals(key)) {
            sb.append("aggregation query: ").append(val).append("\n");
        } else if (auth == CONTACTS && "G".equals(key)) {
            sb.append("aggregation merge: ").append(val).append("\n");
        } else if (auth == CONTACTS && "n".equals(key)) {
            sb.append("num entries: ").append(val).append("\n");
        } else if (auth == CONTACTS && "p".equals(key)) {
            sb.append("photos uploaded from server: ").append(val).append("\n");
        } else if (auth == CONTACTS && "P".equals(key)) {
            sb.append("photos downloaded from server: ").append(val).append("\n");
        } else if (auth == CALENDAR && "F".equals(key)) {
            sb.append("server refresh\n");
        } else if (auth == CALENDAR && "s".equals(key)) {
            sb.append("server diffs fetched\n");
        } else {
            sb.append(key).append("=").append(val);
        }
    }
    if (eventSource == 0) {
        sb.append("(server)");
    } else if (eventSource == 1) {
        sb.append("(local)");
    } else if (eventSource == 2) {
        sb.append("(poll)");
    } else if (eventSource == 3) {
        sb.append("(user)");
    }
    return sb.toString();
}

From source file:au.org.ala.layers.web.IntersectService.java

@RequestMapping(value = WS_INTERSECT_BATCH, method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody// ww  w.  j  a  v  a 2 s.  c  o  m
public Map batch(@RequestParam(value = "fids", required = false, defaultValue = "") String fids,
        @RequestParam(value = "points", required = false, defaultValue = "") String pointsString,
        @RequestParam(value = "gridcache", required = false, defaultValue = "0") String gridcache,
        HttpServletRequest request, HttpServletResponse response) {

    BatchConsumer.start(layerIntersectDao, userProperties.getProperty("batch_path"));

    //help get params when they don't pick up automatically from a POST
    try {
        if ("POST".equalsIgnoreCase(request.getMethod()) && fids.isEmpty() && pointsString.isEmpty()) {
            Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
            String body = s.hasNext() ? s.next() : "";

            for (String param : body.split("&")) {
                if (param.startsWith("fids=")) {
                    fids = param.substring(5);
                } else if (param.startsWith("points=")) {
                    pointsString = param.substring(7);
                }
            }
        }
    } catch (Exception e) {
        logger.error("failed to read POST body for: " + WS_INTERSECT_BATCH, e);
    }

    if (pointsString == null || pointsString.isEmpty()) {
        return null;
    }

    Map map = new HashMap();
    String batchId = null;
    try {

        // get limits
        int pointsLimit, fieldsLimit;

        String[] passwords = userProperties.getProperty("batch_sampling_passwords").split(",");
        pointsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_points_limit"));
        fieldsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_fields_limit"));

        String password = request.getParameter("pw");
        for (int i = 0; password != null && i < passwords.length; i++) {
            if (passwords[i].equals(password)) {
                pointsLimit = Integer.MAX_VALUE;
                fieldsLimit = Integer.MAX_VALUE;
            }
        }

        // count fields
        int countFields = 1;
        int p = 0;
        while ((p = fids.indexOf(',', p + 1)) > 0)
            countFields++;

        // count points
        int countPoints = 1;
        p = 0;
        while ((p = pointsString.indexOf(',', p + 1)) > 0)
            countPoints++;

        if (countPoints / 2 > pointsLimit) {
            map.put("error", "Too many points.  Maximum is " + pointsLimit);
        } else if (countFields > fieldsLimit) {
            map.put("error", "Too many fields.  Maximum is " + fieldsLimit);
        } else {
            batchId = BatchProducer.produceBatch(userProperties.getProperty("batch_path"),
                    "request address:" + request.getRemoteAddr(), fids, pointsString, gridcache);

            map.put("batchId", batchId);
            BatchProducer.addInfoToMap(userProperties.getProperty("batch_path"), batchId, map);
            map.put("statusUrl", userProperties.getProperty("layers_service_url")
                    + WS_INTERSECT_BATCH_STATUS.replace("{id}", batchId));
        }

        return map;
    } catch (Exception e) {
        e.printStackTrace();
    }

    map.put("error", "failed to create new batch");
    return map;
}

From source file:com.std.Index.java

public void find_historical_data(int month, int day, int year) {
    try {/*from  www. java  2s. c o  m*/
        String url = "http://real-chart.finance.yahoo.com/table.csv?s=" + this.ticker + "&d=" + month + "&e="
                + day + "&f=" + year + "&g=d&a=0&b=1&c=1970&ignore=.csv";
        InputStream input;
        input = new URL(url).openStream();
        Scanner s = new Scanner(input);
        s.useDelimiter("\\A");
        String csv = s.hasNext() ? s.next() : "";
        s.close();
        input.close();
        csv = csv.replace("\"", "");
        historical_data = new ArrayList<String>(Arrays.asList(csv.split("\n")));
    } catch (Exception ex) {
        System.out.println("Could not retrieve historical data");
        System.out.println("Error with connection");

    }
}

From source file:org.diyefi.openlogviewer.propertypanel.PropertiesPane.java

private void loadProperties() {
    try {// w  w  w . j a va 2 s  .  co m
        final Scanner scan = new Scanner(new FileReader(OLVProperties));

        while (scan.hasNext()) {
            final String[] propLine = scan.nextLine().split("=");
            final SingleProperty sp = new SingleProperty();
            final String[] prop = propLine[1].split(",");
            sp.setHeader(propLine[0]);
            sp.setColor(
                    new Color(Integer.parseInt(prop[0]), Integer.parseInt(prop[1]), Integer.parseInt(prop[2])));
            sp.setMin(Double.parseDouble(prop[3]));
            sp.setMax(Double.parseDouble(prop[4]));
            sp.setTrackIndex(Integer.parseInt(prop[5]));
            sp.setActive(Boolean.parseBoolean(prop[6]));
            addProperty(sp);
        }

        scan.close();
    } catch (FileNotFoundException fnf) {
        System.out.print(fnf.toString());
        throw new RuntimeException(fnf);
    }
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Get Command List JSON File From Server
 * /* w  ww  .j a  v a  2  s .  com*/
 * @throws IOException
 * @throws MalformedURLException
 * @throws JSONException
 */
public void getCommandsList() throws IOException, MalformedURLException, JSONException {
    // Connect to Intel Galileo get Commands List
    HttpURLConnection httpCon = (HttpURLConnection) commandsJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readCommand = httpCon.getInputStream();
    Scanner scanCommand = new Scanner(readCommand).useDelimiter("\\A");
    // Set stream to String
    String commandFile = scanCommand.hasNext() ? scanCommand.next() : "";
    // Initialize serveFile as read string
    JSONObject commandsList = new JSONObject(commandFile);
    JSONObject temp = (JSONObject) commandsList.get("commands");
    JSONArray comArray = (JSONArray) temp.getJSONArray("command");
    int numberOfCommands = comArray.length();
    commands = new String[numberOfCommands];
    // Fill the Array
    for (int i = 0; i < numberOfCommands; i++) {
        JSONObject commandObject = (JSONObject) comArray.get(i);
        commands[i] = commandObject.getString("text");
    }
    Log.d("JSON", "Loaded " + commands[2]);
    httpCon.disconnect();
}

From source file:org.collectionspace.chain.csp.schema.Record.java

private static String getURLTail(String url) {
    String result = null;//w w  w .  j av a 2 s.co  m

    Scanner scanner = null;
    try {
        scanner = new Scanner(url).useDelimiter("\\/+");
        while (scanner.hasNext() == true) {
            result = scanner.next();
        }
    } catch (Exception e) {
        // Ignore the exception or logger.trace(e);
    } finally {
        scanner.close();
    }

    return result;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Long[] subsetLongVector(InputStream in, int column, int numCases) {
    Long[] retVector = new Long[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            try {
                retVector[caseIndex] = new Long(line[column]);
            } catch (NumberFormatException ex) {
                retVector[caseIndex] = null; // assume missing value
            }/*from w w w.j a  v a  2 s. c o m*/
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:hmp.HMPClassiferSummary.java

private ReadContainer getReads(File file) throws FileNotFoundException {
    String readFileName = cli.getOptionValue("sourceDir") + File.separator
            + file.getName().replace(fileSuffix, "");
    File readFile = new File(readFileName);
    System.out.println("Getting reads from " + readFile.getName() + " size=" + readFile.length() + " bytes");
    ReadContainer container = new ReadContainer();

    Scanner scan = new Scanner(readFile);
    String line = null;//  ww w  .  ja  v a  2  s . co  m
    Read read = null;
    while (scan.hasNext()) {
        line = scan.nextLine();
        if (!line.isEmpty()) {
            if (line.startsWith(">")) {
                read = new Read(line, readDelimiter, String.valueOf(readIdIndex));
                container.addRead(read);
            } else {
                read.addSequence(line);
            }
        }
    }
    System.out.println("Read " + readFile.getName() + " reads=" + container.getNumberOfReads());
    return container;
}