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:de.siemens.quantarch.bugs.IssueTrackerParser.java

/**
 * Parse the project specific configuration file provided in the command
 * line//from   w w  w . j ava2  s .  c  o m
 * 
 * @param projectConfigFile
 * @param config
 */
private static void parseProjectConfiguration(String projectConfigFile, BugExtractorConfig config)
        throws CommandLineArgsException {
    Reader projectFileReader = null;
    try {
        Yaml projectConfigYaml = new Yaml();
        projectFileReader = new FileReader(projectConfigFile);
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) projectConfigYaml.load(projectFileReader);
        // NOTE: project denotes the identifier name used in
        // the database, whereas bugsProject is the name
        // used for bugzilla.
        String project = (String) map.get("project");
        String bugsProject = (String) map.get("bugsProjectName");
        String issueTrackerType = (String) map.get("issueTrackerType");
        String issueTrackerURL = (String) map.get("issueTrackerURL");
        Boolean productAsProject = (Boolean) map.get("productAsProject");
        if (StringUtils.isBlankOrNull(project) || StringUtils.isBlankOrNull(bugsProject)
                || StringUtils.isBlankOrNull(issueTrackerURL) || StringUtils.isBlankOrNull(issueTrackerType)
                || null == productAsProject) {
            throw new CommandLineArgsException("Improper Project Configuration file supplied\n\n");
        }

        config.setIssueTrackerType(issueTrackerType);
        config.setIssueTrackerURL(issueTrackerURL);
        config.setProjectName(project);
        config.setBugsProjectName(bugsProject);
        config.setProductAsProject(productAsProject);
    } catch (FileNotFoundException e) {
        throw new CommandLineArgsException(
                "The global configuration file " + projectConfigFile + " does not exist");
    } finally {
        if (null != projectFileReader) {
            try {
                projectFileReader.close();
            } catch (final IOException ioe) {
                System.err.println("We got the following exception trying to clean up the reader: " + ioe);
            }
        }
    }
}

From source file:de.uzk.hki.da.sb.Cli.java

/**
 * Copies the files listed in a SIP list to a single directory
 * /* w w  w  .  j av a 2  s. com*/
 * @param fileListFile The SIP list file
 * @return The path to the directory containing the files
 */
private String copySipListContentToFolder(File sipListFile) {

    CliProgressManager progressManager = new CliProgressManager();

    String tempFolderName = getTempFolderName();

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        logger.log("ERROR: Failed to create SAX parser", e);
        System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden.");
        return "";
    }
    xmlReader.setErrorHandler(new ErrorHandler() {

        @Override
        public void error(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e);
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e);
        }

        @Override
        public void warning(SAXParseException e) throws SAXException {
            logger.log("WARNING: Warning while parsing siplist", e);
            System.out.println("\nWarnung:\n" + e.getMessage());
        }
    });

    InputStream inputStream;
    try {
        inputStream = new FileInputStream(sipListFile);

        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        Builder parser = new Builder(xmlReader);
        Document doc = parser.build(reader);
        reader.close();

        Element root = doc.getRootElement();
        Elements sipElements = root.getChildElements("sip");

        long files = 0;
        for (int i = 0; i < sipElements.size(); i++) {
            Elements fileElements = sipElements.get(i).getChildElements("file");
            if (fileElements != null)
                files += fileElements.size();
        }
        progressManager.setTotalSize(files);

        for (int i = 0; i < sipElements.size(); i++) {
            Element sipElement = sipElements.get(i);
            String sipName = sipElement.getAttributeValue("name");

            File tempDirectory = new File(tempFolderName + File.separator + sipName);
            if (tempDirectory.exists()) {
                FileUtils.deleteQuietly(new File(tempFolderName));
                System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". "
                        + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen.");
                return "";
            }
            tempDirectory.mkdirs();

            Elements fileElements = sipElement.getChildElements("file");

            for (int j = 0; j < fileElements.size(); j++) {
                Element fileElement = fileElements.get(j);
                String filepath = fileElement.getValue();

                File file = new File(filepath);
                if (!file.exists()) {
                    logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in siplist, "
                            + "but does not exist");
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " existiert nicht.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }

                try {
                    if (file.isDirectory())
                        FileUtils.copyDirectoryToDirectory(file, tempDirectory);
                    else
                        FileUtils.copyFileToDirectory(file, tempDirectory);
                    progressManager.copyFilesFromListProgress();
                } catch (IOException e) {
                    logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder "
                            + tempDirectory.getAbsolutePath(), e);
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " konnte nicht kopiert werden.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }
            }
        }
    } catch (Exception e) {
        logger.log("ERROR: Failed to read siplist " + sipListFile.getAbsolutePath(), e);
        System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. ");
        return "";
    }

    return (new File(tempFolderName).getAbsolutePath());
}

