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:com.pinterest.clusterservice.cm.AwsVmManager.java

private Map<String, String> transformUserDataToConfigMap(String clusterName, String userData) throws Exception {
    String userDataString = userData.replace(String.format(AWS_USERDATA_TEMPLATE, clusterName, clusterName),
            "");/*from  ww  w. ja v  a2  s . com*/
    Map<String, String> resultMap = new HashMap<>();
    if (userDataString.length() == 0) {
        return resultMap;
    }

    Scanner scanner = new Scanner(userDataString);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        List<String> config = Arrays.asList(line.split(": "));
        if (config.size() == 2) {
            resultMap.put(config.get(0), config.get(1));
        }
    }
    scanner.close();
    return resultMap;
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Get connections synchronously. //from ww w  .ja  va 2 s . co  m
 * Operation blocks until it is completed.
 * 
 * @param tgServer TG server to get connections from
 * @param tgNetListenerName Name of the net listener for TG Admin to connect to - if null connect to 1st one
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param timeout Number of milliseconds allowed to complete the stop server operation - If lower than 0 wait forever
 * @return Array of session IDs
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String[] getConnections(TGServer tgServer, String tgNetListenerName, String logFile,
        String logLevel, long timeout) throws TGAdminException {

    String output = showConnections(tgServer, tgNetListenerName, logFile, logLevel, timeout);
    Scanner scanner = new Scanner(output);
    boolean counting = false;
    //int indexClientId;
    int indexSessionId = 0;
    int adminConnectionCount = 0;
    List<String> connectionList = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.contains("Client ID")) {
            counting = true;
            //indexClientId = line.indexOf("Client ID");
            indexSessionId = line.indexOf("Session ID");
        } else if (line.contains("----------"))
            counting = false;
        else if (line.contains("connection(s) returned")) {
            counting = false;
            adminConnectionCount = Integer.parseInt(line.substring(0, line.indexOf(' ', 0)));
        } else if (counting) {
            connectionList.add(line.substring(indexSessionId, line.indexOf(' ', indexSessionId)));
        }
    }
    scanner.close();
    if (connectionList.size() != adminConnectionCount)
        throw new TGAdminException("TGAdmin - Not able to determine number of connections");
    return connectionList.toArray(new String[0]);
}

From source file:ai.grakn.graql.GraqlShell.java

private void printLicense() {
    StringBuilder result = new StringBuilder("");

    //Get file from resources folder
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream(LICENSE_LOCATION);

    Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name());
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        result.append(line).append("\n");
    }//from  w  ww. j  a v  a  2s  .c  o  m
    result.append("\n");
    scanner.close();

    this.print(result.toString());
}

From source file:com.joliciel.jochre.search.JochreIndexBuilderImpl.java

