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:ml.shifu.shifu.core.processor.ExportModelProcessor.java

private Map<Integer, ColumnStatistics> readSEValuesToMap(String seOutputFiles, SourceType source)
        throws IOException {
    // here only works for 1 reducer
    FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source)
            .globStatus(new Path(seOutputFiles));
    if (globStatus == null || globStatus.length == 0) {
        throw new RuntimeException("Var select MSE stats output file not exist.");
    }/*from  w w  w . j  av  a2s  .  c  o m*/
    Map<Integer, ColumnStatistics> map = new HashMap<Integer, ColumnStatistics>();
    List<Scanner> scanners = null;
    try {
        scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source);
        for (Scanner scanner : scanners) {
            String str = null;
            while (scanner.hasNext()) {
                str = scanner.nextLine().trim();
                String[] splits = CommonUtils.split(str, "\t");
                if (splits.length == 5) {
                    map.put(Integer.parseInt(splits[0].trim()),
                            new ColumnStatistics(Double.parseDouble(splits[2]), Double.parseDouble(splits[3]),
                                    Double.parseDouble(splits[4])));
                }
            }
        }
    } finally {
        if (scanners != null) {
            for (Scanner scanner : scanners) {
                if (scanner != null) {
                    scanner.close();
                }
            }
        }
    }
    return map;
}

From source file:org.ala.util.BieAccessLogReader.java

public final void processFile(String aFileName, String url) throws FileNotFoundException {
    Scanner scanner = new Scanner(new File(aFileName));
    try {/*from   w ww  .ja  v a2  s . co m*/
        if (uidInfosourceIDMap == null) {
            uidInfosourceIDMap = infoSourceDao.getInfosourceIdUidMap();
        }
        if (restfulClient == null) {
            restfulClient = new RestfulClient();
        }
        if (serMapper == null) {
            serMapper = new ObjectMapper();
            serMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        }
        // first use a Scanner to get each line
        while (scanner.hasNextLine()) {
            try {
                processLine(scanner.nextLine(), url);
            } catch (Exception e) {
                //do nothing
                e.printStackTrace();
            }
        }
    } finally {
        // ensure the underlying stream is always closed
        // this only has any effect if the item passed to the Scanner
        // constructor implements Closeable (which it does in this case).
        try {
            //check & clean recordCounts.
            processLine("", url);
            System.out.println("****** PROCESS END. line ctr :" + ctr);
        } catch (Exception e) {
            //do nothing
        }
        scanner.close();
        restfulClient = null;
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.playback.GerritMissedEventsPlaybackManager.java

/**
 * Takes a string of json events and creates a collection.
 * @param eventsString Events in json in a string.
 * @return collection of events./*from w w w.ja  va  2  s . c  o m*/
 */
private List<GerritTriggeredEvent> createEventsFromString(String eventsString) {
    List<GerritTriggeredEvent> events = Collections.synchronizedList(new ArrayList<GerritTriggeredEvent>());
    Scanner scanner = new Scanner(eventsString);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        logger.debug("found line: {}", line);
        JSONObject jsonObject = null;
        try {
            jsonObject = GerritJsonEventFactory.getJsonObjectIfInterestingAndUsable(line);
            if (jsonObject == null) {
                continue;
            }
        } catch (Exception ex) {
            logger.warn("Unanticipated error when creating DTO representation of JSON string.", ex);
            continue;
        }
        GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject);
        if (evt instanceof GerritTriggeredEvent) {
            Provider provider = new Provider();
            provider.setName(serverName);
            ((GerritTriggeredEvent) evt).setProvider(provider);
            events.add((GerritTriggeredEvent) evt);
        }
    }
    scanner.close();
    return events;
}

From source file:br.com.poc.navigation.NavigationLoader.java