From source file:com.twistbyte.affiliate.HttpUtility.java

/**
 * Do a get request to the given url and set the header values passed
 *
 * @param url//  w w  w  .  j  a  va  2  s  . com
 * @param headerValues
 * @return
 */
public HttpResult doGet(String url, Map<String, String> headerValues) {

    String resp = "";

    logger.info("url : " + url);
    GetMethod method = new GetMethod(url);

    logger.info("Now use connection timeout: " + connectionTimeout);
    httpclient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);

    if (headerValues != null) {
        for (Map.Entry<String, String> entry : headerValues.entrySet()) {

            method.setRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResult serviceResult = new HttpResult();
    serviceResult.setSuccess(false);
    serviceResult.setHttpStatus(404);
    Reader reader = null;
    try {

        int result = httpclient.executeMethod(new HostConfiguration(), method, new HttpState());
        logger.info("http result : " + result);
        resp = method.getResponseBodyAsString();

        logger.info("response: " + resp);

        serviceResult.setHttpStatus(result);
        serviceResult.setBody(resp);
        serviceResult.setSuccess(200 == serviceResult.getHttpStatus());
    } catch (java.net.ConnectException ce) {
        logger.warn("ConnectException: " + ce.getMessage());
    } catch (IOException e) {
        logger.error("IOException sending request to " + url + " Reason:" + e.getMessage(), e);
    } finally {
        method.releaseConnection();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {

            }
        }
    }

    return serviceResult;
}

From source file:io.lightlink.output.JSONResponseStream.java

