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:debrepo.teamcity.archive.DebFileReader.java

protected Map<String, String> getDebItemsFromControl(File debFile, String controlFileContents) {
    Pattern p = Pattern.compile("^(\\S+):(.+)$");

    Map<String, String> map = new LinkedHashMap<String, String>();
    Scanner scanner = new Scanner(controlFileContents);

    while (scanner.hasNextLine()) {
        Matcher m = p.matcher(scanner.nextLine());
        if (m.find()) {
            map.put(m.group(1), m.group(2).trim());
        }//from  w w w  .ja va2 s .c o  m
    }
    scanner.close();

    map.putAll(getExtraPackageItemsFromDeb(debFile));

    return map;
}

From source file:com.bealearts.template.SimpleTemplate.java

/**
 * Load a template file// w w w .j  av  a 2 s .  co  m
 * @throws FileNotFoundException 
 */
public void loadTemplate(File template) throws FileNotFoundException {
    this.blockMap = new HashMap<String, BlockContent>();
    this.blockData = null;

    StringBuilder text = new StringBuilder();
    String NL = System.getProperty("line.separator");
    Scanner scanner = new Scanner(new FileInputStream(template), "UTF-8");
    try {
        while (scanner.hasNextLine()) {
            text.append(scanner.nextLine() + NL);
        }
    } finally {
        scanner.close();
    }

    this.parseTemplate(text.toString());
}

From source file:org.sasabus.export2Freegis.network.DataReadyManager.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long start = System.currentTimeMillis();
    BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody()));
    try {//from  w  w w .j  av  a2  s.  c  o  m
        StringBuilder requestStringBuff = new StringBuilder();
        int b;
        while ((b = in.read()) != -1) {
            requestStringBuff.append((char) b);
        }
        Scanner sc = new Scanner(new File(DATAACKNOWLEDGE));
        String rdyackstring = "";
        while (sc.hasNextLine()) {
            rdyackstring += sc.nextLine();
        }
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);

        rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp);

        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length());
        out.write(rdyackstring);
        out.flush();
        long before_elab = System.currentTimeMillis() - start;
        DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber);
        String datarequest = teqrequest.datarequest();
        ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest);
        int vtcounter = 0;
        if (!requestelements.isEmpty()) {
            Iterator<TeqObjects> iterator = requestelements.iterator();
            System.out.println("Sending List of Elements!");
            String geoJson = "{\"type\":\"FeatureCollection\",\"features\":[";
            while (iterator.hasNext()) {
                TeqObjects object = iterator.next();
                if (object instanceof VehicleTracking) {
                    geoJson += ((VehicleTracking) object).toGeoJson() + ",";
                    ++vtcounter;
                }
            }
            if (geoJson.charAt(geoJson.length() - 1) == ',') {
                geoJson = geoJson.substring(0, geoJson.length() - 1);
            }
            geoJson += "]}";
            System.out.println(
                    "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )");
            HttpPost subrequest = new HttpPost(DATASEND);

            StringEntity requestEntity = new StringEntity(geoJson,
                    ContentType.create("application/json", "UTF-8"));

            CloseableHttpClient httpClient = HttpClients.createDefault();

            subrequest.setEntity(requestEntity);
            long after_elab = System.currentTimeMillis() - start;
            CloseableHttpResponse response = httpClient.execute(subrequest);
            //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode());
            //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase());
            httpClient.close();
            long before_db = System.currentTimeMillis() - start;
            dbmanager.insertIntoDatabase(requestelements);
            System.out.format(
                    "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d",
                    before_elab, after_elab, before_db, (System.currentTimeMillis() - start),
                    Thread.currentThread().getName(), requestelements.size());
            System.out.println("");
        }

    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
        return;
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (httpExchange != null)
            httpExchange.close();
    }
}

From source file:tr.edu.gsu.nerwip.tools.corpus.ArticleCompletion.java

/**
 * This methods allows setting the category of 
 * articles already retrieved and manually annotated
 * for evaluation. This way, the annotation can be
 * performed overall, or in function of the category.
 * The categories must be listed in a file in which
 * each line contains the name of the article folder
 * and the corresponding category.// ww  w. j  a v a2  s.c o  m
 * 
 * @throws ParseException
 *       Problem while accessing the files.
 * @throws SAXException
 *       Problem while accessing the files.
 * @throws IOException
 *       Problem while accessing the files.
 */
