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:br.cefetrj.sagitarii.nunki.comm.WebClient.java

private String convertStreamToString(java.io.InputStreamReader is) {
    java.util.Scanner s = new java.util.Scanner(is);
    s.useDelimiter("\\A");
    String retorno = s.hasNext() ? s.next() : "";
    s.close();// ww  w.j  a v  a2  s. c  om
    return retorno;
}

From source file:mase.evorbc.KdTreeRepertoire.java

private Map<Integer, double[]> fileCoordinates(File file) {
    Map<Integer, double[]> res = new HashMap<>();
    try {/*from   ww  w. j a  va  2s  .c om*/
        Scanner sc = new Scanner(file);
        while (sc.hasNext()) {
            String line = sc.nextLine();
            String[] split = line.trim().split(" ");
            int index = Integer.parseInt(split[0]);
            double[] coords = new double[split.length - 1];
            for (int i = 0; i < coords.length; i++) {
                coords[i] = Double.parseDouble(split[i + 1]);
            }
            res.put(index, coords);
        }
        return res;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ArbitratorFactory.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * check if dirname matches configuration hidden folder regex.
 *
 * @param dirName dir name//from w w w  .j  a  v a 2s  .  c o  m
 * @param conf connector configuration
 * @return true if matches.
 */
public static boolean checkIfDirIsHidden(final String dirName, final IConfiguration conf) {
    if (dirName == null || dirName.equals("")) {
        return false;
    }
    String dir = PathUtils.removeSlashFromEnd(PathUtils.escape(dirName));
    Scanner sc = new Scanner(dir).useDelimiter("/");
    while (sc.hasNext()) {
        boolean check = Pattern.compile(getHiddenFileOrFolderRegex(conf.getHiddenFolders())).matcher(sc.next())
                .matches();
        if (check) {
            return true;
        }
    }
    return false;
}

From source file:slina.mb.utils.LogFileReaderImpl.java

/**
 * readFileTest is faster/*from  ww  w . j  a  v a 2s.  com*/
 * @param fileName
 * @return
 * @throws IOException
 */
public List<String> readnio(String fileName) throws IOException {

    List<String> lines = new ArrayList<String>();
    long before = System.currentTimeMillis();

    Scanner scanner = new Scanner(new FileReader(fileName));

    while (scanner.hasNext()) {
        lines.add(scanner.next());
    }

    long after = System.currentTimeMillis();
    System.out.println("nio run took " + (after - before) + " ms");
    return lines;

}

From source file:org.openmrs.module.eidinterface.web.controller.PatientStatusController.java

@ResponseBody
@RequestMapping(value = "module/eidinterface/getPatientStatus", method = RequestMethod.POST)
public String getPatientStatus(HttpServletResponse response, @RequestBody String identifiers)
        throws IOException {

    StringWriter sw = new StringWriter();
    CSVWriter csv = new CSVWriter(sw);

    String[] header = { "Identifier", "Status", "CCC Number" };
    csv.writeNext(header);/*from w ww .  j  a v  a  2 s  . c  o m*/

    StringReader sr = new StringReader(identifiers);
    Scanner s = new Scanner(sr);

    // iterate through identifiers
    while (s.hasNext()) {

        String identifier = s.next().trim();

        String status;
        String ccc = "";

        String[] parts = identifier.split("-");
        String validIdentifier = new LuhnIdentifierValidator().getValidIdentifier(parts[0]);

        if (!OpenmrsUtil.nullSafeEquals(identifier, validIdentifier)) {
            status = "INVALID IDENTIFIER";
        } else {
            List<Patient> patients = Context.getPatientService().getPatients(null, identifier, null, true);
            if (patients != null && patients.size() == 1) {
                Patient p = patients.get(0);
                PatientIdentifier pi = p.getPatientIdentifier(CCC_NUMBER_PATIENT_IDENTIFIER_ID);
                if (pi != null) {
                    status = "ENROLLED";
                    ccc = pi.getIdentifier();
                } else {
                    status = "NOT ENROLLED";
                }
            } else if (patients != null && patients.size() > 1) {
                status = "MULTIPLE FOUND";
            } else {
                status = "NOT FOUND";
            }
        }

        csv.writeNext(new String[] { identifier, status, ccc });
    }

    // flush the string writer
    sw.flush();

    // set the information
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    // respond with it
    return sw.toString();
}

From source file:com.neu.bigdata.service.PredictionService.java

public String setJSON(String fileName) {

    try {/*from   w  w  w.ja v a 2s.  c o m*/

        File apiFile = new File(fileName);
        Scanner sc = new Scanner(apiFile);
        while (sc.hasNext()) {
            jsonBody += sc.nextLine() + "\n";
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        return jsonBody;
    }

}

From source file:opennlp.tools.parse_thicket.apps.MostFrequentWordsFromPageGetter.java

public List<String> getMostFrequentWordsInText(String input) {
    int maxRes = 4;
    Scanner in = new Scanner(input);
    in.useDelimiter("\\s+");
    Map<String, Integer> words = new HashMap<String, Integer>();

    while (in.hasNext()) {
        String word = in.next();//from ww w .  jav  a2s  . co  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);
        }
    }

    words = ValueSortMap.sortMapByValue(words, false);
    List<String> results = new ArrayList<String>(words.keySet());

    if (results.size() > maxRes)
        results = results.subList(0, maxRes); // get maxRes elements

    return results;
}

From source file:fr.itldev.koya.services.impl.util.AlfrescoRestErrorHandler.java

@Override
public void handleError(ClientHttpResponse clienthttpresponse) throws IOException {

    if (!statusOK.contains(clienthttpresponse.getStatusCode())) {
        AlfrescoServiceException ex;/*www .  ja  v  a2  s  . c o m*/
        if (clienthttpresponse.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
            java.util.Scanner s = new java.util.Scanner(clienthttpresponse.getBody()).useDelimiter("\\A");
            String message = s.hasNext() ? s.next() : "";

            /*
             Try to get any Koya Error code if exists
             */
            Integer koyaErrorCode = null;

            Matcher matcher = ERRORCODEPATTERN.matcher(message);
            if (matcher.find()) {
                koyaErrorCode = Integer.valueOf(matcher.group(1));
            }

            ex = new AlfrescoServiceException(
                    "Erreur " + clienthttpresponse.getStatusCode() + " : " + clienthttpresponse.getStatusText(),
                    koyaErrorCode);
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());
        } else if (clienthttpresponse.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            ex = new AlfrescoServiceException("Acces Denied");
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());

        } else {
            ex = new AlfrescoServiceException();
            ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value());
            throw ex;
        }
        throw ex;

    }
}

