Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

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 {//from  w ww  . java  2  s  .  co m
        //            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));
    }
}

From source file:com.mgmtp.perfload.perfalyzer.binning.PerfMonBinningStrategy.java

@Override
public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        tokenizer.reset(line);/* w  w w  . j  av  a  2 s  . co  m*/
        List<String> tokenList = tokenizer.getTokenList();

        if (typeConfig == null) {
            String type = tokenList.get(1);
            typeConfig = PerfMonTypeConfig.fromString(type);
        }

        try {
            long timestampMillis = Long.parseLong(tokenList.get(0));
            Double value = Double.valueOf(tokenList.get(2));
            binManager.addValue(timestampMillis, value);
        } catch (NumberFormatException ex) {
            log.error("Could not parse value {}. Line in perfMon file might be incomplete. Ignoring it.", ex);
        }
    }

    binManager.toCsv(destChannel, "seconds", typeConfig.getHeader(), intNumberFormat,
            typeConfig.getAggregationType());
}

From source file:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request/*w  w  w .  j a  v  a 2  s .  c  om*/
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:com.joliciel.talismane.machineLearning.TextFileWordList.java

public TextFileWordList(File file) {
    try {//from   w  w  w.  ja v a 2  s . c o  m
        this.name = file.getName();

        Scanner scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));
        int i = 1;
        String firstLine = scanner.nextLine();
        if (!firstLine.equals("Type: WordList")) {
            throw new JolicielException("A word list file must start with \"Type: WordList\"");
        }
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.length() > 0 && !line.startsWith("#")) {
                if (line.startsWith("Name: ")) {
                    this.name = line.substring("Name: ".length());
                    i++;
                    continue;
                }
                wordList.add(line);
            }
            i++;
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.joliciel.csvLearner.features.NormalisationLimitReader.java

private void readCSVFile(InputStream csvInputStream, Map<String, Float> featureToMaxMap) {
    Scanner scanner = new Scanner(csvInputStream, "UTF-8");
    try {// w w  w  .j a  v a 2s  .  c o  m
        boolean firstLine = true;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (!firstLine) {
                List<String> cells = CSVFormatter.getCSVCells(line);
                String featureName = cells.get(0);
                float maxValue = Float.parseFloat(cells.get(1));
                featureToMaxMap.put(featureName, maxValue);
            }
            firstLine = false;
        }
    } finally {
        scanner.close();
    }
}

From source file:com.joliciel.talismane.posTagger.PosTagSetImpl.java

void load(Scanner scanner) {
    List<String> descriptors = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        descriptors.add(line);//from  ww w  .  j  a v  a 2  s .  c o  m
    }
    this.load(descriptors);
}

From source file:de.wpsverlinden.dupfind.DupFind.java

private void run() throws IOException {
    outputPrinter.printSplash();//from   w w  w  .java 2  s  .  co  m
    fileIndexer.loadIndex();

    Scanner sc = new Scanner(new InputStreamReader(System.in));
    while (true) {
        System.out.print(fileIndexer.pwd());
        String line = sc.nextLine();
        if ("exit".equals(line)) {
            break;
        }
        String[] words = line.split(" ");

        if ("help".equals(words[0])) {
            outputPrinter.printHelp();
        } else if ("build_index".equals(words[0]) && words.length == 1) {
            buildIndex();

        } else if ("calc_hashes".equals(words[0]) && words.length >= 1 && words.length <= 2) {
            calcHashes();

        } else if ("show_dupes_of".equals(words[0]) && words.length >= 2) {
            showDupesOf(line.substring(words[0].length() + 1).replace("\"", ""));

        } else if ("show_dupes".equals(words[0]) && words.length == 1) {
            showDupes();

        } else if ("num_of_dupes".equals(words[0]) && words.length == 1) {
            numOfDupes();

        } else if ("delete_dupes_of".equals(words[0]) && words.length >= 2) {
            deleteDupesOf(line.substring(words[0].length() + 1).replace("\"", ""));

        } else if ("delete_dupes".equals(words[0]) && words.length == 1) {
            deleteDupes();

        } else {
            outputPrinter.printInvalidCommand(line);
        }
    }
}

From source file:br.com.intelidev.dao.DadosDao.java

public List<Dados> get_stream_data(String stream_api, String user, String pass) {

    HttpsURLConnection conn = null;
    List<Dados> list_return = new ArrayList<>();
    int i;/*from   w ww .j a  va  2 s.co m*/

    try {
        // Create url to the Device Cloud server for a given web service request
        //00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/" + stream_api);
        //URL url = new URL("https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = user + ":" + pass;
        System.out.println(userpassword);

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
        // Convert JSON string to Object
        StreamDados stream = mapper.readValue(responseContent, StreamDados.class);
        //System.out.println(stream.getList());
        System.out.println(stream.getList().size());
        for (i = 0; i < stream.getList().size(); i++) {
            list_return.add(stream.getList().get(i));
            //System.out.println("ts: "+ stream.getList().get(i).getTimestamp() + "Value: " + stream.getList().get(i).getValue());

        }

    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.DadosDao.get_stream_data() e" + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }

    return list_return;
}

From source file:debrepo.teamcity.archive.DebFileReader.java

protected Map<String, String> getDebItemsFromControl(File debFile, String controlFileContents) {
    Pattern p = Pattern.compile("^(\\S+):(.+)$");

    Map<String, String> map = new LinkedHashMap<String, String>();
    Scanner scanner = new Scanner(controlFileContents);

    while (scanner.hasNextLine()) {
        Matcher m = p.matcher(scanner.nextLine());
        if (m.find()) {
            map.put(m.group(1), m.group(2).trim());
        }// w w w  . jav a2s.co  m
    }
    scanner.close();

    map.putAll(getExtraPackageItemsFromDeb(debFile));

    return map;
}

From source file:view.UserInteractor.java

private void tryLoadFile(Scanner in) {
    String input;/* w  w  w. ja  va  2s  .c  o  m*/
    for (int i = 0; i < 10; i++) {
        try {
            System.out.println("Enter filename or '.' for no file: ");
            input = in.nextLine();
            if (input.equals("."))
                break;
            controller.loadFile(input);
            System.out.println("File loaded");
            break;
        } catch (InputMismatchException ex) {
            System.out.println("Invalid format of this file");
        } catch (NoSuchFileException ex) {
            System.out.println("File not found");
        } catch (IOException ex) {
            System.out.println("IO error");
        }
    }

}