Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.apache.hadoop.hive.ql.QTestUtil.java

public String readEntireFileIntoString(File queryFile) throws IOException {
    InputStreamReader isr = new InputStreamReader(new BufferedInputStream(new FileInputStream(queryFile)),
            QTestUtil.UTF_8);//from   w ww.  ja v a 2 s. co m
    StringWriter sw = new StringWriter();
    try {
        IOUtils.copy(isr, sw);
    } finally {
        if (isr != null) {
            isr.close();
        }
    }
    return sw.toString();
}

From source file:uk.co.matbooth.calameo.impl.CalameoClientImpl.java

/**
 * Internal method that actually does the work of making the request to Calamo and
 * parsing the response.//  ww  w. ja v a2s  . com
 * 
 * @param responseType
 *          the class of type T that the response is expected to be
 * @param params
 *          a map of key/value pairs to be sent to Calamo as query parameters
 * @return the response object of type T, whose class was specified in the responseType
 *         argument
 * @throws CalameoException
 *           if there was an error communicating with Calamo
 */
private <T extends Response<?>> T executeRequest(final Class<T> responseType, final Map<String, String> params)
        throws CalameoException {
    HttpClient client = null;
    HttpGet get = null;
    InputStreamReader entity = null;
    try {
        // Generate signed params
        Map<String, String> p = new HashMap<String, String>(params);
        p.put("apikey", getConfig().getKey());
        p.put("expires", Long.toString(new Date().getTime() + getConfig().getExpires()));
        p.put("output", "JSON");
        p.put("subscription_id", getConfig().getSubscription());
        Set<String> keys = new TreeSet<String>(p.keySet());
        StringBuilder input = new StringBuilder(getConfig().getSecret());
        for (String key : keys) {
            input.append(key);
            input.append(p.get(key));
        }
        p.put("signature", DigestUtils.md5Hex(input.toString()));
        // Configure HTTP client
        client = new DefaultHttpClient();
        // Configure GET request
        URIBuilder uri = new URIBuilder(getConfig().getEndpoint());
        for (String key : p.keySet()) {
            uri.addParameter(key, p.get(key));
        }
        get = new HttpGet(uri.build());
        log.debug("Request URI: " + get.getURI());
        // Execute request and parse response
        HttpResponse response = client.execute(get);
        entity = new InputStreamReader(response.getEntity().getContent());
        JsonElement parsed = new JsonParser().parse(entity);
        JsonElement responseJson = parsed.getAsJsonObject().get("response");
        T r = new Gson().fromJson(responseJson, responseType);
        log.debug("Response Object: " + r);
        // Return response or throw an error
        if ("error".equals(r.getStatus())) {
            CalameoException e = new CalameoException(r.getError().getCode(), r.getError().getMessage());
            log.error(e.getMessage());
            throw e;
        } else {
            return r;
        }
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } catch (URISyntaxException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } catch (JsonParseException e) {
        log.error(e.getMessage());
        throw new CalameoException(e);
    } finally {
        if (entity != null) {
            try {
                entity.close();
            } catch (IOException e) {
                log.warn(e.getMessage());
            }
        }
        if (get != null) {
            get.releaseConnection();
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
}

From source file:org.talend.mdm.workbench.serverexplorer.console.MDMServerMessageConsole.java

private void doMonitor() {

    String monitorURL = buildMonitorURL(position);

    MessageConsoleStream errorMsgStream = newErrorMessageStream();
    InputStream is = null;//w ww  .ja va 2  s.c o m
    BufferedReader br = null;
    MessageConsoleStream msgStream = null;
    InputStreamReader isr = null;
    try {
        HttpResponse response = executeByHttpget(monitorURL, serverDef.getUser(), serverDef.getPasswd());
        int code = response.getStatusLine().getStatusCode();
        if (HTTP_STATUS_OK == code) {
            modifyChunkedPosition(response);
            if (isEndOfChunk(response)) {
                return;
            }
            is = response.getEntity().getContent();
            msgStream = newMessageStream();

            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                msgStream.println(line);
            }
        } else {

            if (HTTP_STATUS_NO_ACCESS == code) {
                errorMsgStream.println(Messages.MDMServerMessageConsole_No_Acess_Message);
                disposeTimer();
            } else if (HTTP_STSTUS_FORBIDDEN == code) {
                errorMsgStream.println(Messages.MDMServerMessageConsole_Forbidden_Message);
                disposeTimer();
            } else if (HTTP_STATUS_NOT_FOUND == code) {
                errorMsgStream.println(Messages.MDMServerMessageConsole_NotConnected_Message);
                disposeTimer();
            }
        }
    } catch (HttpHostConnectException ex) {
        errorMsgStream.println(ex.getMessage());
        disposeTimer();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        errorMsgStream.println(e.getMessage());
        disposeTimer();
    } catch (SecurityException e) {
        errorMsgStream.println(e.getMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (msgStream != null) {
            try {
                msgStream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (errorMsgStream != null) {
            try {
                errorMsgStream.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:org.apache.hadoop.util.SysInfoLinux.java

/**
 * Read /proc/meminfo, parse and compute memory information.
 * @param readAgain if false, read only on the first time
 *//* w  w w  .  j a  va 2s.c  o m*/
private void readProcMemInfoFile(boolean readAgain) {

    if (readMemInfoFile && !readAgain) {
        return;
    }

    // Read "/proc/memInfo" file
    BufferedReader in;
    InputStreamReader fReader;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsMemFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        LOG.warn("Couldn't read " + procfsMemFile + "; can't determine memory settings");
        return;
    }

    Matcher mat;

    try {
        String str = in.readLine();
        while (str != null) {
            mat = PROCFS_MEMFILE_FORMAT.matcher(str);
            if (mat.find()) {
                if (mat.group(1).equals(MEMTOTAL_STRING)) {
                    ramSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPTOTAL_STRING)) {
                    swapSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(MEMFREE_STRING)) {
                    ramSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPFREE_STRING)) {
                    swapSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(INACTIVE_STRING)) {
                    inactiveSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(INACTIVEFILE_STRING)) {
                    inactiveFileSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(HARDWARECORRUPTED_STRING)) {
                    hardwareCorruptSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(HUGEPAGESTOTAL_STRING)) {
                    hugePagesTotal = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(HUGEPAGESIZE_STRING)) {
                    hugePageSize = Long.parseLong(mat.group(2));
                }
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    readMemInfoFile = true;
}

From source file:rb.app.GLObject.java

public void read_offline_data(String directory_name, boolean isAssetFile) throws IOException {

    HttpClient client = new DefaultHttpClient();
    int buffer_size = 8192;

    // Read in output data
    InputStreamReader isr;
    String dataString = directory_name + "/geometry.dat";

    if (!isAssetFile) {
        HttpGet request = new HttpGet(dataString);
        HttpResponse response = client.execute(request);
        isr = new InputStreamReader(response.getEntity().getContent());
    } else { // Read from assets
        isr = new InputStreamReader(context.getAssets().open(dataString));
    }/*from   ww  w.  j  ava2s. c o  m*/
    BufferedReader reader = new BufferedReader(isr, buffer_size);

    String line = reader.readLine();
    String[] tokens = line.split(" ");

    node_num = Integer.parseInt(tokens[0]);
    int count = 1;
    ref_node = new float[node_num * 3];
    node = new float[node_num * 3];
    sol = new float[field_num][node_num];
    ucolor = new float[field_num][node_num * 4];
    for (int i = 0; i < node_num; i++) {
        ref_node[i * 3 + 0] = Float.parseFloat(tokens[count]);
        ref_node[i * 3 + 1] = Float.parseFloat(tokens[count + 1]);
        ref_node[i * 3 + 2] = Float.parseFloat(tokens[count + 2]);
        count += 3;
        node[i * 3 + 0] = ref_node[i * 3 + 0];
        node[i * 3 + 1] = ref_node[i * 3 + 1];
        node[i * 3 + 2] = ref_node[i * 3 + 2];
    }
    cal_boxsize();

    reg_num = Integer.parseInt(tokens[count]);
    face_num = Integer.parseInt(tokens[count + 1]);
    count += 2;
    face = new short[face_num * 3];
    for (int i = 0; i < face_num; i++) {
        face[i * 3 + 0] = Short.parseShort(tokens[count]);
        face[i * 3 + 1] = Short.parseShort(tokens[count + 1]);
        face[i * 3 + 2] = Short.parseShort(tokens[count + 2]);
        count += 3;
    }
    node_reg = new int[node_num];
    for (int i = 0; i < node_num; i++) {
        node_reg[i] = Integer.parseInt(tokens[count]);
        count++;
    }
    face_dom = new int[face_num];
    for (int i = 0; i < face_num; i++) {
        face_dom[i] = Integer.parseInt(tokens[count]);
        count++;
    }
    isr.close();

    // Create a wireframe list (edge data)
    face_wf = new short[face_num * 3 * 2];
    for (int i = 0; i < face_num; i++) {
        face_wf[i * 6 + 0 * 2 + 0] = face[i * 3 + 0];
        face_wf[i * 6 + 0 * 2 + 1] = face[i * 3 + 1];
        face_wf[i * 6 + 1 * 2 + 0] = face[i * 3 + 1];
        face_wf[i * 6 + 1 * 2 + 1] = face[i * 3 + 2];
        face_wf[i * 6 + 2 * 2 + 0] = face[i * 3 + 2];
        face_wf[i * 6 + 2 * 2 + 1] = face[i * 3 + 0];
    }

    if (!is2D())
        cal_normal_data();
}

From source file:ch.njol.skript.Updater.java

/**
 * Gets the changelogs and release dates of the newest versions
 * /*from  w  ww  .  j a  v a  2s .  com*/
 * @param sender
 */
final static void getChangelogs(final CommandSender sender) {
    InputStream in = null;
    InputStreamReader r = null;
    try {
        final URLConnection conn = new URL(RSSURL).openConnection();
        conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); // Bukkit returns a 403 (forbidden) if no user agent is set
        in = conn.getInputStream();
        r = new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding());
        final XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(r);

        infos.clear();
        VersionInfo current = null;

        outer: while (reader.hasNext()) {
            XMLEvent e = reader.nextEvent();
            if (e.isStartElement()) {
                final String element = e.asStartElement().getName().getLocalPart();
                if (element.equalsIgnoreCase("title")) {
                    final String name = reader.nextEvent().asCharacters().getData().trim();
                    for (final VersionInfo i : infos) {
                        if (name.equals(i.name)) {
                            current = i;
                            continue outer;
                        }
                    }
                    current = null;
                } else if (element.equalsIgnoreCase("description")) {
                    if (current == null)
                        continue;
                    final StringBuilder cl = new StringBuilder();
                    while ((e = reader.nextEvent()).isCharacters())
                        cl.append(e.asCharacters().getData());
                    current.changelog = "- " + StringEscapeUtils.unescapeHtml("" + cl).replace("<br>", "")
                            .replace("<p>", "").replace("</p>", "").replaceAll("\n(?!\n)", "\n- ");
                } else if (element.equalsIgnoreCase("pubDate")) {
                    if (current == null)
                        continue;
                    synchronized (RFC2822) { // to make FindBugs shut up
                        current.date = new Date(
                                RFC2822.parse(reader.nextEvent().asCharacters().getData()).getTime());
                    }
                }
            }
        }
    } catch (final IOException e) {
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(ExceptionUtils.toString(e));
            Skript.error(sender, m_check_error.toString());
        } finally {
            stateLock.writeLock().unlock();
        }
    } catch (final Exception e) {
        Skript.error(sender, m_internal_error.toString());
        Skript.exception(e, "Unexpected error while checking for a new version of Skript");
        stateLock.writeLock().lock();
        try {
            state = UpdateState.CHECK_ERROR;
            error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
        } finally {
            stateLock.writeLock().unlock();
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
        if (r != null) {
            try {
                r.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException {
    String resourceBundleName = module.getResourceBundleName();
    if (resourceBundleName == null) {
        resourceBundleName = "resources." + module.getId();
    }/*  w  w  w  .  j  ava 2s  .c  o m*/
    String rbBasePath = "/src/main/resources/resources/"
            + StringUtils.substringAfterLast(resourceBundleName, ".");
    Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties();
    if (i18nProperties != null) {
        List<File> newFiles = new ArrayList<File>();
        for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) {
            String lang = entry.getKey();
            Map<String, String[]> properties = entry.getValue();

            String[] values = properties.get(Constants.JCR_TITLE);
            String title = ArrayUtils.isEmpty(values) ? null : values[0];

            values = properties.get(Constants.JCR_DESCRIPTION);
            String description = ArrayUtils.isEmpty(values) ? null : values[0];

            String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION;
            InputStream is = null;
            InputStreamReader isr = null;
            OutputStream os = null;
            OutputStreamWriter osw = null;
            try {
                FileObject file = getFile(rbPath);
                FileContent content = file.getContent();
                Properties p = new SortedProperties();
                if (file.exists()) {
                    is = content.getInputStream();
                    isr = new InputStreamReader(is, Charsets.ISO_8859_1);
                    p.load(isr);
                    isr.close();
                    is.close();
                } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) {
                    continue;
                } else {
                    newFiles.add(new File(file.getName().getPath()));
                }
                if (!StringUtils.isEmpty(title)) {
                    p.setProperty(key, title);
                }
                if (!StringUtils.isEmpty(description)) {
                    p.setProperty(key + "_description", description);
                }
                os = content.getOutputStream();
                osw = new OutputStreamWriter(os, Charsets.ISO_8859_1);
                p.store(osw, rbPath);
                ResourceBundle.clearCache();
            } catch (FileSystemException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } catch (IOException e) {
                logger.error("Failed to save resourceBundle", e);
                throw new RepositoryException("Failed to save resourceBundle", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(osw);
            }
        }
        SourceControlManagement sourceControl = module.getSourceControl();
        if (sourceControl != null) {
            try {
                sourceControl.add(newFiles);
            } catch (IOException e) {
                logger.error("Failed to add files to source control", e);
                throw new RepositoryException("Failed to add new files to source control: " + newFiles, e);
            }
        }
    }
}

From source file:com.interacciones.mxcashmarketdata.driver.process.DriverServerHandler.java

@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    LOGGER.debug("Received : " + message);
    IoBuffer ib = (IoBuffer) message;/*w  ww.j  a  v  a 2 s .com*/
    try {
        InputStream is = ib.asInputStream();
        /**
         * We have to create them b/c they are needed as arguments in the constructors.
         */
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        long time = System.currentTimeMillis();
        int data = br.read();
        int count = 1;

        while (data != -1) {
            char theChar = (char) data;
            strbuf.append(theChar);
            count++;

            if (data == 13) {
                count = 0;
                long tmpSequence = 0;
                String strSequence;

                strbuf.deleteCharAt(strbuf.length() - 1);
                int sizestrbuf = strbuf.length();
                try {
                    //Message reader, Sequence number
                    strSequence = strbuf.substring(sizestrbuf - MSG_LENGTH, sizestrbuf - MSG_SEQUENCE);
                    tmpSequence = Long.parseLong(strSequence);

                    if (myMsgSequence == tmpSequence) {
                        myMsgSequence = countSequence.next();
                        /**
                         * Sending message File, OpenMama, Queuing
                         * Implement Interface MessageProcessing
                         */
                        messageProcessing.receive(
                                strbuf.toString().substring(sizestrbuf - MSG_LENGTH, sizestrbuf), tmpSequence);
                        flagRetransmission = true;
                    } else if (flagRetransmission) {
                        System.out.print(
                                "\r[" + df.format(new Date()) + "] Sequence retransmission: " + myMsgSequence);
                        MessageRetransmission msgRetra = new MessageRetransmission();
                        msgRetra.setSequencelong(myMsgSequence);
                        msgRetra.MsgConstruct();
                        IoBuffer io = IoBuffer.wrap(msgRetra.getByte());
                        LOGGER.info("Sequence Retransmission " + myMsgSequence);
                        LOGGER.debug(msgRetra.toString());
                        session.write(io.duplicate());
                        flagRetransmission = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.error("Error: " + e.getMessage());
                    LOGGER.error(strbuf.toString());
                }
                strbuf.delete(0, strbuf.length()); //What's more expensive? delete or read the object.
            }
            data = br.read();
        }
        time = System.currentTimeMillis() - time;
        globlaCount = globlaCount + time;
        isr.close();
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}