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.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.//  w w  w .java 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 = 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));
    }
}

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

@SuppressWarnings("resource")
static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

From source file:com.bb.extensions.plugin.unittests.internal.utilities.FileUtils.java

/**
 * Convert an input stream to a string//from   www.  ja  v a 2s .  co m
 * 
 * @param stream
 *            The input stream
 * @return The string contents of the input stream
 */
public static String toString(java.io.InputStream stream) {
    Scanner s = new Scanner(stream).useDelimiter("\\A"); //$NON-NLS-1$
    return s.hasNext() ? s.next() : ""; //$NON-NLS-1$
}

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 .  j  a  va  2  s.  co  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:com.google.api.ads.adwords.awreporting.server.AwReportingServer.java

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

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

    ClassPathResource sampleFile = new ClassPathResource(DAFAULT_PROPERTIES_LOCATION);
    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:dm_p2.DBSCAN.java

public static void generateLinkedHashMap(String filename) {
    String filePath = new File("").getAbsolutePath();

    try {//from  www.  j  av  a2 s. c om
        Scanner s = new Scanner(new File(filePath + "/src/dm_p2/" + filename));
        while (s.hasNext()) {
            String inputLine = s.nextLine();
            String[] splitData = inputLine.split("\t");
            int geneId = Integer.parseInt(splitData[0]);
            expressionValues = new ArrayList<Double>();
            int cc = Integer.parseInt(splitData[1]);
            given.put(geneId, cc);
            for (int i = 2; i < splitData.length; i++) {

                expressionValues.add(Double.parseDouble(splitData[i]));
            }
            //                gene g=new gene();
            //                g.add(geneId, expressionValues);
            //                genelist.add(g);
            linkedHashMap.put(geneId, expressionValues);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:com.pieframework.model.repository.ModelStore.java

protected static String parse(String query) {
    ComponentQueryBuilder builder = new ComponentQueryBuilder();

    Scanner scanner = new Scanner(query);
    scanner.useDelimiter(PATH_DELIMITER);

    while (scanner.hasNext()) {
        final String[] nameValue = scanner.next().split(NAME_VALUE_DELIMITER);
        if (nameValue.length == 0 || nameValue.length > 2) {
            throw new IllegalArgumentException("Illegal format");
        }/*from  ww w.j a  v a  2s. co  m*/
        builder.add(nameValue[0]);
    }
    return builder.build();
}

From source file:opennlp.tools.doc_classifier.DocClassifier.java

public static String formClassifQuery(String pageContentReader, int maxRes) {

    // We want to control which delimiters we substitute. For example '_' &
    // \n we retain
    pageContentReader = pageContentReader.replaceAll("[^A-Za-z0-9 _\\n]", "");

    Scanner in = new Scanner(pageContentReader);
    in.useDelimiter("\\s+");
    Map<String, Integer> words = new HashMap<String, Integer>();

    while (in.hasNext()) {
        String word = in.next();/*w  w w  .j a v  a  2  s.c o  m*/
        if (!StringUtils.isAlpha(word) || word.length() < 4)
            continue;

        if (!words.containsKey(word)) {
            words.put(word, 1);
        } else {
            words.put(word, words.get(word) + 1);
        }
    }
    in.close();
    words = ValueSortMap.sortMapByValue(words, false);
    List<String> resultsAll = new ArrayList<String>(words.keySet()), results = null;

    int len = resultsAll.size();
    if (len > maxRes)
        results = resultsAll.subList(len - maxRes, len - 1); // get maxRes
    // elements
    else
        results = resultsAll;

    return results.toString().replaceAll("(\\[|\\]|,)", " ").trim();
}

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;/* ww  w. java 2 s. co  m*/
    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:wordGame.Util.WebUtil.java

public static Board GetBoardFromServer(String boardID) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet getMethod = new HttpGet(WEBGETBOARD + boardID);
    Scanner fileScanner = null;
    String boardString = null;/*www  .j  ava 2  s  . c  om*/
    try {
        HttpResponse response = httpclient.execute(getMethod);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            fileScanner = new Scanner(new BufferedReader(new InputStreamReader(responseEntity.getContent())));
            while (fileScanner.hasNext()) {
                boardString = fileScanner.next();
                return BoardGenerator.generateCubesFromWebString(boardString);
            }
        }
    } catch (IOException e) {
        return null;
    }
    return null;

}