private static void insertArticleCategories() throws ParseException, SAXException, IOException {
    logger.log("Setting categories in articles");
    logger.increaseOffset();

    File file = new File(FileNames.FO_OUTPUT + File.separator + "cats" + FileNames.EX_TXT);
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis);
    Scanner scanner = new Scanner(isr);
    logger.log("Reading file " + file);

    logger.increaseOffset();
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine().trim();
        String temp[] = line.split("\\t");
        String name = temp[0];
        String folderPath = FileNames.FO_OUTPUT + File.separator + name;
        File folderFile = new File(folderPath);
        if (folderFile.exists()) {
            //            String gender = temp[1];
            String categoryStr = temp[2].toUpperCase(Locale.ENGLISH);
            ArticleCategory category = ArticleCategory.valueOf(categoryStr);
            //category = StringTools.initialize(category);
            logger.log("Processing '" + name + "': cat=" + category);
            List<ArticleCategory> categories = new ArrayList<ArticleCategory>();
            categories.add(category);

            Article article = Article.read(name);
            article.setCategories(categories);
            article.write();
        } else
            logger.log("Processing '" + temp[0] + "': folder not found");
    }
    logger.decreaseOffset();

    scanner.close();
    logger.decreaseOffset();
    logger.log("Categories set");
}

From source file:com.yahoo.ycsb.bulk.hbase.RangePartitioner.java

private synchronized Text[] getCutPoints() throws IOException {
    if (cutPointArray == null) {
        String cutFileName = conf.get(CUTFILE_KEY);
        Path[] cf = DistributedCache.getLocalCacheFiles(conf);

        if (cf != null) {
            for (Path path : cf) {
                if (path.toUri().getPath().endsWith(cutFileName.substring(cutFileName.lastIndexOf('/')))) {
                    TreeSet<Text> cutPoints = new TreeSet<Text>();
                    Scanner in = new Scanner(new BufferedReader(new FileReader(path.toString())));
                    try {
                        while (in.hasNextLine())
                            cutPoints.add(new Text(Base64.decodeBase64(in.nextLine().getBytes())));
                    } finally {
                        in.close();
                    }//from  w w  w  . j av a  2s  .  com
                    cutPointArray = cutPoints.toArray(new Text[cutPoints.size()]);
                    break;
                }
            }
        }
        if (cutPointArray == null)
            throw new FileNotFoundException(cutFileName + " not found in distributed cache");
    }
    return cutPointArray;
}

From source file:de.uzk.hki.da.repository.ElasticsearchMetadataIndex.java