From source file:org.openvoters.android.tasks.RemoteAPIGetListTask.java

@Override
protected JSONObject doInBackground(RemoteAPIGetListCallback... params) {
    if (params.length > 0) {
        callback = params[0];/*from   w ww .  ja v a  2s  .c o m*/
    }

    JSONObject result = null;
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance("");

    try {
        HttpGet request = new HttpGet(String.format("%s/%s", RemoteAPI.getBaseURL(), "getlist"));
        HttpResponse response = httpClient.execute(request);

        InputStream input = response.getEntity().getContent();
        java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A");
        String responseString = s.hasNext() ? s.next() : "";

        JSONObject obj = new JSONObject(responseString);
        httpClient.close();
        result = obj;
    } catch (Exception e) {
        httpClient.close();
        taskError = true;
        exc = e;
        return null;
    }

    httpClient.close();

    elabora(result);
    return result;
}

From source file:games.livestreams.providers.Twitch.java

@Override
public String[] getStreams(String tag) {
    final ArrayList<String> streams = new ArrayList<String>();
    String apiUrl = String.format(ExtensionObject.Configuration.get("twitch.link"),
            Integer.parseInt(ExtensionObject.Configuration.get("streams.limit")), tag);

    try {/* ww  w. j a  v  a 2 s . c om*/
        //            apiUrl = URLEncoder.encode(apiUrl, "UTF-8");
        URL url = new URL(apiUrl);

        Scanner scan = new Scanner(url.openStream());
        String jsonAnswer = "";
        while (scan.hasNext())
            jsonAnswer += scan.nextLine();
        scan.close();

        JSONObject jsonObject = new JSONObject(jsonAnswer);
        JSONArray jsonArray = jsonObject.getJSONArray("streams");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject streamObject = jsonArray.getJSONObject(i);

            String streamName = streamObject.getJSONObject("channel").getString("display_name");
            String streamStatus = "online";
            String streamUrl = streamObject.getJSONObject("channel").getString("url");
            String streamViewers = streamObject.getString("viewers");

            streamName = IrcMessageTextModifier.makeBold(streamName);
            streamViewers = IrcMessageTextModifier.makeColoured(IrcMessageTextModifier.makeBold(streamViewers),
                    IrcTextColor.Brown);

            String realStatus = streamObject.getJSONObject("channel").getString("status");

            if (realStatus != null && !realStatus.trim().isEmpty()) {
                streamStatus = realStatus;
            }

            String formattedStreamInfoOutput = String.format("[%s] (%s) %s (%s viewers)", streamName,
                    streamStatus, streamUrl, streamViewers);

            streams.add(formattedStreamInfoOutput);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    if (!streams.isEmpty()) {
        String[] streamsArray = new String[] {};

        return streams.toArray(streamsArray);
    } else {
        throw new ProviderError(String.format("No streams found on \"%s\" service with tag \"%s\"",
                this.getProviderName(), tag));
    }
}