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.siphyc.utils.Utilities.java

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if (!sc.hasNextInt(radix)) {
        return false;
    }/*from w  w w.  jav  a  2 s.c  om*/
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

From source file:no.imr.stox.functions.utils.RUtils.java

public static String callR(String rFolder, String fileName, String cmd) {
    try {/*from  w ww .j  a  va  2 s .  c om*/
        String triggerFile = getTmpDir() + fileName;
        try (PrintWriter pw = new PrintWriter(triggerFile)) {
            pw.println(cmd);
        }
        Process proc = callR(rFolder, triggerFile, false);
        if (proc != null) {
            java.io.InputStream is = proc.getInputStream();
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter(";");
            while (s.hasNext()) {
                String str = s.next();
                return StringUtils.substringBetween(str, "\"", "\"");
            }
        }
    } catch (IOException ex) {
    }
    return "";
}

From source file:com.ibm.sbt.sample.web.util.SnippetFactory.java

private static String httpGet(String url) {
    try {//from w w  w  .j  ava2s  . co  m
        HttpClient httpClient = SSLUtil.wrapHttpClient(new DefaultHttpClient());
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity content = response.getEntity();
            java.util.Scanner scanner = new java.util.Scanner(content.getContent());
            scanner.useDelimiter("\\A");
            String result = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
            return result;
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    }

}

From source file:org.disit.servicemap.ServiceMap.java

static private void loadStopWords() {
    if (stopWords != null)
        return; //already loaded;

    stopWords = new ArrayList<String>();
    String token1 = "";
    try {//from  w ww.  j  av a 2  s .  c  o  m
        // create Scanner
        Scanner scanner = new Scanner(new File(System.getProperty("user.home") + "/servicemap/stop_words.txt"));
        while (scanner.hasNext()) {
            // find next line
            token1 = scanner.next();
            //System.out.println("-"+token1+"-");
            stopWords.add(token1);
        }
        scanner.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Exception: File not found " + ex.toString());
    }
}

From source file:info.varden.anatychia.Main.java

public static String getTextFromJarPath(String path) {
    try {/*ww  w  . j  a v a  2s.co  m*/
        InputStream input = Main.class.getResourceAsStream(path);
        Scanner s = new Scanner(input, "UTF-8").useDelimiter("\\A");
        String str = s.hasNext() ? s.next() : "Error: Failed to read file " + path;
        s.close();
        input.close();
        return str;
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        return "Error: Failed to read file " + path;
    }
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context//from w ww .  j av  a2s  .c  om
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Prints the sample properties file on the default output.
 *//*from   ww  w .j  a va2 s .c o m*/
private static void printSamplePropertiesFile() {

    System.out.println("\n  File: aw-report-sample.properties example");

    ClassPathResource sampleFile = new ClassPathResource("aw-report-sample.properties");
    Scanner fileScanner = null;
    try {
        fileScanner = new Scanner(sampleFile.getInputStream());
        while (fileScanner.hasNext()) {
            System.out.println(fileScanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileScanner != null) {
            fileScanner.close();
        }
    }
}

From source file:longism.com.api.APIUtils.java

/**
 * TODO Function:Load json by type.<br>
 *
 * @param activity    - to get context/*from w w w .j a  v  a2s .  c  o  m*/
 * @param action      - get or post or s.thing else. Define at top of class
 * @param data        - Parameter
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @param username    - username if sever need to log in
 * @param password    - password if sever need to log in
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void LoadJSONByType(final Activity activity, final int action, final HashMap<String, String> data,
        final String url, final String username, final String password, final APICallBack apiCallBack) {
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpGet get = null;
                HttpPost post = null;
                HttpResponse response = null;
                String paramString = null;

                ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        BasicNameValuePair value = new BasicNameValuePair(key, data.get(key));
                        list.add(value);
                    }
                }
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);

                DefaultHttpClient client = new DefaultHttpClient(params);

                /**
                 * Select action to do
                 */
                switch (action) {
                case ACTION_GET_JSON:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    response = client.execute(post);
                    break;
                case ACTION_GET_JSON_WITH_AUTH:
                    paramString = URLEncodedUtils.format(list, "utf-8");
                    get = new HttpGet(url + "?" + paramString);
                    setAuthenticate(client, get, username, password);
                    response = client.execute(get);
                    break;
                case ACTION_POST_JSON_WITH_AUTH:
                    post = new HttpPost(url);
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                    setAuthenticate(client, post, username, password);
                    response = client.execute(post);
                    break;
                }

                final StringBuilder builder = new StringBuilder();
                if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    InputStream inputStream = response.getEntity().getContent();
                    Scanner scanner = new Scanner(inputStream);
                    while (scanner.hasNext()) {
                        builder.append(scanner.nextLine());
                    }
                    inputStream.close();
                    scanner.close();
                    apiCallBack.success(builder.toString(), 0);
                } else {
                    apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null"
                            : "" + response.getStatusLine().getStatusCode());
                }
            } catch (final Exception e) {
                apiCallBack.fail(e.getMessage());
            } finally {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        apiCallBack.uiEnd();
                    }
                });
            }
        }
    }).start();
}