@Override
public String getIndexedMetadata(String indexName, String objectId) {

    try {//from   www.  j  a v  a 2  s . com
        String requestURL = "http://localhost:9200/" + indexName + "/" + C.ORE_AGGREGATION + "/_search?q=_id:"
                + objectId + "*";
        System.out.println("requestURL:" + requestURL);
        logger.debug("requestURL:" + requestURL);
        URL wikiRequest;
        wikiRequest = new URL(requestURL);
        URLConnection connection;
        connection = wikiRequest.openConnection();
        connection.setDoOutput(true);

        Scanner scanner;
        scanner = new Scanner(wikiRequest.openStream());
        String response = scanner.useDelimiter("\\Z").next();
        System.out.println("R:" + response);

        scanner.close();
        return response;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:de.uzk.hki.da.repository.ElasticsearchMetadataIndex.java

@Override
public String getAllIndexedMetadataFromIdSubstring(String indexName, String objectId) {

    try {/*from www . j  av  a  2s  .c  o  m*/
        String requestURL = "http://localhost:9200/" + indexName + "/" + C.ORE_AGGREGATION + "/_search?q=_id:"
                + objectId + "" + "*";
        System.out.println("requestURL:" + requestURL);
        logger.debug("requestURL:" + requestURL);
        URL wikiRequest;
        wikiRequest = new URL(requestURL);
        URLConnection connection;
        connection = wikiRequest.openConnection();
        connection.setDoOutput(true);

        Scanner scanner;
        scanner = new Scanner(wikiRequest.openStream());
        String response = scanner.useDelimiter("\\Z").next();
        System.out.println("R:" + response);

        scanner.close();
        return response;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:jp.classmethod.aws.petrucci.Tasks.java

@Scheduled(cron = "0 */2 * * * *")
public void reportS3AndEC2() {
    logger.info("report start");
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    StringBuilder sb = new StringBuilder();

    logger.info("check S3 buckets");
    sb.append("== S3 Buckets ==\n");
    try {//ww  w. j  av  a2  s.com
        for (Bucket bucket : s3.listBuckets()) {
            sb.append(
                    String.format("%s (created:%s)%n", bucket.getName(), df.format(bucket.getCreationDate())));
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    sb.append("\n");

    logger.info("check EC2 instances");
    sb.append("== EC2 Instances ==").append("\n");
    try {
        DescribeInstancesResult result = ec2.describeInstances();
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                sb.append(String.format("%s %s %s%n", instance.getInstanceId(), instance.getImageId(),
                        instance.getInstanceType(), instance.getInstanceLifecycle()));
            }
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    if (logger.isInfoEnabled()) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(sb.toString());
            while (scanner.hasNextLine()) {
                logger.info("{}", scanner.nextLine());
            }
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    logger.info("send report mail");
    ses.sendEmail(new SendEmailRequest(mailaddress, new Destination(Collections.singletonList(mailaddress)),
            new Message(new Content("S3 & EC2 Report"), new Body(new Content(sb.toString())))));

    logger.info("report end");
}

From source file:uk.ac.gda.dls.client.views.MonitorCompositeFactory.java

void setVal(String newVal) {
    if (decimalPlaces != null) {
        Scanner sc = new Scanner(newVal.trim());
        if (sc.hasNextDouble()) {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(decimalPlaces.intValue());
            newVal = format.format(sc.nextDouble());
        }//from w  w  w  .  ja  v  a2 s.c om
        sc.close();
    }
    val = newVal;
    if (!isDisposed())
        display.asyncExec(setTextRunnable);
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptBSearchModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFileSearch, String searchString)
        throws ExcerptBSearchException {
    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {/*  w  ww .j a  v  a2s  .co m*/
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFileSearch.getAbsolutePath() + ".tmp");
    String content = "";
    String contentAll = "";

    // Records aus table herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getSearchtableName();
        String folder = getConfigurationService().getSearchtableFolder();

        File fSearchtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        searchString = searchString.replaceAll("\\.", "\\.*");

        try {
            // grep -E "REGEX-Suchbegriff" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " -E \"" + searchString + "\" "
                    + fSearchtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                Util.switchOffConsole();
                rt = Runtime.getRuntime();
                proc = rt.exec(command.toString().split(" "));
                // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

                // Fehleroutput holen
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

                // Output holen
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

                // Threads starten
                errorGobbler.start();
                outputGobbler.start();

                // Warte, bis wget fertig ist
                proc.waitFor();

                Util.switchOnConsole();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            contentAll = "";
            content = "";
            contentAll = scanner.useDelimiter("\\Z").next();
            scanner.close();
            content = contentAll;
            /* im contentAll ist jetzt der Gesamtstring, dieser soll anschliessend nur noch aus den 4
             * Such-Zellen und den weiteren 4 ResultateZellen bestehen -> content */
            String nr1 = getConfigurationService().getcellNumber1();
            String nr2 = getConfigurationService().getcellNumber2();
            String nr3 = getConfigurationService().getcellNumber3();
            String nr4 = getConfigurationService().getcellNumber4();
            String nr5 = getConfigurationService().getcellNumberResult1();
            String nr6 = getConfigurationService().getcellNumberResult2();
            String nr7 = getConfigurationService().getcellNumberResult3();
            String nr8 = getConfigurationService().getcellNumberResult4();

            String cellLoop = "";
            // Loop von 1, 2, 3 ... bis 499999.
            for (int i = 1; i < 500000; i++) {
                cellLoop = "";
                cellLoop = "c" + i;
                if (cellLoop.equals(nr1) || cellLoop.equals(nr2) || cellLoop.equals(nr3) || cellLoop.equals(nr4)
                        || cellLoop.equals(nr5) || cellLoop.equals(nr6) || cellLoop.equals(nr7)
                        || cellLoop.equals(nr8)) {
                    // wird behalten
                } else {
                    String deletString = "<c" + i + ">" + ".*" + "</c" + i + ">";
                    content = content.replaceAll(deletString, "");
                }
            }

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            contentAll = "";
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}