Example usage for java.util Scanner useDelimiter

List of usage examples for java.util Scanner useDelimiter

Introduction

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

Prototype

public Scanner useDelimiter(String pattern) 

Source Link

Document

Sets this scanner's delimiting pattern to a pattern constructed from the specified String .

Usage

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();/*from  w w  w  .j av  a2 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:com.networknt.light.server.handler.loader.FormLoader.java

private static void loadFormFile(String host, File file) {
    Scanner scan = null;
    try {//from ww  w .j  av a2 s.c  o  m
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion.
        String content = scan.useDelimiter("\\Z").next();
        // convert to map
        Map<String, Object> newMap = ServiceLocator.getInstance().getMapper().readValue(content,
                new TypeReference<HashMap<String, Object>>() {
                });
        String formId = (String) newMap.get("formId");
        Map<String, Object> oldMap = (Map<String, Object>) formMap.get(formId);
        boolean changed = false;
        if (oldMap == null) {
            // never loaded before.
            changed = true;
        } else {
            if (newMap.get("action") != null && !newMap.get("action").equals(oldMap.get("action"))) {
                changed = true;
            }
            if (!changed && newMap.get("schema") != null
                    && !newMap.get("schema").equals(oldMap.get("schema"))) {
                changed = true;
            }
            if (!changed && newMap.get("form") != null && !newMap.get("form").equals(oldMap.get("form"))) {
                changed = true;
            }
            if (!changed && newMap.get("modelData") != null
                    && !newMap.get("modelData").equals(oldMap.get("modelData"))) {
                changed = true;
            }
        }
        if (changed) {
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "form");
            inputMap.put("name", "impForm");
            inputMap.put("readOnly", false);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Form: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

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");
        }//  w w  w.  j a  va  2  s .  co m
        builder.add(nameValue[0]);
    }
    return builder.build();
}

From source file:export.FormCrawler.java

public static JSONObject parse(InputStream in) throws JSONException {
    final Scanner s = new Scanner(in);
    final JSONObject o = new JSONObject(s.useDelimiter("\\A").next());
    s.close();/*from  ww  w  . ja va2  s.  c om*/
    return o;
}

From source file:export.FormCrawler.java

public static JSONObject parse(Reader in) throws JSONException {
    final Scanner s = new Scanner(in);
    final JSONObject o = new JSONObject(s.useDelimiter("\\A").next());
    s.close();//  w  w w.  j  av  a2 s . co m
    return o;
}

From source file:org.runnerup.export.FormCrawler.java

public static JSONObject parse(String in) throws JSONException {
    final Scanner s = new Scanner(in);
    final JSONObject o = new JSONObject(s.useDelimiter("\\A").next());
    s.close();//from w ww  .  ja  va  2  s  . c  o m
    return o;
}

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;/* w w w  . ja  v  a2 s  .  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:com.ibm.sbt.sample.web.util.SnippetFactory.java

private static String httpGet(String url) {
    try {/* w ww .j a va2 s .  c o  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: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//from   ww  w  .j a  va 2 s.  c  om
 * @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:com.rockhoppertech.music.DurationParser.java

/**
 * Copies new events into the TimeSeries parameter - which is also returned.
 * //w ww . jav  a 2s  . co  m
 * @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;
}