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.innovationgate.wgpublisher.plugins.WGAPlugin.java

public static Configuration loadConfiguration(File file, boolean full)
        throws FileNotFoundException, IOException, InvalidCSConfigVersionException {

    if (!file.exists()) {
        return null;
    }//from  ww  w .j a v a2s .co m

    file = WGUtils.resolveDirLink(file);

    DesignDefinition syncInfo = null;
    CSConfig csConfig = null;
    OverlayData overlayData = null;
    String licenseText = null;

    // Normal plugin file
    if (file.isFile()) {
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(file));
        try {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {

                String entryName = entry.getName();
                if (entryName.equals(DesignDirectory.DESIGN_DEFINITION_FILE)
                        || entryName.equals(DesignDirectory.SYNCINFO_FILE)) {
                    TemporaryFile tempFile = new TemporaryFile("design", zipIn, WGFactory.getTempDir());
                    syncInfo = DesignDefinition.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.CSCONFIG_PATH)) {
                    TemporaryFile tempFile = new TemporaryFile("csconfig", zipIn, WGFactory.getTempDir());
                    csConfig = CSConfig.load(tempFile.getFile());
                    tempFile.delete();
                } else if (entryName.equals(SystemContainerManager.LICENSE_PATH)) {
                    licenseText = WGUtils.readString(new InputStreamReader(zipIn, "UTF-8")).trim();
                } else if (entryName.equals(SystemContainerManager.OVERLAY_DATA_PATH)) {
                    try {
                        overlayData = OverlayData.read(zipIn);
                    } catch (Exception e) {
                        Logger.getLogger("wga.plugins").error(
                                "Exception reading overlay data from plugin file " + file.getAbsolutePath(), e);
                    }
                }

                if (syncInfo != null && csConfig != null) {
                    if (!full || overlayData != null) {
                        break;
                    }
                }
            }
        } finally {
            zipIn.close();
        }
    }

    // Developer plugin folder
    else {
        File syncInfoFile = DesignDirectory.getDesignDefinitionFile(file);
        if (syncInfoFile.exists()) {
            syncInfo = DesignDefinition.load(syncInfoFile);
        }
        File csConfigFile = new File(file, SystemContainerManager.CSCONFIG_PATH);
        if (csConfigFile.exists()) {
            csConfig = CSConfig.load(csConfigFile);
        }
        File licenseTextFile = new File(file, SystemContainerManager.LICENSE_PATH);
        if (licenseTextFile.exists()) {
            Reader reader = new InputStreamReader(new FileInputStream(licenseTextFile), "UTF-8");
            licenseText = WGUtils.readString(reader).trim();
            reader.close();
        }
        File overlayDataFile = new File(file, SystemContainerManager.OVERLAY_DATA_PATH);
        if (overlayDataFile.exists()) {
            try {
                InputStream stream = new FileInputStream(overlayDataFile);
                overlayData = OverlayData.read(stream);
                stream.close();
            } catch (Exception e) {
                Logger.getLogger("wga.plugins").error(
                        "Exception reading overlay data from plugin directory " + file.getAbsolutePath(), e);
            }
        }

    }

    if (syncInfo != null && csConfig != null && csConfig.getPluginConfig() != null) {
        return new Configuration(syncInfo, csConfig, licenseText, overlayData);
    } else {
        return null;
    }

}

From source file:io.github.jeddict.jcode.util.FileUtil.java