From source file:com.rockhoppertech.music.DurationParser.java

/**
 * Copies new events into the TimeSeries parameter - which is also returned.
 * // w w  w. j  a  v  a2 s  .  c om
 * @param ts
 *            a {@code TimeSeries} that will be added to
 * @param s
 *            a duration string
 * @return the same{@code TimeSeries} that you passed in
 */
public static TimeSeries getDurationAsTimeSeries(TimeSeries ts, String s) {
    String token = null;
    Scanner scanner = new Scanner(s);

    if (s.indexOf(',') != -1) {
        scanner.useDelimiter(",");
    }

    while (scanner.hasNext()) {
        if (scanner.hasNext(dpattern)) {
            token = scanner.next(dpattern);
            double d = getDottedValue(token);
            ts.add(d);
            logger.debug("'{}' is dotted value is {}", token, d);

        } else if (scanner.hasNext(pattern)) {
            token = scanner.next(pattern);
            double d = durKeyMap.get(token);
            ts.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();
            ts.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 ts;
}

From source file:nbayes_mr.NBAYES_MR.java

public static void test(String fname) {
    try {/*from  w ww.  j  a v a2  s. c o m*/
        Scanner s = new Scanner(new File(fname));
        Double probs[] = new Double[probhmap.size()];
        int totallines = 0;
        int positive = 0;
        //System.out.println("class:"+probhmap.size());
        while (s.hasNext()) {
            totallines++;
            String line = s.nextLine();
            String split[] = line.split(",");
            Set<String> classlist = probhmap.keySet();
            Iterator classitr = classlist.iterator();
            int classi = 0;
            double maxprob = -1.0;
            String classassg = "";
            while (classitr.hasNext()) {
                String hi = (String) classitr.next();
                //System.out.println(hi);
                probs[classi] = ((double) probhmap.get(hi) / (double) total);
                for (int i = 0; i < split.length - 1; i++) {
                    int ll = 0, ll1 = 0;
                    if (probhmap.containsKey(hi)) {
                        ll = probhmap.get(hi);
                    }
                    if (probxhmap.containsKey(split[i] + "|" + hi)) {
                        ll1 = probxhmap.get(split[i] + "|" + hi);
                    }

                    //System.out.println(split[i]);

                    if (ll1 != 0) {
                        probs[classi] *= ((double) probxhmap.get(split[i] + "|" + hi)
                                / (double) probhmap.get(hi));
                    } else {
                        probs[classi] = 0.0;
                    }
                }
                if (probs[classi] > maxprob) {
                    maxprob = probs[classi];
                    classassg = hi;
                }
                classi++;
            }
            //System.out.println(line);
            //System.out.println(split.length);

            if (classassg.equalsIgnoreCase(split[10])) {
                positive++;
            }
            //s.next();
        }
        accuracy.add((double) positive / (double) totallines);
        //Integer cnt5=count/5;
        //Scanner sc = new Scanner(new File("/" + fname));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}