private void processDocument(File documentDir, boolean forceUpdate) {
    try {//from   w w  w .  j a  v  a 2  s . c  om
        File instructionsFile = new File(documentDir, "instructions.txt");
        boolean updateIndex = false;
        if (instructionsFile.exists()) {
            String instructions = null;
            Scanner scanner = new Scanner(
                    new BufferedReader(new InputStreamReader(new FileInputStream(instructionsFile), "UTF-8")));
            while (scanner.hasNextLine()) {
                instructions = scanner.nextLine();
                break;
            }
            scanner.close();

            LOG.info("Instructions: " + instructions + " for " + documentDir.getName());
            if (instructions.equals("delete")) {
                this.deleteDocumentInternal(documentDir);
                File lastIndexDateFile = new File(documentDir, "indexDate.txt");
                if (lastIndexDateFile.exists())
                    lastIndexDateFile.delete();

                return;
            } else if (instructions.equals("skip")) {
                return;
            } else if (instructions.equals("update")) {
                updateIndex = true;
            } else {
                LOG.info("Unknown instructions.");
            }
        }

        File zipFile = new File(documentDir, documentDir.getName() + ".zip");
        if (!zipFile.exists()) {
            LOG.info("Nothing to index in " + documentDir.getName());
            return;
        }

        File metaDataFile = new File(documentDir, "metadata.txt");
        if (!metaDataFile.exists()) {
            LOG.info("Skipping: OCR analysis incomplete for " + documentDir.getName());
            return;
        }

        if (forceUpdate)
            updateIndex = true;

        if (!updateIndex) {

            LOG.debug("Checking last update date on " + documentDir.getName());
            long zipDate = zipFile.lastModified();

            File lastIndexDateFile = new File(documentDir, "indexDate.txt");

            long lastIndexDate = Long.MIN_VALUE;

            if (lastIndexDateFile.exists()) {
                Scanner scanner = new Scanner(new BufferedReader(
                        new InputStreamReader(new FileInputStream(lastIndexDateFile), "UTF-8")));
                while (scanner.hasNextLine()) {
                    lastIndexDate = Long.parseLong(scanner.nextLine());
                    break;
                }
                scanner.close();
            }
            if (zipDate > lastIndexDate)
                updateIndex = true;
        }

        if (updateIndex) {
            this.updateDocumentInternal(documentDir);
        } else {
            LOG.info("Index for " + documentDir.getName() + "already up-to-date.");
        } // should update index?

    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:ml.shifu.shifu.core.processor.BasicModelProcessor.java

/**
 * Close all scanners/*  w  ww  .  ja  va  2 s. com*/
 * 
 * @param scanners
 *            the scanners
 */
public void closeScanners(List<Scanner> scanners) {
    if (CollectionUtils.isNotEmpty(scanners)) {
        for (Scanner scanner : scanners) {
            scanner.close();
        }
    }
}

From source file:co.pugo.convert.ConvertServlet.java

/**
 * extract a set of image links//from   w  ww  .  j a v a2s  .  co m
 * @param content document content as String
 * @return Set of http links to images
 */
private Set<String> extractImageLinks(String content) {
    final Set<String> imageLinks = new HashSet<>();
    final Scanner scanner = new Scanner(content);
    final Pattern imgPattern = Pattern.compile("<img(.*?)>", Pattern.DOTALL);
    final Pattern srcPattern = Pattern.compile("src=\"(.*?)\"");

    Matcher matchSrc;
    String imgMatch;

    while (scanner.findWithinHorizon(imgPattern, 0) != null) {
        imgMatch = scanner.match().group(1);
        matchSrc = srcPattern.matcher(imgMatch);
        if (matchSrc.find())
            imageLinks.add(matchSrc.group(1));
    }

    scanner.close();
    return imageLinks;
}

From source file:com.github.Jikoo.BookSuite.CommandHandler.java

public void asyncBookImport(final Player p, final String s) {
    new BukkitRunnable() {
        public void run() {
            BookMeta bm;//from   w  ww  . ja  v  a  2 s  .  c o m
            StringBuilder sb = new StringBuilder();
            try {
                URL url = new URL(s);
                Scanner urlInput = new Scanner(url.openStream());
                ;
                while (urlInput.hasNextLine()) {
                    sb.append(urlInput.nextLine()).append('\n');
                }
                urlInput.close();
            } catch (Exception e) {
                bm = (BookMeta) new ItemStack(Material.WRITTEN_BOOK);
            }
            bm = plugin.filemanager.makeBookMetaFromText(p, sb.toString(), true);
            syncBookImport(p, bm);
        }
    }.runTaskAsynchronously(BookSuite.getInstance());
}

From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java

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

    String get = Cache.getInstance().get(prefix + s);
    String resp = "";
    if (get != null) {
        //System.out.print(".");
        resp = get;//from www  . j  a  v  a  2  s . co m
    } else {
        final URL url = new URL(s);
        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        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();

        Cache.getInstance().put(prefix + s, resp);
    }

    return resp;
}

From source file:ch.sdi.core.impl.parser.CsvParser.java

/**
 * Parses the given input stream./*from  w  ww  . j a v  a  2 s  .  com*/
 * <p>
 *
 * @param aInputStream
 *        must not be null
 * @param aDelimiter
 *        must not be null
 * @param aEncoding
 *        The encoding to be used. If null or empty, the systems default encoding is used.
 * @return a list which contains a list for each found person. The inner list contains the found
 *         values for this person. The number and the order must correspond to the configured field
 *         name list (see
 *         in each line.
 * @throws SdiException
 */
public List<List<String>> parse(InputStream aInputStream, String aDelimiter, String aEncoding,
        List<RawDataFilterString> aFilters) throws SdiException {
    if (!StringUtils.hasLength(aDelimiter)) {
        throw new SdiException("Delimiter not set", SdiException.EXIT_CODE_CONFIG_ERROR);
    } // if myDelimiter == null

    try {
        myLog.debug("Using encoding " + aEncoding);

        BufferedReader br = new BufferedReader(
                !StringUtils.hasText(aEncoding) ? new InputStreamReader(aInputStream)
                        : new InputStreamReader(aInputStream, aEncoding));
        List<List<String>> result = new ArrayList<>();
        Collection<String> myLinesFiltered = new ArrayList<>();

        int lineNo = 0;
        String line;
        LineLoop: while ((line = br.readLine()) != null) {
            lineNo++;

            if (aFilters != null) {
                for (RawDataFilterString filter : aFilters) {
                    if (filter.isFiltered(line)) {
                        myLog.debug("Skipping commented line: " + line);
                        myLinesFiltered.add(line);
                        continue LineLoop;
                    }
                }
            }

            myLog.debug("Parsing line " + lineNo + ": " + line);

            List<String> list = new ArrayList<String>();
            Scanner sc = new Scanner(line);
            try {
                sc.useDelimiter(aDelimiter);
                while (sc.hasNext()) {
                    list.add(sc.next());
                }

                // Note: if the line is terminated by the delimiter (last entry not present, the last entry
                // will not appear in the scanned enumeration. Check for this special case:
                if (line.endsWith(aDelimiter)) {
                    list.add("");
                } // if line.endsWith( aDelimiter )
            } finally {
                sc.close();
            }

            result.add(list);
        }

        myLog.info(new ReportMsg(ReportMsg.ReportType.PREPARSE_FILTER, "Filtered lines", myLinesFiltered));

        return result;
    } catch (Throwable t) {
        throw new SdiException("Problems while parsing CSV file", t, SdiException.EXIT_CODE_PARSE_ERROR);
    }
}

From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java

public synchronized String Http2(String s, Map<String, String> mp, String prefix)
        throws SQLException, IOException {
    String md = s + mp.toString();
    String get = Cache.getInstance().get(prefix + md);
    String resp = "";
    if (get != null) {
        resp = get;/*from  ww w .  j  av  a  2 s.c  o m*/
    } else {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(s);
        method.getParams().setContentCharset("utf-8");

        //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());
        }

        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();
            Cache.getInstance().put(prefix + md, resp);

        }

    }

    return resp;
}