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:com.hypersocket.upgrade.UpgradeServiceImpl.java

private void executeScript(Map<String, Object> beans, URL script) throws ScriptException, IOException {
    if (log.isInfoEnabled()) {
        log.info("Executing script " + script);
    }//from  w w  w.j  a v a  2s.c  o m

    if (script.getPath().endsWith(".js")) {
        ScriptContext context = new SimpleScriptContext();
        ScriptEngine engine = buildEngine(beans, script, context);
        InputStream openStream = script.openStream();
        if (openStream == null) {
            throw new FileNotFoundException("Could not locate resource " + script);
        }
        Reader in = new InputStreamReader(openStream);
        try {
            engine.eval(in, context);
        } finally {
            in.close();
        }
    } else if (script.getPath().endsWith(".class")) {
        String path = script.getPath();
        int idx = path.indexOf("upgrade/");
        path = path.substring(idx);
        idx = path.lastIndexOf(".");
        path = path.substring(0, idx).replace("/", ".");
        try {
            @SuppressWarnings("unchecked")
            Class<? extends Runnable> clazz = (Class<? extends Runnable>) getClass().getClassLoader()
                    .loadClass(path);
            Runnable r = clazz.newInstance();
            springContext.getAutowireCapableBeanFactory().autowireBean(r);
            r.run();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {

        BufferedReader r = new BufferedReader(new InputStreamReader(script.openStream()));
        try {
            String statement = "";
            String line;
            boolean ignoreErrors = false;
            while ((line = r.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("EXIT IF FRESH")) {
                    if (isFreshInstall()) {
                        break;
                    }
                    continue;
                }

                if (!line.startsWith("/*") && !line.startsWith("//")) {
                    if (line.endsWith(";")) {
                        line = line.substring(0, line.length() - 1);
                        statement += line;
                        sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                        statement = "";
                    } else {
                        statement += line + "\n";
                    }
                }
            }

            if (StringUtils.isNotBlank(statement)) {
                try {
                    sessionFactory.getCurrentSession().createSQLQuery(statement).executeUpdate();
                } catch (Throwable e) {
                    if (!ignoreErrors) {
                        throw e;
                    }
                }
            }
        } finally {
            r.close();
        }
    }

}

From source file:net.ontopia.topicmaps.impl.rdbms.Occurrence.java

@Override
public String getValue() {
    Object value = loadField(LF_value);
    if (value instanceof String) {
        return (String) value;
    } else if (value instanceof OnDemandValue) {
        OnDemandValue odv = (OnDemandValue) value;
        try {//  w  w w .  j a v a2 s  . c om
            Reader r = (Reader) odv.getValue(_p_getTransaction());
            try {
                return IOUtils.toString(r);
            } finally {
                r.close();
            }
        } catch (IOException e) {
            throw new OntopiaRuntimeException(e);
        }
    } else if (value != null) {
        throw new OntopiaRuntimeException("Occurrence value cannot be non-null at this point: " + value);
    } else {
        return null; // FIXME: or possibly something else
    }
}

From source file:net.ontopia.topicmaps.impl.rdbms.VariantName.java

@Override
public String getValue() {
    Object value = loadField(LF_value);
    if (value instanceof String) {
        return (String) value;
    } else if (value instanceof OnDemandValue) {
        OnDemandValue odv = (OnDemandValue) value;
        try {//  w  w w  .  ja  va  2s  .  c  o m
            Reader r = (Reader) odv.getValue(_p_getTransaction());
            try {
                return IOUtils.toString(r);
            } finally {
                r.close();
            }
        } catch (IOException e) {
            throw new OntopiaRuntimeException(e);
        }
    } else if (value != null) {
        throw new OntopiaRuntimeException("VariantName value cannot be non-null at this point: " + value);
    } else {
        return null; // FIXME: or possibly something else
    }
}

From source file:com.adamrosenfield.wordswithcrosses.net.DerStandardDownloader.java

private void downloadPuzzle(DerStandardPuzzleMetadata pm) throws RefreshException {
    String pUrl = pm.getPuzzleUrl(BASE_URL);
    int id = pm.getId();

    boolean save = false;

    if (pUrl != null && !pm.isPuzzleAvailable()) {
        try {//from w  w w. j a v  a  2  s. c  o m
            Reader r = getURLReader(getHttpConnection(pUrl));
            try {
                InputSource input = new InputSource(r);
                parser.parsePuzzle(pm, input);
                save = true;
            } finally {
                r.close();
            }
        } catch (IOException e) {
            throw new RefreshException("Fetching/Parsing puzzle for " + pUrl + ".", e);
        } catch (ParserConfigurationException e) {
            throw new RefreshException("Fetching/Parsing puzzle for " + pUrl + ".", e);
        } catch (SAXException e) {
            throw new RefreshException("Fetching/Parsing puzzle for " + pUrl + ".", e);
        }
    }

    if (pm.isPuzzleAvailable() && !pm.isSolutionAvailable()) {
        try {
            InputSource isSolution = postForSolution(id);
            if (isSolution != null) {
                parser.parseSolution(pm, isSolution);
                save = true;
            }
        } catch (IOException e) {
            throw new RefreshException("Fetching/Parsing solution for " + id + ".", e);
        } catch (JSONException e) {
            throw new RefreshException("Fetching/Parsing solution for " + id + ".", e);
        } catch (SAXException e) {
            throw new RefreshException("Fetching/Parsing solution for " + id + ".", e);
        }
    }

    if (save) {
        try {
            savePuzzle(pm);
        } catch (IOException ioe) {
            throw new RefreshException("Saving puzzle " + id + ".", ioe);
        }
    }
}

From source file:com.continuuity.loom.http.LoomPluginHandlerTest.java

private String bodyToString(HttpResponse response) throws IOException {
    Reader reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8);
    try {//from   w w  w  .  j a  va2s  .c o m
        return CharStreams.toString(reader);
    } finally {
        reader.close();
    }
}

From source file:com.xiuhao.commons.mybatis.SqlSessionFactoryBuilderFix.java

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {/*from w  ww  .j av  a2s  .  c  o m*/
        XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
        return build(parser.parse());
    } catch (Exception e) {
        log.error("", e);
        throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
        ErrorContext.instance().reset();
        try {
            reader.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:fr.paris.lutece.portal.service.search.PageIndexer.java

/**
 * Builds a document which will be used by Lucene during the indexing of the
 * pages of the site with the following//w  w w .  ja  v a 2 s .  c o m
 * fields : summary, uid, url, contents, title and description.
 * @return the built Document
 * @param strUrl The base URL for documents
 * @param page the page to index
 * @throws IOException The IO Exception
 * @throws InterruptedException The InterruptedException
 * @throws SiteMessageException occurs when a site message need to be
 *             displayed
 */
protected Document getDocument(Page page, String strUrl)
        throws IOException, InterruptedException, SiteMessageException {
    // make a new, empty document
    Document doc = new Document();

    // Add the url as a field named "url".  Use an UnIndexed field, so
    // that the url is just stored with the document, but is not searchable.
    doc.add(new Field(SearchItem.FIELD_URL, strUrl, Field.Store.YES, Field.Index.NOT_ANALYZED));

    // Add the last modified date of the file a field named "modified".
    // Use a field that is indexed (i.e. searchable), but don't tokenize
    // the field into words.
    String strDate = DateTools.dateToString(page.getDateUpdate(), DateTools.Resolution.DAY);
    doc.add(new Field(SearchItem.FIELD_DATE, strDate, Field.Store.YES, Field.Index.NOT_ANALYZED));

    // Add the uid as a field, so that index can be incrementally maintained.
    // This field is not stored with document, it is indexed, but it is not
    // tokenized prior to indexing.
    String strIdPage = String.valueOf(page.getId());
    doc.add(new Field(SearchItem.FIELD_UID, strIdPage, Field.Store.NO, Field.Index.NOT_ANALYZED));

    String strPageContent = _pageService.getPageContent(page.getId(), 0, null);
    StringReader readerPage = new StringReader(strPageContent);
    HTMLParser parser = new HTMLParser(readerPage);

    //the content of the article is recovered in the parser because this one
    //had replaced the encoded caracters (as &eacute;) by the corresponding special caracter (as ?)
    Reader reader = parser.getReader();
    int c;
    StringBuilder sb = new StringBuilder();

    while ((c = reader.read()) != -1) {
        sb.append(String.valueOf((char) c));
    }

    reader.close();

    // Add the tag-stripped contents as a Reader-valued Text field so it will
    // get tokenized and indexed.
    StringBuilder sbFieldContent = new StringBuilder();
    StringBuilder sbFieldMetadata = new StringBuilder();
    sbFieldContent.append(page.getName()).append(" ").append(sb.toString());

    // Add the metadata description of the page if it exists
    if (page.getDescription() != null) {
        sbFieldContent.append(" ").append(page.getDescription());
    }

    // Add the metadata keywords of the page if it exists
    String strMetaKeywords = page.getMetaKeywords();

    if (StringUtils.isNotBlank(strMetaKeywords)) {
        sbFieldContent.append(" ").append(strMetaKeywords);
        sbFieldMetadata.append(strMetaKeywords);
    }

    doc.add(new Field(SearchItem.FIELD_CONTENTS, sbFieldContent.toString(), Field.Store.NO,
            Field.Index.ANALYZED));

    if (StringUtils.isNotBlank(page.getMetaDescription())) {
        if (sbFieldMetadata.length() > 0) {
            sbFieldMetadata.append(" ");
        }

        sbFieldMetadata.append(page.getMetaDescription());
    }

    if (sbFieldMetadata.length() > 0) {
        doc.add(new Field(SearchItem.FIELD_METADATA, sbFieldMetadata.toString(), Field.Store.NO,
                Field.Index.ANALYZED));
    }

    // Add the title as a separate Text field, so that it can be searched
    // separately.
    doc.add(new Field(SearchItem.FIELD_TITLE, page.getName(), Field.Store.YES, Field.Index.NO));

    if ((page.getDescription() != null) && (page.getDescription().length() > 1)) {
        // Add the summary as an UnIndexed field, so that it is stored and returned
        // with hit documents for display.
        doc.add(new Field(SearchItem.FIELD_SUMMARY, page.getDescription(), Field.Store.YES,
                Field.Index.ANALYZED));
    }

    doc.add(new Field(SearchItem.FIELD_TYPE, INDEX_TYPE_PAGE, Field.Store.YES, Field.Index.NOT_ANALYZED));
    doc.add(new Field(SearchItem.FIELD_ROLE, page.getRole(), Field.Store.YES, Field.Index.NOT_ANALYZED));

    // return the document
    return doc;
}

From source file:gdv.xport.satz.SatzTest.java

/**
 * Hier probieren wir jetzt 2 Saetze ueber einen Reader einzulesen.
 *
 * @throws IOException sollte eigenlich nicht passieren, da wir von einem
 *             String lesen/* www.  j av  a2s.c o m*/
 */
@Test
//@Ignore // Fehler ist noch nicht behoben
public void testImportFromReaderTwice() throws IOException {
    Satz x = new Datensatz(123, 7);
    Reader reader = new StringReader(INPUT_SATZ_123 + INPUT_SATZ_123);
    try {
        checkImport(x, reader);
        checkImport(x, reader);
    } finally {
        reader.close();
    }
}

From source file:com.manydesigns.elements.pdf.TableFormPdfExporter.java

public void export(OutputStream outputStream) throws FOPException, IOException, TransformerException {
    FopFactory fopFactory = FopFactory.newInstance();

    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream);

    // Setup XSLT
    TransformerFactory Factory = TransformerFactory.newInstance();
    Transformer transformer = Factory.newTransformer(xsltSource);

    // Set the value of a <param> in the stylesheet
    transformer.setParameter("versionParam", "2.0");

    // Setup input for XSLT transformation
    Reader reader = composeXml();
    Source src = new StreamSource(reader);

    // Resulting SAX events (the generated FO) must be piped through to
    // FOP//from ww  w.j a v  a2s.  c  o  m
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);
    reader.close();

    outputStream.flush();
}

From source file:net.sf.nmedit.jtheme.image.SVGImageResource.java

private static Image renderSVGImage(Reader source, int width, int height) {

    ImageTranscoder pngt = new PNGTranscoder();
    TranscoderInput input = new TranscoderInput(source);

    ByteArrayOutputStream out = new ByteArrayOutputStream(8096);

    try {//from   w w  w.j  a  v a  2s.  c  o m
        TranscoderOutput output = new TranscoderOutput(out);

        if (width > 0 && height > 0) {
            Float w = new Float(width);

            pngt.addTranscodingHint(PNGTranscoder.KEY_WIDTH, w);
            pngt.addTranscodingHint(PNGTranscoder.KEY_MAX_WIDTH, w);
            Float h = new Float(height);
            pngt.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, h);
            pngt.addTranscodingHint(PNGTranscoder.KEY_MAX_HEIGHT, h);
        }

        // TODO other solution for SAX parser / class loader issue ?
        Thread.currentThread().setContextClassLoader(ImageResource.class.getClassLoader());

        // Save the image.
        try {
            pngt.transcode(input, output);
        } catch (TranscoderException e) {
            Log log = LogFactory.getLog(ImageResource.class);
            if (log.isWarnEnabled()) {
                log.warn("could not render image", e);
            }
            return null;
        }
    } finally {
        try {
            source.close();
        } catch (IOException e) {
            Log log = LogFactory.getLog(ImageResource.class);
            if (log.isWarnEnabled()) {
                log.warn("could not close stream", e);
            }
        }
    }

    return Toolkit.getDefaultToolkit().createImage(out.toByteArray());

}