Example usage for java.io Reader close

List of usage examples for java.io Reader close

Introduction

In this page you can find the example usage for java.io Reader close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:net.jetrix.config.ServerConfig.java

/**
 * Load the configuration./* w w w.j av  a  2 s  .  co m*/
 */
public void load(URL serverConfigURL) {
    this.serverConfigURL = serverConfigURL;

    try {
        // parse the server configuration
        Digester digester = new Digester();
        digester.register("-//LFJR//Jetrix TetriNET Server//EN",
                findResource("tetrinet-server.dtd").toString());
        digester.setValidating(true);
        digester.addRuleSet(new ServerRuleSet());
        digester.push(this);
        Reader reader = new InputStreamReader(serverConfigURL.openStream(), ENCODING);
        digester.parse(new InputSource(reader));
        reader.close();

        // parse the channel configuration
        digester = new Digester();
        digester.register("-//LFJR//Jetrix Channels//EN", findResource("tetrinet-channels.dtd").toString());
        digester.setValidating(true);
        digester.addRuleSet(new ChannelsRuleSet());
        digester.push(this);
        channelsConfigURL = new URL(serverConfigURL, channelsFile);
        reader = new InputStreamReader(channelsConfigURL.openStream(), ENCODING);
        digester.parse(new InputSource(reader));
        reader.close();
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to load the configuration", e);
    }
}

From source file:com.googlecode.fascinator.common.PythonUtils.java

/*****
 * Parse an XML document from an inputstream
 * /*from  www  .ja v  a  2  s  .  co  m*/
 * @param xmlIn, the inputstream to read and parse
 * @return Document object after parsing
 */
public Document getXmlDocument(InputStream xmlIn) {
    Reader reader = null;
    try {
        reader = new InputStreamReader(xmlIn, "UTF-8");
        return saxReader.read(reader);
    } catch (UnsupportedEncodingException uee) {
    } catch (DocumentException de) {
        log.error("Failed to parse XML", de);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
            }
        }
    }
    return null;
}

From source file:co.cask.cdap.gateway.handlers.metrics.MetricsQueryTest.java

@Test
public void testQueueLength() throws Exception {
    QueueName queueName = QueueName.fromFlowlet("WordCount", "WordCounter", "counter", "queue");

    // Insert queue metrics
    MetricsCollector enqueueCollector = collectionService.getCollector(MetricsScope.SYSTEM,
            "WordCount.f.WordCounter.counter", "0");
    enqueueCollector.increment("process.events.out", 10, queueName.getSimpleName());

    // Insert ack metrics
    MetricsCollector ackCollector = collectionService.getCollector(MetricsScope.SYSTEM,
            "WordCount.f.WordCounter.unique", "0");
    ackCollector.increment("process.events.processed", 6, "input." + queueName.toString());
    ackCollector.increment("process.events.processed", 2, "input.stream:///streamX");
    ackCollector.increment("process.events.processed", 1, "input.stream://developer/streamX");

    // Insert stream metrics
    MetricsCollector streamCollector = collectionService.getCollector(MetricsScope.SYSTEM,
            Constants.Gateway.METRICS_CONTEXT, "0");
    streamCollector.increment("collect.events", 5, "streamX");

    // Wait for collection to happen
    TimeUnit.SECONDS.sleep(2);/*from  ww  w . j  ava2 s .c  o m*/

    // Query for queue length
    HttpPost post = getPost("/v2/metrics");
    post.setHeader("Content-type", "application/json");
    post.setEntity(new StringEntity(
            "[\"/system/apps/WordCount/flows/WordCounter/flowlets/unique/process.events.pending?aggregate=true\"]"));
    HttpResponse response = doPost(post);
    Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8);
    try {
        Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
        JsonElement json = new Gson().fromJson(reader, JsonElement.class);
        // Expected result looks like
        // [
        //   {
        //     "path":"/process/events/appId/flows/flowId/flowlet2/pending?aggregate=true",
        //     "result":{"data":6}
        //   }
        // ]
        JsonObject resultObj = json.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonObject();
        Assert.assertEquals(6, resultObj.getAsJsonPrimitive("data").getAsInt());
    } finally {
        reader.close();
    }
}

From source file:de.uzk.hki.da.metadata.MetsMetadataStructure.java

/**
 * Append to each dmdSec in a Mets-File one accessCondition-Element and save it.
 * //w ww  .j a  v  a 2 s.  c o  m
 * @param targetMetsFile
 * @param licenseHref
 * @param displayLabel
 * @param text
 * @throws IOException
 * @throws JDOMException
 */
public void appendAccessCondition(File targetMetsFile, String licenseHref, String displayLabel, String text)
        throws IOException, JDOMException {
    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();

    FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, targetMetsFile.getPath()));
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
    Reader reader = new InputStreamReader(bomInputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
    Document metsDoc = builder.build(is);

    List<Element> dmdSections = metsDoc.getRootElement().getChildren("dmdSec", C.METS_NS);

    for (int i = 0; i < dmdSections.size(); i++) {
        Element newAccessConditionE = generateAccessCondition(licenseHref, displayLabel, text);
        logger.debug("Append to Mets new LicenseElement: " + newAccessConditionE.toString());
        Element dmdSecElement = (Element) dmdSections.get(i);
        Element modsXmlData = MetsParser.getModsXmlData(dmdSecElement);
        modsXmlData.addContent(newAccessConditionE);
    }
    fileInputStream.close();
    bomInputStream.close();
    reader.close();

    writeDocumentToFile(metsDoc, Path.makeFile(workPath, targetMetsFile.getPath()));
}

