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:org.arasthel.almeribus.utils.LoadFromWeb.java

public static ResultTiempo calcularTiempo(Context context, int parada, int linea) {
    ResultTiempo result = new ResultTiempo();
    if (!isConnectionEnabled(context)) {
        Log.d("AlmeriBus", "No hay conexin");
        result.setTiempo(ERROR_IO);/* ww w  .  j a  va2  s . c  o m*/
    }
    try {
        loadCookie();
        URL url = new URL(QUERY_ADDRESS_TIEMPO_PARADA + linea + "/" + parada + "/" + "3B5579C8FFD6");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera/");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        Log.d("Almeribus", strBuilder.toString());
        JSONObject json = new JSONObject(strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        int type = json.getInt("waitTimeType");
        if (isSuccessful && type > 0) {
            int time = json.getInt("waitTime");
            if (time == Integer.MAX_VALUE) {
                time = NO_DATOS;
            }
            if (time <= 0) {
                time = 0;
            }
            result.setTiempo(time);
            result.setTiempoTexto(json.getString("waitTimeString"));
        } else {
            result.setTiempo(NO_DATOS);
        }
    } catch (Exception e) {
        Log.d("Almeribus", e.toString());
        result.setTiempo(ERROR_IO);
        return result;
    }
    return result;
}

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

/**
 * TODO Function:Load json by type.<br>
 *
 * @param activity    - to get context/*from   ww  w .  j a  va 2s  .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.evolveum.midpoint.util.MiscUtil.java

public static List<String> splitLines(String string) {
    List<String> lines = new ArrayList<String>();
    Scanner scanner = new Scanner(string);
    while (scanner.hasNextLine()) {
        lines.add(scanner.nextLine());
    }//from  ww  w .ja v  a 2 s .  co m
    return lines;
}

From source file:com.ibm.iotf.sample.client.gateway.devicemgmt.GatewayFirmwareHandlerSample.java

private static InstalStatus ParseInstallLog() throws FileNotFoundException {
    try {/* w ww.  j  av a2 s.  c  o  m*/
        File file = new File(INSTALL_LOG_FILE);
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(DEPENDENCY_ERROR_MSG)) {
                scanner.close();
                return InstalStatus.DEPENDENCY_ERROR;
            } else if (line.contains(ERROR_MSG)) {
                scanner.close();
                return InstalStatus.ERROR;
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        throw e;
    }
    return InstalStatus.SUCCESS;
}

From source file:br.upf.contatos.tcp.Client.java

