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:com.wandrell.example.swss.client.console.ConsoleClient.java

/**
 * Waits until the 'enter' key is pressed.
 *
 * @param output/* w  w  w . j a  va 2s  . c o m*/
 *            output where the information will be printed
 * @param scanner
 *            scanner for reading the input
 */
private static final void waitForEnter(final PrintStream output, final Scanner scanner) {

    output.println();
    // The scanner is cleaned to remove any new line
    if (scanner.hasNextLine()) {
        scanner.nextLine();
    }

    output.println("Press Enter to continue.");
    scanner.nextLine();
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static int cargarParadasLinea(Context context, int numeroLinea) {
    if (!isConnectionEnabled(context)) {
        return SIN_CONEXION;
    }//  w w  w  .j  a v  a2 s. c om
    try {
        if (cookie == null) {
            if (loadCookie() == MANTENIMIENTO) {
                return MANTENIMIENTO;
            }
        }
        URL url = new URL(QUERY_ADDRESS_PARADAS_LINEA + numeroLinea);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        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.connect();
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        JSONObject json = new JSONObject(strBuilder.toString());
        Log.d("Almeribus", strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        if (isSuccessful) {
            DataStorage.DBHelper.eliminarParadasLinea(numeroLinea);
            Linea l = new Linea(numeroLinea);
            JSONArray list = json.getJSONArray("list");
            Parada primeraParada = null;
            Parada paradaAnterior = null;
            for (int i = 0; i < list.length(); i++) {
                JSONObject paradaJSON = list.getJSONObject(i);
                int numeroParada = paradaJSON.getInt("IdBusStop");
                String nombreParada = paradaJSON.getString("Name");
                Parada p = null;
                if (DataStorage.paradas.containsKey(numeroParada)) {
                    p = DataStorage.paradas.get(numeroParada);
                    p.setNombre(nombreParada);
                } else {
                    p = new Parada(numeroParada, nombreParada);
                }
                synchronized (DataStorage.DBHelper) {
                    DataStorage.DBHelper.addInfoParada(numeroParada, nombreParada);
                }
                p.addLinea(l.getNumero());
                if (paradaAnterior != null) {
                    p.setAnterior(paradaAnterior.getId(), numeroLinea);
                }

                if (i == 0) {
                    primeraParada = p;
                } else if (i == list.length() - 1) {
                    primeraParada.setAnterior(p.getId(), numeroLinea);
                    p.setSiguiente(primeraParada.getId(), numeroLinea);
                }

                if (paradaAnterior != null) {
                    paradaAnterior.setSiguiente(p.getId(), numeroLinea);
                }

                paradaAnterior = p;
                synchronized (DataStorage.paradas) {
                    if (DataStorage.paradas.containsKey(numeroParada)) {
                        DataStorage.paradas.remove(numeroParada);
                    }
                    DataStorage.paradas.put(numeroParada, p);
                }

                l.addParada(p);
            }
            DataStorage.lineas.put(numeroLinea, l);
            for (Parada parada : l.getParadas()) {
                synchronized (DataStorage.DBHelper) {
                    try {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea,
                                parada.getSiguiente(numeroLinea));
                    } catch (ParadaNotFoundException e) {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, 0);
                    }
                }
            }
            return TODO_OK;
        } else {
            return ERROR_IO;
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        return ERROR_IO;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ERROR_IO;
}

From source file:configurator.Configurator.java

/**
 * Method for transform ip text to list of ip addresses. Check recording
 * method and select the method of conversion.
 *
 * @param ipText List of ip ranges, subnets and single ip
 * @return list of ip addresses// ww w.j  a  v a 2  s  .c  o m
 */
static List<String> parseIp(String ipText) {
    Scanner ipReader = new Scanner(ipText);
    List<String> ipList = new ArrayList<>();
    String ipLine;
    while (ipReader.hasNext()) {
        ipLine = ipReader.nextLine().trim();
        if (ipLine.contains("/")) {
            ipList.addAll(parseIpSubnet(ipLine));
        } else if (ipLine.contains("-")) {
            ipList.addAll(parseIpRange(ipLine));
        } else if (validateIP(ipLine)) {
            ipList.add(ipLine);
        } else {
            throw new NumberFormatException();
        }
    }
    return ipList;
}

From source file:com.crowsofwar.gorecore.config.ConfigLoader.java

/**
 * Load a Map containing the YAML configurations at that path.
 * /* w  w  w . j a va  2 s . c o m*/
 * @param path
 *            Path starting at ".minecraft/config/"
 * 
 * @throws ConfigurationException
 *             when an error occurs while trying to read the file
 */
private static Map<String, Object> loadMap(String path) {

    try {

        String contents = "";

        File file = new File("config/" + path);
        file.getParentFile().mkdirs();
        file.createNewFile();

        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine())
            contents += scanner.nextLine() + "\n";
        scanner.close();

        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map) yaml.load(contents);

        return map == null ? new HashMap<>() : map;

    } catch (IOException e) {
        throw new ConfigurationException.LoadingException(
                "Exception trying to load config file at " + new File("config/" + path).getAbsolutePath(), e);
    } catch (ClassCastException e) {

        System.out.println("ConfigLoader- warning: File at " + path + " was not a map; ignored contents.");
        return new HashMap<>();

    } catch (ScannerException e) {

        throw new ConfigurationException.LoadingException("Malformed YAML file at config/" + path, e);

    } catch (Exception e) {

        // TODO use a logger
        System.err.println("Error while loading config at 'config/" + path + "':");
        throw e;

    }

}