public static void expandTemplate(Reader reader, Writer writer, Map<String, Object> values,
        Charset targetEncoding) throws IOException {
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);//  ww  w.j a v a2  s.c  o  m
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    try {
        eng.getContext().setWriter(writer);
        eng.eval(reader);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.cloudera.sqoop.testutil.SeqFileReader.java

public static Object getFirstValue(String filename) throws IOException {
    Reader r = null;
    try {/*from  w  w w  . ja  va 2  s.c  om*/
        // read from local filesystem
        Configuration conf = new Configuration();
        if (!BaseSqoopTestCase.isOnPhysicalCluster()) {
            conf.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS);
        }
        FileSystem fs = FileSystem.get(conf);
        r = new SequenceFile.Reader(fs, new Path(filename), conf);
        Object key = ReflectionUtils.newInstance(r.getKeyClass(), conf);
        Object val = ReflectionUtils.newInstance(r.getValueClass(), conf);
        LOG.info("Reading value of type " + r.getValueClassName() + " from SequenceFile " + filename);
        r.next(key);
        r.getCurrentValue(val);
        LOG.info("Value as string: " + val.toString());
        return val;
    } finally {
        if (null != r) {
            try {
                r.close();
            } catch (IOException ioe) {
                LOG.warn("IOException during close: " + ioe.toString());
            }
        }
    }
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static JsonElement parseResponse(@NotNull InputStream githubResponse) throws IOException {
    Reader reader = new InputStreamReader(githubResponse);
    try {/*from  w ww. j a  v  a 2  s .  c  o m*/
        return new JsonParser().parse(reader);
    } catch (JsonSyntaxException jse) {
        throw new GithubJsonException("Couldn't parse GitHub response", jse);
    } finally {
        reader.close();
    }
}

From source file:au.org.ala.bhl.command.ImportItemsCommand.java

/**
 * Work horse. Reads each line of the CSV file, and creates an Item Descriptor. If the item descriptor is accepted by the filter (by default all items will be
 * accepted), the item is imported into the database.
 * @param options// w w w .  j  a  va 2s  . c  o  m
 * @param handler
 * @param filter
 * @throws Exception
 */
private static void processItemsFile(final IndexerOptions options, ItemsFileHandler handler,
        ItemDescriptorFilter filter) throws Exception {
    String sourceFile = options.getSourceFilename();
    File f = new File(sourceFile);
    if (f.exists()) {
        FileInputStream fis = new FileInputStream(f);
        Reader filereader = new InputStreamReader(fis, "ISO-8859-1");
        CSVReader reader = new CSVReader(filereader, ',', '"', 1);
        String[] nextLine;
        try {
            while ((nextLine = reader.readNext()) != null) {
                ItemDescriptor item = new ItemDescriptor(nextLine[0], nextLine[1], nextLine[2], nextLine[3],
                        nextLine[4]);
                if (filter == null || filter.accept(item)) {
                    LogService.log(ImportItemsCommand.class, "Including item %s", item.getInternetArchiveId());
                    if (handler != null) {
                        handler.onItem(item);
                    }
                }
            }
        } finally {
            reader.close();
            filereader.close();
            fis.close();
        }

    } else {
        throw new RuntimeException("File not found! " + sourceFile);
    }

}

From source file:dk.clarin.tools.workflow.java

/**
* Sends an HTTP GET request to a url/* www . ja v  a2s  .c o  m*/
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestString - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/

public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat,
        String filename, String jobID, boolean postmethod) {
    int code = 0;
    String message = "";
    //String filelist;
    if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
        // Send a GET or POST request to the servlet
        try {
            // Construct data
            String requestResult = "";
            String urlStr = endpoint;
            if (postmethod) // HTTP POST
            {
                logger.debug("HTTP POST");
                StringReader input = new StringReader(requestString);
                StringWriter output = new StringWriter();
                URL endp = new URL(endpoint);

                HttpURLConnection urlc = null;
                try {
                    urlc = (HttpURLConnection) endp.openConnection();
                    try {
                        urlc.setRequestMethod("POST");
                    } catch (ProtocolException e) {
                        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
                    }
                    urlc.setDoOutput(true);
                    urlc.setDoInput(true);
                    urlc.setUseCaches(false);
                    urlc.setAllowUserInteraction(false);
                    urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

                    OutputStream out = urlc.getOutputStream();

                    try {
                        Writer writer = new OutputStreamWriter(out, "UTF-8");
                        pipe(input, writer);
                        writer.close();
                    } catch (IOException e) {
                        throw new Exception("IOException while posting data", e);
                    } finally {
                        if (out != null)
                            out.close();
                    }
                } catch (IOException e) {
                    throw new Exception("Connection error (is server running at " + endp + " ?): " + e);
                } finally {
                    if (urlc != null) {
                        code = urlc.getResponseCode();

                        if (code == 200) {
                            got200(result, BracMat, filename, jobID, urlc.getInputStream());
                        } else {
                            InputStream in = urlc.getInputStream();
                            try {
                                Reader reader = new InputStreamReader(in);
                                pipe(reader, output);
                                reader.close();
                                requestResult = output.toString();
                            } catch (IOException e) {
                                throw new Exception("IOException while reading response", e);
                            } finally {
                                if (in != null)
                                    in.close();
                            }
                            logger.debug("urlc.getResponseCode() == {}", code);
                            message = urlc.getResponseMessage();
                            didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                    postmethod, urlStr, message, requestResult);
                        }
                        urlc.disconnect();
                    } else {
                        code = 0;
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                }
                //requestResult = output.toString();
                logger.debug("postData returns " + requestResult);
            } else // HTTP GET
            {
                logger.debug("HTTP GET");
                // Send data

                if (requestString != null && requestString.length() > 0) {
                    urlStr += "?" + requestString;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                conn.connect();

                // Cast to a HttpURLConnection
                if (conn instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) conn;
                    code = httpConnection.getResponseCode();
                    logger.debug("httpConnection.getResponseCode() == {}", code);
                    message = httpConnection.getResponseMessage();
                    BufferedReader rd;
                    StringBuilder sb = new StringBuilder();
                    ;
                    //String line;
                    if (code == 200) {
                        got200(result, BracMat, filename, jobID, httpConnection.getInputStream());
                    } else {
                        // Get the error response
                        rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
                        int nextChar;
                        while ((nextChar = rd.read()) != -1) {
                            sb.append((char) nextChar);
                        }
                        rd.close();
                        requestResult = sb.toString();
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                } else {
                    code = 0;
                    didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod,
                            urlStr, message, requestResult);
                }
            }
            logger.debug("Job " + jobID + " receives status code [" + code + "] from tool.");
        } catch (Exception e) {
            //jobs = 0; // No more jobs to process now, probably the tool is not reachable
            logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage());
            /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
        }
    } else {
        //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all
        logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint
                + ")");
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
    return code;
}

