Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

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

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:com.cubusmail.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {// ww w.j av  a2  s.com
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from   ww  w.j ava  2s.c om
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.bankinterface.config.JsonBankConfig.java

/**
 * ??//from  ww w.  j  a v  a2  s . com
 * 
 * @param configName
 * @return
 * @throws IOException
 */
private String getContent(String configName) throws IOException {
    InputStreamReader in = null;
    String content = null;
    try {
        in = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(configName), "UTF-8");
        StringWriter out = new StringWriter();
        int n = 0;
        char[] buffer = new char[4096];
        while (-1 != (n = in.read(buffer))) {
            out.write(buffer, 0, n);
        }
        content = out.toString();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return content;
}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

public void validate() throws SearchException {
    THROTTLER.throttle();//from  w  w w.j  av  a 2s . c  om
    InputStreamReader isr = null;
    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("action", "getnzb"));
        params.add(new BasicNameValuePair("nzbid", "" + 0));
        URI uri = getUri("index.php", params);
        isr = new InputStreamReader((InputStream) uri.toURL().getContent());

        char[] buffer = new char[BUFFSIZE];
        int numRead;
        int trueCount = 0;
        int falseCount = 0;
        while ((numRead = isr.read(buffer)) > 0) {
            for (int c = 0; c < numRead; c++) {
                if (buffer[c] == VALID_STRING.charAt(trueCount)) {
                    trueCount++;
                } else {
                    trueCount = 0;
                }
                if (trueCount == VALID_STRING.length())
                    return;
                if (buffer[c] == INVALID_STRING.charAt(falseCount)) {
                    falseCount++;
                } else {
                    falseCount = 0;
                }
                if (falseCount == INVALID_STRING.length()) {
                    throw new SearchException("Invalid credentials.");
                }
            }
        }
        throw new SearchException("Unable to determine validity.");
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    } finally {
        THROTTLER.setThrottleForNextAction();
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                /* dan niet */
            }
        }
    }
}

From source file:org.apache.struts2.dispatcher.PlainTextResult.java

protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {

    // verify charset
    Charset charset = null;/*from w  w  w.  j av a  2  s  .co  m*/
    if (charSet != null) {
        if (Charset.isSupported(charSet)) {
            charset = Charset.forName(charSet);
        } else {
            _log.warn("charset [" + charSet + "] is not recognized ");
            charset = null;
        }
    }

    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);
    ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(SERVLET_CONTEXT);

    if (charset != null) {
        response.setContentType("text/plain; charset=" + charSet);
    } else {
        response.setContentType("text/plain");
    }
    response.setHeader("Content-Disposition", "inline");

    PrintWriter writer = response.getWriter();
    InputStreamReader reader = null;
    try {
        if (charset != null) {
            reader = new InputStreamReader(servletContext.getResourceAsStream(finalLocation), charset);
        } else {
            reader = new InputStreamReader(servletContext.getResourceAsStream(finalLocation));
        }
        if (reader == null) {
            _log.warn("resource at location [" + finalLocation
                    + "] cannot be obtained (return null) from ServletContext !!! ");
        } else {
            char[] buffer = new char[BUFFER_SIZE];
            int charRead = 0;
            while ((charRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, charRead);
            }
        }
    } finally {
        if (reader != null)
            reader.close();
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}

From source file:org.bremersee.sms.GoyyaSmsService.java