private void startNavigation() {

    Scanner scanner = new Scanner(System.in);

    this.printLogo();

    boolean continueExecution = true;

    do {//ww w . jav a  2s. com

        this.printMenu();

        final String option = scanner.next();

        switch (option) {

        case "1":

            try {

                this.printCommandList();

                String commands = scanner.next();

                System.out.println("\n > Aguarde o processamento....");

                System.out.println("\n > Comandos inputados: " + commands);

                final String distinateCoordinate = navigationComponent.traceRoute(commands).toString();

                System.out.println("\n > A rota final ser: " + distinateCoordinate);

            } catch (ParseInputCommandException | InvalidCommandException exception) {

                System.out.println("\n > Ocorreram alguns erros ao processar a sequncia de comandos:\n");

                final List<String> messages = ExceptionMessageCollector.getStackMessages(exception);

                messages.stream().forEach((message) -> {
                    System.out.println(message);
                });

            }

            break;

        case "2":

            System.out.println("\n > Obrigado por navegar conosco! \n");

            scanner.close();

            continueExecution = false;

            break;

        default:

            System.out.println("\n > Opo de menu invlida.");

            break;

        }

    } while (continueExecution);

}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.FrenchTemplateParser.java

public HashMap<String, String> getParseText(String path, boolean print, boolean normalize)
        throws FileNotFoundException {

    HashMap<String, String> parsing = new HashMap<String, String>();

    String filePath = path;//from  w ww.  j a  v  a 2  s .c om
    Scanner scanner = new Scanner(new File(filePath));

    // On boucle sur chaque champ detect
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        line = line.trim();

        if (!line.startsWith("#") && line.length() > 0) {

            String name = line.replaceAll("\\[(.*)\\]", "");
            String value = line.substring(name.length());
            value = value.replaceAll("\\[", "");
            value = value.replaceAll("\\]", "");

            if (print) {
                System.out.println(name + "\t" + value);
            }
            parsing.put(name, value);

            if (normalize) {
                if (print) {
                    System.out.println(name.toUpperCase() + "\t" + value);
                    System.out.println(name.toLowerCase() + "\t" + value);
                }
                parsing.put(name.toUpperCase(), value);
                parsing.put(name.toLowerCase(), value);
            }
        }
        // faites ici votre traitement
    }

    scanner.close();

    return parsing;
}

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private boolean resultsWithinBounds(Rectangle bounds) {
    if (resultsWindowShowing()) {
        float minx = bounds.x;
        float maxx = minx + bounds.width;
        float miny = bounds.y;
        float maxy = miny + bounds.height;

        for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
            String line = resultsWindow.getTextPanel().getLine(i);
            Scanner s = new Scanner(line);
            s.useDelimiter("\t");
            s.nextInt();/*w  w  w. jav a 2s  .c  o  m*/
            float cx = s.nextFloat(); // cx
            float cy = s.nextFloat(); // cy
            s.close();
            if (cx >= minx && cx <= maxx && cy >= miny && cy <= maxy) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

private static void loadPageFile(String host, File file) {
    Scanner scan = null;
    try {// ww w  . j a va2 s  .  com
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        String pageId = file.getName();
        pageId = pageId.substring(0, pageId.lastIndexOf('.'));
        if (content != null && !content.equals(pageMap.get(pageId))) {
            System.out.println(content);
            System.out.println(pageMap.get(pageId));
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "page");
            inputMap.put("name", "impPage");
            inputMap.put("readOnly", false);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("pageId", pageId);
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Page: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            //System.out.println("Skip file " + pageId);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java

/**
 * XNDisc Server  ? ?  ?/*from  w w w. j  a  v  a2  s.  c om*/
 * 
 * @return ?? true,  false
 */
private static boolean isXNDiscServerAlive() {
    boolean isAlive = false;

    String HOST = XNDiscConfig.getString(XNDiscConfig.HOST, XNDiscConfig.LOCAL_HOST);
    String PORT = XNDiscConfig.getString(XNDiscConfig.PORT);

    Scanner scanner = null;
    ByteArrayOutputStream baos = null;
    try {
        String os = System.getProperty("os.name").toLowerCase();
        String ostype = (os.contains("windows")) ? "W" : "U";
        CommandLine cmdline = new CommandLine("netstat");
        cmdline.addArgument("-an");
        if (ostype.equals("W")) {
            cmdline.addArgument("-p");
            cmdline.addArgument("\"TCP\"");
        } else { // UNIX ? ? -an ? ?  ?  
            if (XNDiscUtils.isSolaris()) {
                cmdline.addArgument("-P");
                cmdline.addArgument("tcp");
            } else if (XNDiscUtils.isAix()) {
                cmdline.addArgument("-p");
                cmdline.addArgument("TCP");
            }
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        baos = new ByteArrayOutputStream();
        PumpStreamHandler sh = new PumpStreamHandler(baos);
        executor.setStreamHandler(sh);
        executor.execute(cmdline);
        String str = baos.toString();
        if (str != null && str.length() > 0) { // ?  XNDisc alive ?(XNDisc Server ? ?)
            scanner = new Scanner(str);
            while (scanner.hasNextLine()) {
                String readline = scanner.nextLine();
                if (readline.contains(HOST) && readline.contains(PORT)
                        && readline.contains(XNDISC_LISTEN_STATUS)) {
                    isAlive = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        isAlive = false;
    } finally {
        try {
            if (scanner != null) {
                scanner.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return isAlive;
}

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private void saveTraces() {
    if (!onFrames.isEmpty() && updated) {
        GenericDialog gd = new GenericDialog(TITLE);
        gd.enableYesNoCancel();//from   w w w.j  ava  2  s  .c  om
        gd.hideCancelButton();
        gd.addMessage("The list contains unsaved selected frames.\n \nDo you want to continue?");
        gd.showDialog();
        if (!gd.wasOKed())
            return;
    }

    // For all spots in the results window, get the ID and then save the traces to memory
    if (!resultsWindowShowing())
        return;

    // Create a results set in memory
    MemoryPeakResults results = new MemoryPeakResults();
    results.setName(TITLE);
    results.begin();
    MemoryPeakResults.addResults(results);

    ArrayList<TraceResult> traceResults = new ArrayList<TraceResult>(
            resultsWindow.getTextPanel().getLineCount());
    for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
        String line = resultsWindow.getTextPanel().getLine(i);
        Scanner s = new Scanner(line);
        s.useDelimiter("\t");
        int id = s.nextInt();
        s.nextDouble(); // cx
        s.nextDouble(); // cy
        double signal = s.nextDouble();
        s.close();

        Trace trace = traces.get(id);
        if (trace != null) {
            results.addAll(trace.getPoints());
            traceResults.add(new TraceResult(new Spot(id, signal), trace));
        }
    }

    results.end();

    saveTracesToFile(traceResults);

    IJ.showStatus("Saved traces");
}

From source file:carmen.LocationResolver.java

/**
 * /*  www.  j  a  v a2  s.  c om*/
 * @param fileName
 * @param splitOn
 * @return
 * @throws IOException 
 */
protected HashMap<String, Integer> loadLocationToIdFile(String filename) throws IOException {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    Scanner inputScanner = new Scanner(new FileInputStream(filename), "UTF-8");
    int lineNumber = 0;
    while (inputScanner.hasNextLine()) {
        lineNumber++;
        String line = null;
        try {
            line = inputScanner.nextLine().toLowerCase();
            String[] splitString = line.split("\t");
            int locationId = Integer.parseInt(splitString[0].trim());
            for (int ii = 1; ii < splitString.length; ii++) {
                String entry = splitString[ii].trim();
                // Check for duplicates.
                if (map.containsKey(entry) && !map.get(entry).equals(locationId)) {
                    logger.warn("Duplicate location found: " + entry);
                }
                map.put(entry, locationId);
            }
        } catch (Exception e) {
            logger.warn("Error in location to id file line " + lineNumber + ": " + filename + ";" + line);
        }
    }
    inputScanner.close();
    return map;
}