public static boolean comando(String line, ClientConnector tcpService) {

    if (line.equals("help")) {
        System.out.println("op=[ listar, incluir, editar, deletar, parar, cidade ], label = valor");
        System.out.println("Para sair digite: parar");

        return true;

    } else {/*from  w ww .  ja v a2 s .c  o m*/

        tcpService.connect();
        String[] chamadas = line.split(",");
        String[] op = chamadas[0].split("=");

        switch (op[1]) {
        case "listar":

            for (ContatoBean cb : tcpService.getAll()) {
                //System.out.println(new JSONObject(cb));
                System.out.println("ID:" + cb.getId());
                System.out.println("Nome:" + cb.getNome());
                System.out.println("Email:" + cb.getEmail());
                System.out.println("Endereco:" + cb.getEndereco());
                System.out.println("Comp:" + cb.getComplemento());
                System.out.println("CEP:" + cb.getCep());
                System.out.println("Cidade:" + cb.getCidade());
                System.out.println("Estado:" + cb.getEstado());
                System.out.println("Email Alt.:" + cb.getEmailAlternativo());
                System.out.println("------------");
            }

            break;

        case "id":
            String idList;
            Scanner scan2 = new Scanner(System.in);
            System.out.println("Informe o id do contato  listar:");
            idList = scan2.nextLine();
            int numIdList = Integer.parseInt(idList);
            ContatoBean conbean = new ContatoBean();
            conbean.setId(numIdList);

            try {
                conbean = tcpService.getById(numIdList);
                System.out.println("O contato buscado : ");
                System.out.println(new JSONObject(conbean));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "incluir":
            String id;
            String nome;
            String email;
            String end;
            String comp;
            String cep;
            String cid;
            String est;

            Scanner scan = new Scanner(System.in);
            //System.out.printf("Digite o id:");   
            //id = scan.nextLine();                     *** Pegar ID Informado
            System.out.printf("Digite o nome:");
            nome = scan.nextLine();
            System.out.printf("Digite o email:");
            email = scan.nextLine();
            System.out.printf("Digite o endereco:");
            end = scan.nextLine();
            System.out.printf("Digite o complemento:");
            comp = scan.nextLine();
            System.out.printf("Digite o cep:");
            cep = scan.nextLine();
            System.out.printf("Digite a cidade:");
            cid = scan.nextLine();
            System.out.printf("Digite o estado:");
            est = scan.nextLine();

            ContatoBean c = new ContatoBean();
            int numCep = Integer.parseInt(cep);
            int numId = 0; // ***  ID Sequencial automatico
            //int idsec = Integer.parseInt(id); *** Pegar ID Informado
            c.setId(numId); //  ***  ID Sequencial automatico
            //c.setId(idsec);                   *** Pegar ID Informado
            c.setNome(nome);
            c.setEmail(email);
            c.setEndereco(end);
            c.setComplemento(comp);
            c.setCep(numCep);
            c.setCidade(cid);
            c.setEstado(est);
            try {
                c = tcpService.insert(c);
                System.out.println("O contato foi adicionado com Sucesso! Segue abaixo as campos informados: ");
                System.out.println(new JSONObject(c));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "editar":

            while (true) {
                String resp;
                String nummId;
                Scanner sca = new Scanner(System.in);
                System.out.println("Deseja alterar um contato? responda sim ou no");
                resp = sca.nextLine();
                if (resp.equals("sim")) {

                    System.out.println("Informe o id do contato  editar");
                    nummId = sca.nextLine();

                    ContatoBean contB = new ContatoBean();
                    int numIdEdi = Integer.parseInt(nummId);

                    do {
                        String opEditar;

                        System.out.print(
                                "Escolha os atributos  alterar (nome, email, endereco, complemento, cep, cidade, estado, parar): ");
                        opEditar = sca.nextLine();

                        if (opEditar.equals("parar")) {
                            break;
                        } else {
                            String id2 = null;
                            String nome2 = null;
                            String email2 = null;
                            String end2 = null;
                            String comp2 = null;
                            String cep2 = null;
                            String cid2 = null;
                            String est2;
                            ContatoBean contact = new ContatoBean();

                            try {
                                contact = tcpService.getById(numIdEdi);
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                                break;
                            }

                            switch (opEditar) {

                            case "nome":
                                System.out.printf("Digite o nome:");
                                nome2 = sca.nextLine();
                                contact.setNome(nome2);
                                break;
                            case "email":
                                System.out.printf("Digite o email:");
                                email2 = sca.nextLine();
                                contact.setEmail(email2);
                                break;
                            case "endereco":
                                System.out.printf("Digite o endereco:");
                                end2 = sca.nextLine();
                                contact.setEndereco(end2);
                                break;
                            case "complemento":
                                System.out.printf("Digite o complemento:");
                                comp2 = sca.nextLine();
                                contact.setComplemento(comp2);
                                break;
                            case "cep":
                                System.out.printf("Digite o cep:");
                                cep2 = sca.nextLine();
                                int numCepEdit = Integer.parseInt(cep2);
                                contact.setCep(numCepEdit);
                                break;
                            case "cidade":
                                System.out.printf("Digite o cidade:");
                                cid2 = sca.nextLine();
                                contact.setCidade(cid2);
                                break;
                            case "estado":
                                System.out.printf("Digite o estado:");
                                est2 = sca.nextLine();
                                contact.setEstado(est2);
                                break;

                            }

                            try {
                                contact = tcpService.update(contact);
                                System.out.println(
                                        "O contato foi alterado! Segue abaixo suas informaes atualizadas: ");
                                System.out.println(new JSONObject(contact));
                            } catch (RuntimeException e) {
                                System.out.println(e.getMessage());
                            }
                        }
                    } while (true);

                } else {
                    break;
                }

            }
            break;
        case "cidade":
            String cidade;
            ArrayList cidade2 = new ArrayList();
            Scanner scanner = new Scanner(System.in);
            System.out.println("Informe a cidade  listar");
            cidade = scanner.nextLine();

            try {
                cidade2 = (ArrayList) tcpService.getByCidade(cidade);
                // System.out.println(new JSONObject(cidade2));
                System.out.println("Segue os contatos que moram na cidade de " + cidade + ":");
                for (Object cb : cidade2) {
                    System.out.println(new JSONObject(cb));
                }
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "deletar":
            String idDel;
            Scanner scann = new Scanner(System.in);
            System.out.println("Informe o id do contato  deletar");
            idDel = scann.next();
            int numIdDel = Integer.parseInt(idDel);
            ContatoBean cb = new ContatoBean();
            cb.setId(numIdDel);
            try {
                cb = tcpService.delete(numIdDel);
                System.out.println("O contato com o id" + numIdDel + " foi deletado!");
                System.out.println(new JSONObject(cb));
            } catch (RuntimeException e) {
                System.out.println(e.getMessage());
            }

            break;

        case "parar":

            System.out.println("Encerrando Aplicao...");
            return false;
        }

    }

    return true;
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static String readFileAsString(File f) {

    StringBuilder stringBuilder = new StringBuilder();
    Scanner scanner = null;
    try {/* w  ww  . j av a2s . co m*/
        scanner = new Scanner(f);
    } catch (FileNotFoundException e) {
        return null;
    }

    try {
        while (scanner.hasNextLine()) {
            stringBuilder.append(scanner.nextLine() + "\n");
        }
    } finally {
        scanner.close();
    }
    return stringBuilder.toString();
}

From source file:com.all.login.services.LoginDatabaseAccess.java

private static LoginDatabase loadDatabase(File file) {
    LoginDatabase db = null;//from  ww w .ja v  a  2 s. c  o  m
    if (file.exists()) {
        Scanner scanner = null;
        try {
            StringBuilder text = new StringBuilder();
            String NL = System.getProperty("line.separator");
            scanner = new Scanner(new FileInputStream(file));
            while (scanner.hasNextLine()) {
                text.append(scanner.nextLine() + NL);
            }
            db = JsonConverter.toBean(text.toString(), LoginDatabase.class);
        } catch (Exception e) {
            LOG.error("Could not deserialize LoginDatabase.", e);
        } finally {
            try {
                scanner.close();
            } catch (Exception e) {
                LOG.error(e, e);
            }
        }
    }
    if (db == null) {
        db = new LoginDatabase();
    }
    return db;
}

From source file:nbayes_mr.NBAYES_MR.java

public static void test(String fname) {
    try {//from w w w.j  a v a2 s  .c  om
        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();
    }

}

From source file:com.ibm.iotf.sample.client.gateway.devicemgmt.GatewayFirmwareHandlerSample.java

public static String getInstallLog(String fileName) throws FileNotFoundException {
    File file = new File(fileName);
    Scanner scanner = new Scanner(file);
    StringBuilder sb = new StringBuilder();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        sb.append(line);//from   w ww .  jav  a 2s . c o  m
        sb.append('\n');
    }
    scanner.close();
    return sb.toString();
}

From source file:com.aurel.track.dbase.UpdateDbSchema.java

/**
 * Run an SQL script/*w w w  .  java  2s  .c  o  m*/
 * @param script
 */
@SuppressWarnings("resource")
private static void runSQLScript(String script, int maxValue, String progressText) {
    String folderName = getDbScriptFolder();
    int line = 0;
    int noOfLines = 0;
    int progress = 0;
    Connection cono = null;
    try {
        long start = new Date().getTime();
        cono = InitDatabase.getConnection();
        cono.setAutoCommit(false);
        Statement ostmt = cono.createStatement();
        script = "/dbase/" + folderName + "/" + script;
        URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(script);
        InputStream in = populateURL.openStream();
        java.util.Scanner s = new java.util.Scanner(in, "UTF-8").useDelimiter(";");
        while (s.hasNext()) {
            ++noOfLines;
            s.nextLine();
        }
        int mod = noOfLines / maxValue;
        in.close();
        in = populateURL.openStream();
        s = new java.util.Scanner(in, "UTF-8").useDelimiter(";");
        String st = null;
        StringBuilder stb = new StringBuilder();

        int modc = 0;
        progress = Math.round(new Float(mod) / new Float(noOfLines) * maxValue);

        LOGGER.info("Running SQL script " + script);
        while (s.hasNext()) {
            stb.append(s.nextLine().trim());
            st = stb.toString();
            ++line;
            ++modc;
            if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*") && !st.startsWith("#")) {
                if (st.trim().equalsIgnoreCase("go")) {
                    try {
                        cono.commit();
                    } catch (Exception ex) {
                        LOGGER.error(ExceptionUtils.getStackTrace(ex));
                    }
                    stb = new StringBuilder();
                } else {
                    if (st.endsWith(";")) {
                        stb = new StringBuilder(); // clear buffer
                        st = st.substring(0, st.length() - 1); // remove the semicolon
                        try {
                            if ("commit".equals(st.trim().toLowerCase())
                                    || "go".equals(st.trim().toLowerCase())) {
                                cono.commit();
                            } else {
                                ostmt.executeUpdate(st);
                                if (mod > 4 && modc >= mod) {
                                    modc = 0;
                                    ApplicationStarter.getInstance().actualizePercentComplete(progress,
                                            progressText);
                                }
                            }
                        } catch (Exception exc) {
                            if (!("Derby".equals(folderName) && exc.getMessage().contains("DROP TABLE")
                                    && exc.getMessage().contains("not exist"))) {
                                LOGGER.error("Problem executing DDL statements: " + exc.getMessage());
                                LOGGER.error("Line " + line + ": " + st);
                            }
                        }
                    } else {
                        stb.append(" ");
                    }
                }
            } else {
                stb = new StringBuilder();
            }
        }
        in.close();
        cono.commit();
        cono.setAutoCommit(true);

        long now = new Date().getTime();
        LOGGER.info("Database schema creation took " + (now - start) / 1000 + " seconds.");

    } catch (Exception e) {
        LOGGER.error("Problem upgrading database schema in line " + line + " of file " + script, e);
    } finally {
        try {
            if (cono != null) {
                cono.close();
            }
        } catch (Exception e) {
            LOGGER.info("Closing the connection failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}