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.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

protected String readFile(String path) throws IOException {
    CharArrayWriter writer = null;
    InputStream in = null;//from w ww  .j  ava  2s.c o  m
    Reader reader = null;
    try {
        in = new FileInputStream(path);
        writer = new CharArrayWriter();
        reader = new InputStreamReader(in);
        char[] buffer = new char[8];
        int c = 0;
        while ((c = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, c);
        }
        return new String(writer.toCharArray());
    } catch (IOException ioex) {
        return null;
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (in != null) {
            in.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:it.geosolutions.geobatch.migrationmonitor.utils.DS2DSTokenResolver.java

private String loadOutputTemplate() throws IOException {

    StringWriter writer = null;//from w  ww  . j  ava 2  s .  c o  m
    InputStream is = null;
    Reader r = null;
    String output = null;
    try {
        is = getClass().getResourceAsStream("template.txt");
        r = new InputStreamReader(is);
        writer = new StringWriter();
        IOUtils.copy(is, writer);
        output = writer.toString();
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new IOException("Error while loading the DS2DSTemplate...");
    } finally {
        try {
            r.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            is.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            writer.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return output;
}

From source file:com.comcast.cqs.util.Util.java

public static String decompress(String compressed) throws IOException {
    if (compressed == null || compressed.equals("")) {
        return compressed;
    }/*from w  ww  .  j av  a 2s.  co  m*/
    Reader reader = null;
    StringWriter writer = null;
    try {
        if (!compressed.startsWith("H4sIA")) {
            String prefix = compressed;
            if (compressed.length() > 100) {
                prefix = prefix.substring(0, 99);
            }
            logger.warn("event=content_does_not_appear_to_be_zipped message=" + prefix);
            return compressed;
        }
        byte[] unencodedEncrypted = Base64.decodeBase64(compressed);
        ByteArrayInputStream in = new ByteArrayInputStream(unencodedEncrypted);
        GZIPInputStream gzip = new GZIPInputStream(in);
        reader = new InputStreamReader(gzip, "UTF-8");
        writer = new StringWriter();
        char[] buffer = new char[10240];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            writer.write(buffer, 0, length);
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    String decompressed = writer.toString();
    logger.info("event=decompressed from=" + compressed.length() + " to=" + decompressed.length());
    return decompressed;
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Load a configuration from a specified JSON file.
 * //from ww w  . j  ava 2s .  co  m
 * @param file
 * @return
 * @throws IOException
 */
private Configuration load(File file) throws IOException {
    if (file.getName().endsWith(".csv")) {
        return loadCsv(file);
    } else {
        Reader reader = new FileReader(file);
        Gson gson = new GsonBuilder().create();
        try {
            return gson.fromJson(reader, Configuration.class);
        } finally {
            reader.close();
        }
    }
}

From source file:com.pursuer.reader.easyrss.network.AbsDataSyncer.java

protected String parseContent(final Reader in) throws DataSyncerException {
    final StringBuilder builder = new StringBuilder();
    try {/*from  ww  w .  j a  v a  2 s  .co  m*/
        final char buff[] = new char[8192];
        int len;
        final BufferedReader reader = new BufferedReader(in, 8192);
        while ((len = reader.read(buff, 0, buff.length)) != -1) {
            builder.append(buff, 0, len);
        }
        return builder.toString();
    } catch (IOException e) {
        throw new DataSyncerException(e);
    } finally {
        try {
            in.close();
        } catch (final IOException exception) {
            exception.printStackTrace();
        }
    }
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }/*from www  . jav a 2 s  .com*/
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());
    boolean isKeyCol = false;

    boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, Element> keyCols = new TreeMap<String, Element>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];
            String colName = colNames[j];

            isKeyCol = (!noKey && keyField.contains(new Integer(j)));
            isNull = false;
            col = parser.createElementNS(doc, colName, NS);
            if (isKeyCol) {
                parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j));
            }
            switch (metadata.getColumnType(j)) {
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                isNull = dateVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat());
                        textVal = fF.formatDate(dateVal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                        textVal = dateFormatter.format(dateVal);
                    }
                }
            }
                break;
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                if (fF != null) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                    textVal = fF.formatNumber(numVal);
                } else {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                    textVal = numberFormatter.format(numVal);
                }
            }
                break;
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.NUMERIC:
            case Types.SMALLINT:
            case Types.TINYINT: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (isKeyCol) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyCols.put(String.valueOf(j), col);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS);
            data.appendChild(key);
            for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) {
                key.appendChild(keyColsEntry.getValue());
            }
            keyCols.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:com.hp.avmon.home.service.LicenseService.java

/**
 * ?servercpuID/*from  w w  w  .j av  a  2s.  c  o m*/
 * 
 * @return
 */