From source file:PostTest.java

/**
 * Makes a POST request and returns the server response.
 * @param urlString the URL to post to/*from w w  w  .  j a  va 2s.  c om*/
 * @param nameValuePairs a map of name/value pairs to supply in the request.
 * @return the server reply (either from the input stream or the error stream)
 */
public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
        if (first)
            first = false;
        else
            out.print('&');
        String name = pair.getKey();
        String value = pair.getValue();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
        in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
        if (!(connection instanceof HttpURLConnection))
            throw e;
        InputStream err = ((HttpURLConnection) connection).getErrorStream();
        if (err == null)
            throw e;
        in = new Scanner(err);
    }

    while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
    }

    in.close();
    return response.toString();
}

From source file:org.envirocar.app.util.Util.java

public static CharSequence consumeInputStream(InputStream in) throws IOException {
    Scanner sc = new Scanner(in, "UTF-8");

    StringBuilder sb = new StringBuilder();
    String sep = System.getProperty("line.separator");
    while (sc.hasNext()) {
        sb.append(sc.nextLine());//  w w  w  . j  av a2s  .  c  o m
        sb.append(sep);
    }
    sc.close();

    return sb;
}

From source file:net.dv8tion.jda.player.Playlist.java

public static Playlist getPlaylist(String url) {
    List<String> infoArgs = new LinkedList<>();
    infoArgs.addAll(YOUTUBE_DL_PLAYLIST_ARGS);
    infoArgs.add("--"); //Url separator. Deals with YT ids that start with --
    infoArgs.add(url);//  ww w  .j av a2 s.c  om

    //Fire up Youtube-dl and get all sources from the provided url.
    List<AudioSource> sources = new ArrayList<>();
    Scanner scan = null;
    try {
        Process infoProcess = new ProcessBuilder().command(infoArgs).start();
        byte[] infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false);
        if (infoData == null || infoData.length == 0)
            throw new NullPointerException(
                    "The YT-DL playlist process resulted in a null or zero-length INFO!");

        String sInfo = new String(infoData);
        scan = new Scanner(sInfo);

        JSONObject source = new JSONObject(scan.nextLine());
        if (source.has("_type"))//Is a playlist
        {
            sources.add(new RemoteSource(source.getString("url")));
            while (scan.hasNextLine()) {
                source = new JSONObject(scan.nextLine());
                sources.add(new RemoteSource(source.getString("url")));
            }
        } else //Single source link
        {
            sources.add(new RemoteSource(source.getString("webpage_url")));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }

    //Now that we have all the sources we can create our Playlist object.
    Playlist playlist = new Playlist("New Playlist");
    playlist.sources = sources;
    return playlist;
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }/*from ww w.j  a  v a 2s .c  o  m*/

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {//  w  w  w .  j  a v a 2  s.  c  om

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:com.mycompany.songbitmaven.RecommendationController.java

public static SongDataSet trackLookup(String text) {
    Api api = Api.DEFAULT_API;/*from   w  w w . ja  va  2 s . com*/
    final TrackSearchRequest request = api.searchTracks(text).market("US").build();

    try {
        final Page<com.wrapper.spotify.models.Track> trackSearchResult = request.get();
        String jsonURL = trackSearchResult.getNext();

        URL myurl = null;
        try {
            myurl = new URL(jsonURL);
        } catch (Exception e) {
            System.out.println("Improper URL " + jsonURL);
            return null;
        }

        // read from the URL
        Scanner scan = null;
        try {
            scan = new Scanner(myurl.openStream());
        } catch (Exception e) {
            System.out.println("Could not connect to " + jsonURL);
            return null;
        }

        String str = new String();
        while (scan.hasNext()) {
            str += scan.nextLine() + "\n";
        }
        scan.close();

        Gson gson = new Gson();

        System.out.println(jsonURL);
        SongDataSet dataset = gson.fromJson(str, SongDataSet.class);

        return dataset;
    } catch (Exception e) {
        System.out.println("Something went wrong!" + e.getMessage());
        return null;
    }
}