public void writeFromReader(Reader reader) {
    write('"');/*from  ww  w  .  j  a  v  a 2  s  . com*/
    char[] buffer = new char[16000];
    long count = 0;
    int n = 0;
    try {
        while (-1 != (n = reader.read(buffer))) {

            ByteBuffer bbuffer = CHARSET.encode(CharBuffer.wrap(buffer, 0, n));
            write(bbuffer.array(), bbuffer.remaining());

            count += n;
        }
        write('"');
        reader.close();
    } catch (IOException e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:com.advdb.footballclub.FootBallClub.java

private void createPlayer(Session session) {

    Transaction transaction = null;/*from   w  w w  .ja va  2 s.  c  o m*/
    try {
        System.out.println("start createPlayer.");
        transaction = session.beginTransaction();
        Reader in = new FileReader("/Users/apichart/Documents/DW_opponent/DimPlayer-Table 1.csv");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
        for (CSVRecord record : records) {
            String name = record.get(2);
            String nationality = record.get(3);
            String value = record.get(4);
            String height = record.get(6);
            String weight = record.get(7);
            DimPlayer d = new DimPlayer(name, nationality, Double.valueOf(value), Double.valueOf(height),
                    Double.valueOf(weight));
            session.save(d);
        }
        in.close();
        session.flush();
        session.clear();
        transaction.commit();

        System.out.println("finish createPlayer.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*from  w  ww  .  j a  va2  s . com*/
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        final URLConnection connectionCryptsy = URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

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

    return null;
}

From source file:cn.com.iscs.base.util.XMLProperties.java

/**
 * Builds the document XML model up based the given reader of XML data.
 * /*  www  .  j  a  v a 2 s  .c  om*/
 * @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) {
        System.err.print("Error reading XML properties");
        throw new IOException(e.getMessage());
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:fedora.server.storage.translation.AtomDODeserializer.java

private void addAuditDatastream(Entry entry) throws ObjectIntegrityException, StreamIOException {
    try {//from  w  ww.  jav a  2 s .  co m
        Reader auditTrail;
        if (m_format.equals(ATOM_ZIP1_1)) {
            File f = getContentSrcAsFile(entry.getContentSrc());
            auditTrail = new InputStreamReader(new FileInputStream(f), m_encoding);
        } else {
            auditTrail = new StringReader(entry.getContent());
        }
        m_obj.getAuditRecords().addAll(DOTranslationUtility.getAuditRecords(auditTrail));
        auditTrail.close();
    } catch (XMLStreamException e) {
        throw new ObjectIntegrityException(e.getMessage(), e);
    } catch (IOException e) {
        throw new StreamIOException(e.getMessage(), e);
    }
}

From source file:org.usrz.libs.webtools.resources.ServeResource.java

private Response produce(String path) throws Exception {

    /* Basic check for null/empty path */
    if ((path == null) || (path.length() == 0))
        return NOT_FOUND;

    /* Get our resource file, potentially a ".less" file for CSS */
    Resource resource = manager.getResource(path);
    if ((resource == null) && path.endsWith(".css")) {
        path = path.substring(0, path.length() - 4) + ".less";
        resource = manager.getResource(path);
    }//  ww  w .j a  va  2 s . c om

    /* If the root is incorrect, log this, if not found, 404 it! */
    if (resource == null)
        return NOT_FOUND;

    /* Ok, we have a resource on disk, this can be potentially long ... */
    final String fileName = resource.getFile().getName();

    /* Check and validated our cache */
    Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry);

    /* If we have no cache, we *might* want to cache something */
    if (cached == null) {

        /* What to do, what to do? */
        if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) {

            /* Lessify CSS and cache */
            xlog.debug("Lessifying resource \"%s\"", fileName);
            cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType);

        } else if (fileName.endsWith(".js") && minify) {

            /* Uglify JavaScript and cache */
            xlog.debug("Uglifying resource \"%s\"", fileName);
            cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify),
                    scriptMediaType);

        } else if (fileName.endsWith(".json")) {

            /* Strip comments and normalize JSON */
            xlog.debug("Normalizing JSON resource \"%s\"", fileName);

            /* All to do with Jackson */
            final Reader reader = resource.read();
            final StringWriter writer = new StringWriter();
            final JsonParser parser = json.createParser(reader);
            final JsonGenerator generator = json.createGenerator(writer);

            /* Not minifying? Means pretty printing! */
            if (!minify)
                generator.useDefaultPrettyPrinter();

            /* Get our schtuff through the pipeline */
            parser.nextToken();
            generator.copyCurrentStructure(parser);
            generator.flush();
            generator.close();
            reader.close();
            parser.close();

            /* Cached results... */
            cached = new Entry(resource, writer.toString(), jsonMediaType);

        }

        /* Do we have anything to cache? */
        if (cached != null) {
            xlog.debug("Caching resource \"%s\"", fileName);
            cache.put(resource, cached);
        }
    }

    /* Prepare our basic response from either cache or file */
    final ResponseBuilder response = Response.ok();
    if (cached != null) {

        /* Response from cache */
        xlog.trace("Serving cached resource \"%s\"", fileName);
        response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type);
    } else {

        /* Response from a file */
        xlog.trace("Serving file-based resource \"%s\"", fileName);

        /* If text/* or application/javascript, append encoding */
        MediaType type = MediaTypes.get(fileName);
        if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) {
            type = type.withCharset(charsetName);
        }

        /* Our file is served! */
        response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type);
    }

    /* Caching headers and build response */
    final Date expires = Date.from(Instant.now().plus(cacheDuration));
    return response.cacheControl(cacheControl).expires(expires).build();

}

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageImpl.java

/**
 * Load the namespaces file from the disk. It's easy to load into a
 * {@link Properties}, but we need to convert it to a {@link Map}.
 *///w  w w .  j  a  v a2 s  .com
private Map<Character, String> readNamespaces() throws IOException {
    Reader reader = null;
    try {
        reader = new FileReader(this.namespaceFile);
        Properties props = new Properties();
        props.load(reader);

        Map<Character, String> map = new HashMap<Character, String>();
        for (Object key : props.keySet()) {
            char keyChar = key.toString().charAt(0);
            map.put(keyChar, (String) props.get(key));
        }

        return map;
    } catch (Exception e) {
        throw new IOException("Problem loading the namespace file.");
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}