public String getServerCpuIdFromFile() {
    StringBuffer cpuidStrBf = new StringBuffer();
    // 
    callVbExeFile();
    // 

    String cpuidFullPath = getLicensePath() + "mycpuid.txt";

    File file = new File(cpuidFullPath);
    if (!file.exists()) {
        log.info("mycpuid is not exist!");
    }
    Reader reader = null;
    try {
        reader = new InputStreamReader(new FileInputStream(file));
        int buffer = 0;
        while ((buffer = reader.read()) != -1) {
            if ((char) buffer != '\n' && (char) buffer != '\r' && (char) buffer != ' ') {
                cpuidStrBf.append((char) buffer);
            }
        }
        reader.close();

    } catch (Exception e) {
        try {
            reader.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return cpuidStrBf.toString();
}

From source file:de.innovationgate.wga.server.api.Lucene.java

public List<String> bestFileFragments(int fragmentSize, int maxFragments, String prefix, String suffix,
        String encode) throws WGException {
    if (!_wga.getCore().isLuceneEnabled()) {
        _cx.addwarning("Unable to retrieve best file fragments - lucene is not enabled.");
        return Collections.emptyList();
    }//from  ww w .  ja  v  a2  s.c  om

    if (_wga.database().db().getContentStoreVersion() < WGDatabase.CSVERSION_WGA5
            || (_wga.database().db().getContentStoreVersion() == WGDatabase.CSVERSION_WGA5
                    && _wga.database().db().getContentStorePatchLevel() < 5)) {
        _cx.addwarning("bestFileFragments() is not supported on this content store version.");
        return Collections.emptyList();
    }

    org.apache.lucene.search.Query query = (org.apache.lucene.search.Query) _cx.gethttpsession()
            .getAttribute(Query.SESSION_ATTRIBUTE_SIMPLIFIED_LUCENEQUERY);
    if (query == null) {
        // no query in session
        return Collections.emptyList();
    }

    String filename = null;
    SearchDetails sd = _cx.getcontent().getSearchDetails();
    if (sd != null && sd instanceof LuceneSearchDetails) {
        filename = ((LuceneSearchDetails) sd).getFilename();
    }

    if (filename == null) {
        return Collections.emptyList();
    }

    if (encode == null) {
        encode = _wga.design().getTmlDefaultEncoding();
    }

    String prefixPlaceholder = "$HIGHLIGHT_PREFIX$";
    String suffixPlaceholder = "$HIGHLIGHT_SUFFIX$";
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(prefixPlaceholder, suffixPlaceholder);

    // create highlighter
    Highlighter highlighter = _wga.getCore().getLuceneManager()
            .createHighlighter(LuceneManager.INDEXFIELD_ALLCONTENT, query, formatter);

    // retrieve attachment text
    WGFileMetaData md = _cx.content().getFileMetaData(filename);
    if (md == null) {
        return Collections.emptyList();
    }

    BinaryFieldData textData = md.getPlainText();
    if (textData == null) {
        return Collections.emptyList();
    }

    try {
        // TODO highlighter does not support streams - should we limit plaintext size here?
        Reader textReader = new InputStreamReader(textData.getInputStream());
        String text = IOUtils.toString(textReader);
        textReader.close();

        // create tokenstream
        TokenStream tokenStream = _wga.getCore().getLuceneManager().createTokenStream(text, _cx.content());

        // create fragmenter
        Fragmenter fragmenter = new SimpleFragmenter(fragmentSize);
        highlighter.setTextFragmenter(fragmenter);

        String[] highlighted = highlighter.getBestFragments(tokenStream, text, maxFragments);
        if (highlighted != null) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < highlighted.length; i++) {
                String fragment = highlighted[i];
                if (encode != null) {
                    try {
                        fragment = _cx.multiencode(encode, fragment);
                    } catch (FormattingException e) {
                        _cx.addwarning("Unable to retrieve best fragments for file '" + filename
                                + "' bc. of formating exception '" + e.getMessage() + "'.");
                        return Collections.emptyList();
                    }
                }
                fragment = WGUtils.strReplace(fragment, prefixPlaceholder, prefix, true);
                fragment = WGUtils.strReplace(fragment, suffixPlaceholder, suffix, true);
                list.add(fragment);
            }
            return list;
        } else {
            return Collections.emptyList();
        }
    } catch (Exception e) {
        _cx.addwarning("Unable to retrieve best fragments for file '" + filename + "' bc. of exception '"
                + e.getMessage() + "'.");
        return Collections.emptyList();
    }
}

From source file:org.psikeds.knowledgebase.xml.impl.XSDValidator.java

/**
 * Validate XML against specified XSD schmema file.<br>
 * // w  ww.  j a  v  a2 s .  c om
 * @throws SAXException
 *           if XML is not valid against XSD
 * @throws IOException
 */
@Override
public void validate() throws SAXException, IOException {
    if (this.xsdStream != null && this.xmlStream != null) {
        validate(this.xsdStream, this.xmlStream);
        // Note: We do not close the streams here.
        // It's the responsibility of the caller
        return;
    }
    if (this.xsdResource != null && this.xmlResource != null) {
        validate(this.xsdResource, this.xmlResource);
        return;
    }
    if (!StringUtils.isEmpty(this.xsdFilename) && !StringUtils.isEmpty(this.xmlFilename)
            && !StringUtils.isEmpty(this.encoding)) {
        Reader xml = null;
        try {
            xml = new InputStreamReader(new FileInputStream(this.xmlFilename), this.encoding);
            validate(this.xsdFilename, xml);
            return;
        } finally {
            // We opened the file, therefore we also
            // must close the Reader/Stream again!
            if (xml != null) {
                try {
                    xml.close();
                } catch (final IOException ex) {
                    // ignore
                } finally {
                    xml = null;
                }
            }
        }
    }
    throw new IllegalArgumentException("Unsupported configuration settings!");
}

From source file:edu.uthscsa.ric.papaya.builder.Builder.java

public void compressJavaScript(final File inputFile, final File outputFile, final YuiCompressorOptions o)
        throws IOException {
    Reader in = null;
    Writer out = null;/*from   w ww.j a  va  2  s  . com*/
    try {
        in = new InputStreamReader(new FileInputStream(inputFile), o.charset);

        final JavaScriptCompressor compressor = new JavaScriptCompressor(in, new YuiCompressorErrorReporter());
        in.close();
        in = null;

        out = new OutputStreamWriter(new FileOutputStream(outputFile, true), o.charset);
        compressor.compress(out, o.lineBreakPos, o.munge, o.verbose, o.preserveAllSemiColons,
                o.disableOptimizations);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}