@Override
public SmsSendResponseDto doSendSms(final SmsSendRequestDto smsSendRequest) throws SmsException {

    final String sender = getSender(smsSendRequest);

    final String receiver = getReceiver(smsSendRequest);

    final String message = getMessage(smsSendRequest);

    final String messageType = getMessageType(message);

    final String time = createSendTime(smsSendRequest.getSendTime());

    final Charset charset = createCharset();

    String url = new String(this.url);

    url = WebUtils.addUrlParameter(url, GATEWAY_USER_ID_KEY, username, charset);
    url = WebUtils.addUrlParameter(url, GATEWAY_USER_PASSWORD_KEY, password, charset);
    url = WebUtils.addUrlParameter(url, SENDER_KEY, sender, charset);
    url = WebUtils.addUrlParameter(url, RECEIVER_KEY, receiver, charset);
    url = WebUtils.addUrlParameter(url, MESSAGE_KEY, message, charset);

    if (StringUtils.isNotBlank(messageType)) {
        url = WebUtils.addUrlParameter(url, MESSAGE_TYPE_KEY, messageType, charset);
    }/*from w  w w . j a va  2  s. c  om*/
    if (time != null) {
        url = WebUtils.addUrlParameter(url, TIME_KEY, time, charset);
    }

    url = WebUtils.addUrlParameter(url, GET_MSG_ID_KEY, GET_MSG_ID_VALUE, charset);
    url = WebUtils.addUrlParameter(url, GET_COUNT_MSG_KEY, GET_COUNT_MSG_VALUE, charset);
    url = WebUtils.addUrlParameter(url, GET_LIMIT_KEY, GET_LIMIT_VALUE, charset);
    url = WebUtils.addUrlParameter(url, GET_STATUS_KEY, GET_STATUS_VALUE, charset);

    final StringBuilder sb = new StringBuilder();
    HttpURLConnection con = null;
    InputStreamReader in = null;
    try {
        con = createHttpURLConnection(url);

        con.connect();

        in = new InputStreamReader(con.getInputStream(), charset);

        int len;
        char[] buf = new char[64];
        while ((len = in.read(buf)) > 0) {
            sb.append(buf, 0, len);
        }

    } catch (IOException e) {
        SmsException se = new SmsException(e);
        log.error("Sending SMS specified by " + smsSendRequest + " failed.", se);
        throw se;

    } finally {
        IOUtils.closeQuietly(in);
        if (con != null) {
            con.disconnect();
        }
    }

    final GoyyaSmsSendResponseDto goyyaSmsSendResponse = new GoyyaSmsSendResponseDto(sb.toString());
    final SmsSendResponseDto smsSendResponse = new SmsSendResponseDto(smsSendRequest,
            goyyaSmsSendResponse.isOk(), goyyaSmsSendResponse);
    return smsSendResponse;
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param stream//from  w ww.  j  ava 2s  .c om
 * @return
 * @throws IOException
 */
private String readStream(final InputStream stream) throws IOException {

    InputStreamReader reader = null;

    try {

        int count = 0;
        final char[] c = new char[BUFSIZE];
        reader = new InputStreamReader(stream, GlobalConstants.UTF_8);

        if ((count = reader.read(c)) > 0) {
            final StringBuilder sb = new StringBuilder(STRBLD_SIZE);
            do {
                sb.append(c, 0, count);
            } while ((count = reader.read(c)) > 0);
            return sb.toString();
        }
        return "";

    } finally {

        if (null != reader) {
            try {
                reader.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

public StringBuffer getResult() throws Exception {
    InputStream is = null;//from   w ww.j av a  2  s .c  o m
    InputStreamReader isr = null;
    try {
        LOG.info("Try to establish connection to " + url.toString());
        if ("https".compareTo(url.getProtocol()) == 0) {
            if (this.isHttpsCertificateEnabled()) {
                is = this.httpsWithCertificate(url);
            } else {
                is = httpsIgnoreCertificate(url);
            }

        } else {
            URLConnection urlConnection = url.openConnection();
            is = urlConnection.getInputStream();
        }

        isr = new InputStreamReader(is);
        StringBuffer sb = new StringBuffer();
        int numCharsRead;
        char[] charArray = new char[1024];
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }

        return sb;

    } finally {
        if (isr != null)
            isr.close();
    }

}

From source file:com.googlecode.CallerLookup.Main.java

public void parseLookupEntries() {
    mLookupEntries = new HashMap<String, LookupEntry>();
    mUserLookupEntries = new HashMap<String, LookupEntry>();

    boolean updateFound = false;
    for (String fileName : getApplicationContext().fileList()) {
        if (fileName.equals(UPDATE_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(UPDATE_FILE);
                XmlPullParser xml = Xml.newPullParser();
                xml.setInput(file, null);
                parseLookupEntries(xml, mLookupEntries);
                file.close();//w ww.ja  va 2 s  .  co m
                updateFound = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.equals(SAVED_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(SAVED_FILE);
                InputStreamReader reader = new InputStreamReader(file);
                char[] content = new char[8000];
                reader.read(content);
                JSONArray userLookupEntries = new JSONArray(new String(content));
                int count = userLookupEntries.length();
                for (int i = 0; i < count; i++) {
                    JSONObject userLookupEntry = userLookupEntries.getJSONObject(i);
                    mUserLookupEntries.put(userLookupEntry.getString("name"), new LookupEntry(userLookupEntry));
                }
                file.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    if (!updateFound) {
        XmlResourceParser xml = getApplicationContext().getResources().getXml(R.xml.lookups);
        parseLookupEntries(xml, mLookupEntries);
        xml.close();
    }
}

From source file:com.vmware.bdd.manager.TestClusteringJobs.java

private void testGuestInfo() {
    clusterSvc.init();//from  w w w. ja  v a2 s.c  o m
    VcContext.inVcSessionDo(new VcSession<Void>() {
        @Override
        protected boolean isTaskSession() {
            return true;
        }

        @Override
        protected Void body() throws Exception {
            VcVirtualMachine vm = VcCache.get("null:VirtualMachine:vm-97169");

            InputStreamReader reader = new InputStreamReader(System.in);
            char[] cbuf = new char[10];
            int num = reader.read(cbuf);
            while (num != -1) {
                Map<String, String> variables = vm.getGuestVariables();
                System.out.println("All guest variables.");
                for (String key : variables.keySet()) {
                    System.out.println("key:" + key + ", value:" + variables.get(key));
                }
            }
            return null;
        }
    });

}