Example usage for java.util Scanner close

List of usage examples for java.util Scanner close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes this scanner.

Usage

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http(String s) throws SQLException, IOException {

    String resp = "";
    final URL url = new URL(s);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setReadTimeout(60000);/*from  w ww. j  av a  2  s.c o m*/
    connection.addRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
    connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
    while (reader.hasNextLine()) {
        final String line = reader.nextLine();
        resp += line + "\n";
    }
    reader.close();

    return resp;
}

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;//from   www  . j av a 2s .com

    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:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String resp = "";
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(s);
    method.getParams().setContentCharset("utf-8");

    client.getParams().setParameter("api-key", "58ef39e0-b91a-11e6-a057-97f4c970893c");
    client.getParams().setParameter("Content-Type", "application/json");

    //Add any parameter if u want to send it with Post req.
    for (Entry<String, String> mcc : mp.entrySet()) {
        method.addParameter(mcc.getKey(), mcc.getValue());
    }/* ww w  .j a  v a  2 s  . c o  m*/

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();
        final Scanner reader = new Scanner(in, "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

    }

    return resp;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.crfsuite.task.CRFSuiteTestTask.java

private static String captureProcessOutput(Process aProcess) {
    InputStream src = aProcess.getInputStream();
    Scanner sc = new Scanner(src);
    StringBuilder dest = new StringBuilder();
    while (sc.hasNextLine()) {
        String l = sc.nextLine();
        dest.append(l + "\n");
    }//from w  w w.  j  a  v a2  s . c om
    sc.close();
    return dest.toString();
}

From source file:com.ibm.sbt.sample.web.util.SnippetFactory.java

private static String httpGet(String url) {
    try {//  w w  w .  j av a  2 s.  c om
        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:org.arasthel.almeribus.utils.LoadFromWeb.java

private static int loadCookie() throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://m.surbus.com/tiempo-espera");
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        return ERROR_IO;
    }//from w w w.  ja  v a  2s .c om

    Scanner scan = new Scanner(entity.getContent());
    StringBuilder strBuilder = new StringBuilder();
    while (scan.hasNextLine()) {
        strBuilder.append(scan.nextLine());
    }
    scan.close();
    if (!strBuilder.toString().contains("id=\"blockResult\" class=\"messageResult\"")) {
        return MANTENIMIENTO;
    }

    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    for (Cookie c : cookies) {
        if (c.getName().contains("ASP.NET_SessionId")) {
            cookie = c.getValue();
        }
    }
    return TODO_OK;
}

From source file:info.varden.anatychia.Main.java

public static String getTextFromJarPath(String path) {
    try {/*from   www. j ava 2s . c om*/
        InputStream input = Main.class.getResourceAsStream(path);
        Scanner s = new Scanner(input, "UTF-8").useDelimiter("\\A");
        String str = s.hasNext() ? s.next() : "Error: Failed to read file " + path;
        s.close();
        input.close();
        return str;
    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        return "Error: Failed to read file " + path;
    }
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Convert stream to string.//from w  w w.  j a v a  2s  .co  m
 * 
 * @param is
 * @return
 */
public static String convertStreamToString(java.io.InputStream is) {
    Scanner scanner = null;
    try {
        scanner = new Scanner(is);
        scanner.useDelimiter("\\A");
        String content = scanner.next();
        scanner.close();
        return content;
    } catch (java.util.NoSuchElementException e) {
        return "";
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:org.springframework.hateoas.alps.JacksonSerializationTests.java

private static String read(Resource resource) throws IOException {

    Scanner scanner = null;

    try {//from   www  . j a  v  a  2  s .  c  o  m

        scanner = new Scanner(resource.getInputStream());
        StringBuilder builder = new StringBuilder();

        while (scanner.hasNextLine()) {

            builder.append(scanner.nextLine());

            if (scanner.hasNextLine()) {
                builder.append("\n");
            }
        }

        return builder.toString();

    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}

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/* w ww. j  a v  a  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);
}