From source file:com.heliosapm.benchmarks.json.JSONUnmarshalling.java

/**
 * Deserializes a JSON formatted string to a specific class type
 * <b>Note:</b> If you get mapping exceptions you may need to provide a 
 * TypeReference/*from   w  w w. j  av  a 2s .  co  m*/
 * @param json The string to deserialize
 * @param pojo The class type of the object used for deserialization
 * @return An object of the {@code pojo} type
 * @throws IllegalArgumentException if the data or class was null or parsing 
 * failed
 */
public static final <T> T parseToObject(final ChannelBuffer json, final Class<T> pojo) {
    if (json == null || json.readableBytes() < 2)
        throw new IllegalArgumentException("Incoming data was null or empty");
    if (pojo == null)
        throw new IllegalArgumentException("Missing class type");
    InputStream i = null;
    Reader r = null;
    try {
        i = new ChannelBufferInputStream(json);
        r = new InputStreamReader(i);
        return jsonMapper.readValue(r, pojo);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (r != null)
            try {
                r.close();
            } catch (Exception x) {
                /* No Op */}
        if (i != null)
            try {
                i.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:com.heliosapm.benchmarks.json.JSONUnmarshalling.java

public static Person[] deserPersons(final ChannelBuffer buff) {
    InputStream is = null;/* www  .j a  va2s  . com*/
    Reader ros = null;
    try {
        is = new ChannelBufferInputStream(buff);
        ros = new InputStreamReader(is, UTF8);
        return jsonMapper.readValue(ros, Person[].class);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (ros != null)
            try {
                ros.close();
            } catch (Exception x) {
                /* No Op */}
        if (is != null)
            try {
                is.close();
            } catch (Exception x) {
                /* No Op */}
        buff.resetReaderIndex();
    }
}

From source file:com.acciente.commons.htmlform.Parser.java

private static Map parsePOSTMultiPart(HttpServletRequest oRequest, int iStoreFileOnDiskThresholdInBytes,
        File oUploadedFileStorageDir) throws FileUploadException, IOException, ParserException {
    Map oMultipartParams = new HashMap();

    // we have multi-part content, we process it with apache-commons-fileupload

    ServletFileUpload oMultipartParser = new ServletFileUpload(
            new DiskFileItemFactory(iStoreFileOnDiskThresholdInBytes, oUploadedFileStorageDir));

    List oFileItemList = oMultipartParser.parseRequest(oRequest);

    for (Iterator oIter = oFileItemList.iterator(); oIter.hasNext();) {
        FileItem oFileItem = (FileItem) oIter.next();

        // we support the variable name to use the full syntax allowed in non-multipart forms
        // so we use parseParameterSpec() to support array and map variable syntaxes in multi-part mode
        Reader oParamNameReader = null;
        ParameterSpec oParameterSpec = null;

        try {/*from ww  w .  j ava2 s.co  m*/
            oParamNameReader = new StringReader(oFileItem.getFieldName());

            oParameterSpec = Parser.parseParameterSpec(oParamNameReader,
                    oFileItem.isFormField() ? Symbols.TOKEN_VARTYPE_STRING : Symbols.TOKEN_VARTYPE_FILE);
        } finally {
            if (oParamNameReader != null) {
                oParamNameReader.close();
            }
        }

        if (oFileItem.isFormField()) {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem.getString(), false);
        } else {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem);
        }
    }

    return oMultipartParams;
}

From source file:com.zimbra.common.util.ByteUtil.java

/**
 * Closes the given reader and ignores any exceptions.
 * @param r the <tt>Reader</tt>, may be <tt>null</tt>
 *//*from   w w  w . j  a v a2s .  c o m*/
public static void closeReader(Reader r) {
    if (r == null) {
        return;
    }
    try {
        r.close();
    } catch (IOException e) {
        ZimbraLog.misc.debug("ignoring exception while closing reader", e);
    }
}