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:org.apache.felix.http.itest.BaseIntegrationTest.java

protected static String slurpAsString(InputStream is) throws IOException {
    // See <weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html>
    Scanner scanner = new Scanner(is, "UTF-8");
    try {/*from w ww . j  a va 2s  .c o  m*/
        scanner.useDelimiter("\\A");

        return scanner.hasNext() ? scanner.next() : null;
    } finally {
        try {
            scanner.close();
        } catch (Exception e) {
            // Ignore...
        }
    }
}

From source file:com.ibm.iotf.sample.devicemgmt.device.RasPiFirmwareHandlerSample.java

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

From source file:com.amazonaws.services.dynamodbv2.online.index.ViolationDetector.java

private static boolean getUseConditionalUpdateOptionFromConsole() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Do you want to use conditional update? y/n ");
    String op = scanner.nextLine().trim();
    if (op.equalsIgnoreCase("n")) {
        logger.info("User decided to NOT use conditional update. Will use normal update.");
        scanner.close();
        return false;
    } else if (op.equalsIgnoreCase("y")) {
        logger.info("User decided to use conditional update.");
        scanner.close();/*  w  ww. j  ava 2 s .co m*/
        return true;
    } else {
        logger.error("Invalid entry by the user. Will exit.");
        System.out.println("Please type in y/n, exiting...");
        scanner.close();
        System.exit(0);
    }
    return false;
}

From source file:Main.java

public static Map<String, List<String>> createDictionary(Context context) {
    try {//from  www . j  a v a  2  s  .c o m
        AssetManager am = context.getAssets();
        InputStream is = am.open(DICTIONARY_FILENAME);
        Scanner reader = new Scanner(is);
        Map<String, List<String>> map = new HashMap<String, List<String>>();

        while (reader.hasNextLine()) {
            String word = reader.nextLine();
            char[] keyArr = word.toCharArray();
            Arrays.sort(keyArr);
            String key = String.copyValueOf(keyArr);

            List<String> wordList = map.get(key);
            if (wordList == null) {
                wordList = new LinkedList<String>();
            }
            wordList.add(word);
            map.put(key, wordList);
        }
        reader.close();
        return map;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return null;
}

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

/**
 * Load a Map containing the YAML configurations at that path.
 * /*from w w  w .ja  va2  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:org.arasthel.almeribus.utils.LoadFromWeb.java

public static int cargarParadasLinea(Context context, int numeroLinea) {
    if (!isConnectionEnabled(context)) {
        return SIN_CONEXION;
    }//from   w  w w.j a  v a 2 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:longism.com.api.APIUtils.java

/**
 * TODO Function:Upload file then Load json by type POST.<br>
 *
 * @param activity    - to get context/*from   ww  w  . j  a  v  a2s .  co m*/
 * @param action      - need authenticate or not, define at top of class
 * @param data        - parameter String
 * @param files       - param file input <key,path of file>
 * @param url         - host of API
 * @param apiCallBack - call back to handle action when start, finish, success or fail
 * @date: July 07, 2015
 * @author: Nguyen Long
 */
public static void loadJSONWithUploadFile(final Activity activity, final int action,
        final HashMap<String, String> data, final HashMap<String, String> files, final String url,
        final String sUserName, final String sUserPassword, final APICallBack apiCallBack) {

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            apiCallBack.uiStart();
        }
    });
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME);
                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME);
                Charset chars = Charset.forName("UTF-8");
                DefaultHttpClient client = new DefaultHttpClient(params);
                HttpPost post = new HttpPost(url);
                //               DLog.e("Accountant", "url  : " + url);
                MultipartEntity multipartEntity = new MultipartEntity();
                if (files != null) {
                    Set<String> set = files.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        File file = new File(files.get(key));
                        multipartEntity.addPart(key, new FileBody(file));
                    }
                }
                if (data != null) {
                    Set<String> set = data.keySet();
                    for (String key : set) {
                        //                     DLog.e("Accountant", "param  : " + key);
                        StringBody stringBody = new StringBody(data.get(key), chars);
                        multipartEntity.addPart(key, stringBody);
                    }

                }
                post.setEntity(multipartEntity);
                /**
                 * if need authen then run this code below
                 */
                if (action == ACTION_UPLOAD_WITH_AUTH) {
                    setAuthenticate(client, post, sUserName, sUserPassword);
                }

                HttpResponse response = null;
                response = client.execute(post);
                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:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static String readFileAsString(File f) {

    StringBuilder stringBuilder = new StringBuilder();
    Scanner scanner = null;
    try {/*from   ww w  . j  av a 2 s. c  o  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.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:longism.com.api.APIUtils.java

/**
 * TODO Function:Load json by type.<br>
 *
 * @param activity    - to get context/*from  w  ww  . j  av a  2 s .  com*/
 * @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();
}