From source file:com.adamrosenfield.wordswithcrosses.net.derstandard.SolutionParser.java

public void parse(InputSource input) throws SAXException, IOException, JSONException {
    Reader reader = getReader(input);

    try {//from www  . j  a v  a2s  . c o m
        String json = read(reader);

        Puzzle p = pm.getPuzzle();

        boolean responseWasSane = false;

        JSONObject response = new JSONObject(json);
        JSONArray results = response.getJSONArray("Results");
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            int wordNumber = result.getInt("WordNumber");
            String answer = result.getString("Answer");
            boolean horizontal = result.getBoolean("Horizontal");

            writeAnswer(p, wordNumber, answer, horizontal);

            responseWasSane = true;
        }

        if (responseWasSane) {
            p.setScrambled(false);
            pm.setSolutionAvailable(true);
        }

    } finally {
        reader.close();
    }
}

From source file:com.github.jrh3k5.membership.renewal.mailer.service.jpa.JpaEmailService.java

@Override
public void loadEmails(InputStream emailCsv) throws IOException {
    final Reader emailCsvReader = new InputStreamReader(emailCsv);
    try {//from   ww  w .  j  a  v a  2 s  . c o m
        int rowIndex = 0;
        for (String[] row : new CSVReaderBuilder<String[]>(emailCsvReader)
                .entryParser(new DefaultCSVEntryParser()).strategy(CSVStrategy.UK_DEFAULT).build()) {
            if (rowIndex++ == 0) {
                // Skip the first row, which, presumably, has the column names in it
                continue;
            }

            // Skip any malformed rows
            if (row.length < 3) {
                continue;
            }

            // If someone signs up through the site, they won't have a first and last name
            // We can't match on that, so ignore it
            if (StringUtils.isNoneBlank(row[1], row[2])) {
                addEmail(row[1], row[2], row[0]);
            }
        }
    } finally {
        emailCsvReader.close();
    }
}

From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from   www  .  jav a 2  s  .  c  om*/
        //double btcRate = getGoldCoinValueBTC();

        Double btcRate = 0.0;

        Object result = getGoldCoinValueBTC();

        if (result == null)
            return null;

        else
            btcRate = (Double) result;

        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            //Add Bitcoin information
            rates.put("BTC", new ExchangeRate("BTC",
                    Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com"));

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                double gldInCurrency = o.getDouble("15m") * btcRate;
                final String rate = String.format("%.8f", gldInCurrency); //o.optString("15m", null);

                if (rate != null)
                    rates.put(currencyCode, new ExchangeRate(currencyCode,
                            Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.googlecode.fascinator.common.PythonUtils.java

/*****
 * Parse an XML document from a string/* www .  j av  a  2s .  co m*/
 * 
 * @param xmlData to parse
 * @return Document object after parsing
 */
public Document getXmlDocument(String xmlData) {
    Reader reader = null;
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(xmlData.getBytes("utf-8"));
        return saxReader.read(in);
    } catch (UnsupportedEncodingException uee) {
    } catch (DocumentException de) {
        log.error("Failed to parse XML", de);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
            }
        }
    }
    return null;
}

From source file:com.tbodt.jswerve.maven.GenerateTemplatesMojo.java

/**
 * Executes the mojo.//from  www  .j a  va2s.  com
 *
 * @throws MojoExecutionException if something really bad happens
 */
public void execute() throws MojoExecutionException {
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.addDefaultExcludes();
    scanner.setBasedir(sourceDirectory);
    scanner.setIncludes(new String[] { "**/*.jtl" });
    scanner.scan();

    for (String templatePath : scanner.getIncludedFiles()) {
        File template = new File(sourceDirectory, templatePath);

        String templateClassName = StringUtils.removeEnd(templatePath, ".jtl").replace('.', '_')
                .replace(File.separatorChar, '.');

        int lastDot = templateClassName.lastIndexOf('.');
        String templatePackage = templateClassName.substring(0, lastDot);
        String templateName = templateClassName.substring(lastDot + 1);

        File outputFile = new File(outputDirectory,
                templateClassName.replace('.', File.separatorChar) + ".java");
        Reader input = null;
        PrintWriter output = null;
        try {
            input = new FileReader(template);
            getLog().debug(String.valueOf(outputFile.getParentFile().mkdirs()));
            output = new PrintWriter(new FileWriter(outputFile));

            output.println("package " + templatePackage + ";");
            output.println();
            output.println("public class " + templateName + " implements com.tbodt.jswerve.Template {");
            output.println("    @Override");
            output.println("    public String render() {");
            output.write(Jtl.generateCode(input));
            output.println("    }");
            output.println("}");
        } catch (IOException ioe) {
            throw new MojoExecutionException("IOException!", ioe);
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException ex) {
                    getLog().error(ex); // nothing else can be done
                }
            if (output != null)
                output.close();
        }
    }

    // notify maven of the new output directory
    project.addCompileSourceRoot(outputDirectory.getPath());
}

From source file:architecture.common.xml.XmlProperties.java

/**
 * Builds the document XML model up based the given reader of XML data.
 * //  w  w w .j  a  v a2  s  .c  o  m
 * @param in
 *            the input stream used to build the xml document
 * @throws java.io.IOException
 *             thrown when an error occurs reading the input stream.
 */
private void buildDoc(Reader in) throws IOException {
    try {
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        document = xmlReader.read(in);
    } catch (Exception e) {
        log.error("Error reading XML properties", e);
        throw new IOException(e.getMessage());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}