Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

In this page you can find the example usage for java.io InputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:eu.openanalytics.rsb.component.RestResultProcessor.java

private <T> void persistResult(final AbstractResult<?> result, final MimeType resultMimeType,
        final InputStream resultData) throws IOException {

    final GregorianCalendar resultTime = (GregorianCalendar) GregorianCalendar.getInstance();

    final PersistedResult persistedResult = new PersistedResult(result.getApplicationName(),
            result.getUserName(), result.getJobId(), resultTime, result.isSuccess(), resultMimeType) {

        @Override/*  www  . j a  v a2s .co m*/
        public long getDataLength() throws IOException {
            return resultData.available();
        }

        @Override
        public InputStream getData() {
            return resultData;
        }
    };

    resultStore.store(persistedResult);
    result.destroy();
}

From source file:com.erudika.para.storage.LocalFileStore.java

@Override
public String store(String path, InputStream data) {
    if (StringUtils.startsWith(path, File.separator)) {
        path = path.substring(1);/*from  www .  ja  va  2  s  .  c om*/
    }
    if (StringUtils.isBlank(path)) {
        return null;
    }
    int maxFileSizeMBytes = Config.getConfigInt("para.localstorage.max_filesize_mb", 10);
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        if (data.available() > 0 && data.available() <= (maxFileSizeMBytes * 1024 * 1024)) {
            File f = new File(folder + File.separator + path);
            if (f.canWrite()) {
                fos = new FileOutputStream(f);
                bos = new BufferedOutputStream(fos);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = data.read(bytes)) != -1) {
                    bos.write(bytes, 0, read);
                }
                return f.getAbsolutePath();
            }
        }
    } catch (IOException e) {
        logger.error(null, e);
    } finally {
        try {
            fos.close();
            bos.close();
            data.close();
        } catch (IOException e) {
            logger.error(null, e);
        }
    }
    return null;
}

From source file:com.wooki.services.parsers.XHTMLToFormattingObjects.java

private void putInCache(String fileLocation, String systemId) {
    try {/*from w  w w  .j a  va2 s .c  o  m*/
        InputStream in = this.getClass().getResourceAsStream(fileLocation);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        byte[] input = null;
        int available = 0;
        while ((available = in.available()) > 0) {
            int result;
            input = new byte[available];
            result = in.read(input);
            baos.write(input);
            if (result == -1)
                break;
        }
        byte[] dtd = baos.toByteArray();
        Element element = new Element(systemId, dtd);
        cache.put(element);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("Didn't manage to put " + fileLocation + " in the \"" + cacheName
                + "\" cache for systemId " + systemId);
        logger.error(e.getLocalizedMessage());
    }
}

From source file:com.isecpartners.gizmo.HttpResponse.java

public String uncompressData(byte[] blist, InputStream in) {
    StringBuffer sb = new StringBuffer();
    sb.append(extractHeaderBlock(blist));

    try {//  ww  w.  ja v  a 2  s  . c  o  m

        byte[] buf = new byte[1024];

        while (in.available() > 0) {
            int nRead = in.read(buf);
            if (nRead < 0)
                break;
            byte[] buf2 = new byte[nRead];
            System.arraycopy(buf, 0, buf2, 0, nRead);
            sb.append(new String(buf2));
        }
    } catch (IOException ex) {
        Logger.getLogger(HttpResponse.class.getName()).log(Level.SEVERE, null, ex);
    }

    return sb.toString();
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.scenarios.ScenariosServiceImpl.java

@Override
@Transactional// w  ww.  java 2  s. c  om
public Integer create(Scenario newInstance) {

    try {

        InputStream fileContentStream = newInstance.getFileContentStream();
        if (fileContentStream != null) {
            Blob createBlob = factory.getCurrentSession().getLobHelper().createBlob(fileContentStream,
                    fileContentStream.available());
            newInstance.setScenarioFile(createBlob);
        }

        return scenarioDAO.create(newInstance);

    } catch (HibernateException e) {
        log.error(e.getMessage(), e);
        return null;
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }

}

From source file:cz.zcu.kiv.eegdatabase.wui.core.scenarios.ScenariosServiceImpl.java

@Override
@Transactional/*w ww .ja  v a2s .  com*/
public void update(Scenario transientObject) {

    try {

        // XXX WORKAROUND for Hibernate pre 4.0, update entity with blob this way.
        Scenario merged = scenarioDAO.merge(transientObject);
        InputStream fileContentStream = transientObject.getFileContentStream();
        if (fileContentStream != null) {
            Blob createBlob = factory.getCurrentSession().getLobHelper().createBlob(fileContentStream,
                    fileContentStream.available());
            merged.setScenarioFile(createBlob);
            scenarioDAO.update(merged);
        }

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

}

From source file:com.nextgis.rehacompdemo.RoutingActivity.java

public String getGeoJSON(String name) {
    String json;//from w  w  w . j  av  a2s.  com

    try {
        InputStream is = getAssets().open(name + ".geojson");
        int size = is.available();
        byte[] buffer = new byte[size];
        //noinspection ResultOfMethodCallIgnored
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return json;
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w  w w  .j  a  v a 2s  .  c  om
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:com.datatorrent.lib.io.HttpJsonChunksInputOperator.java

@Override
public void processResponse(ClientResponse response) throws IOException {
    InputStream is = response.getEntity(java.io.InputStream.class);

    while (true) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[255];
        int bytesRead;
        while ((bytesRead = is.read(bytes)) != -1) {
            LOG.debug("read {} bytes", bytesRead);
            bos.write(bytes, 0, bytesRead);
            if (is.available() == 0 && bos.size() > 0) {
                // give chance to process what we have before blocking on read
                break;
            }/*  w w w.  j a va  2  s  . c  o  m*/
        }
        try {
            if (processBytes(bos.toByteArray())) {
                LOG.debug("End of chunked input stream.");
                response.close();
                break;
            }
        } catch (JSONException ex) {
            LOG.error("Caught JSON error:", ex);
        }
        if (bytesRead == -1) {
            LOG.error("Unexpected end of chunked input stream");
            response.close();
            break;
        }

        bos.reset();
    }
}

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Authenticate the client http state so that the colony requests can be made.
 *
 * @param baseURL URL requested for colony
 * @param client  HttpClient instance//w  w  w  .  j  a  v  a  2  s.  c  o  m
 *
 * @return true if authentication succeeded.
 *
 * @throws com.dtolabs.client.utils.HttpClientException
 *
 */
public boolean authenticate(final URL baseURL, final HttpClient client) throws HttpClientException {
    final HttpState state = client.getState();
    if (hasSessionCookie(baseURL, state, basePath)) {
        return true;
    }
    final byte[] buffer = new byte[1024];

    boolean doPostLogin = false;
    boolean isLoginFormContent = false;
    logger.debug("No session found, must login...");
    try {
        final URL newUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                basePath + getInitialPath());

        //load welcome page, which should forward to form based logon page.
        final GetMethod get = new GetMethod(newUrl.toExternalForm());
        get.setDoAuthentication(false);
        get.setFollowRedirects(false);
        logger.debug("Requesting: " + newUrl);
        int res = client.executeMethod(get);
        logger.debug("Result is: " + res);

        /*
          Tomcat container auth behaves differently than Jetty.  Tomcat will respond 200 OK and include the login form
          when auth is required, as well as on auth failure, it will also require complete GET of original URL after
          successful auth.
          Jetty will redirect to login page when auth is required, and will redirect to error page on failure.
         */

        String body = get.getResponseBodyAsString();
        if (null != body && body.contains(J_SECURITY_CHECK) && body.contains(JAVA_USER_PARAM)
                && body.contains(JAVA_PASS_PARAM)) {
            isLoginFormContent = true;
        }
        get.releaseConnection();

        if ((res == HttpStatus.SC_UNAUTHORIZED)) {
            if (get.getResponseHeader("WWW-Authenticate") != null
                    && get.getResponseHeader("WWW-Authenticate").getValue().matches("^Basic.*")) {
                logger.warn("Form-based login received UNAUTHORIZED, trying to use Basic authentication");
                final BasicAuthenticator auth = new BasicAuthenticator(username, password);
                return auth.authenticate(baseURL, client);
            } else {
                throw new HttpClientException(
                        "Form-based login received UNAUTHORIZED, but didn't recognize it as Basic authentication: unable to get a session");
            }

        }
        //should now have the proper session cookie
        if (!hasSessionCookie(baseURL, state, basePath)) {
            throw new HttpClientException("Unable to get a session from URL : " + newUrl);
        }
        if (res == HttpStatus.SC_OK && isLoginFormContent) {
            doPostLogin = true;
        } else if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header locHeader = get.getResponseHeader("Location");
            if (locHeader == null) {
                throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
            }
            String location = locHeader.getValue();
            if (!isValidLoginRedirect(get)) {
                //unexpected response
                throw new HttpClientException("Unexpected redirection when getting session: " + location);
            }
            logger.debug("Follow redirect: " + res + ": " + location);

            final GetMethod redir = new GetMethod(location);
            redir.setFollowRedirects(true);
            res = client.executeMethod(redir);
            InputStream ins = redir.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            redir.releaseConnection();

            if (res != HttpStatus.SC_OK) {
                throw new HttpClientException("Login page status was not OK: " + res);
            }
            logger.debug("Result: " + res);

            doPostLogin = true;
        } else if (res != HttpStatus.SC_OK) {
            //if request to welcome page was OK, we figure that the session is already set
            throw new HttpClientException("Request to welcome page returned error: " + res + ": " + get);
        }
        if (doPostLogin) {
            //now post login
            final URL loginUrl = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(),
                    basePath + JAVA_AUTH_PATH);

            final PostMethod login = new PostMethod(loginUrl.toExternalForm());
            login.setRequestBody(new NameValuePair[] { new NameValuePair(JAVA_USER_PARAM, getUsername()),
                    new NameValuePair(JAVA_PASS_PARAM, getPassword()) });

            login.setFollowRedirects(false);
            logger.debug("Post login info to URL: " + loginUrl);

            res = client.executeMethod(login);

            final InputStream ins = login.getResponseBodyAsStream();
            while (ins.available() > 0) {
                //read and discard response body
                ins.read(buffer);
            }
            login.releaseConnection();

            Header locHeader = login.getResponseHeader("Location");
            String location = null != locHeader ? locHeader.getValue() : null;
            if (isLoginError(login)) {
                logger.error("Form-based auth failed");
                return false;
            } else if (null != location && !location.equals(newUrl.toExternalForm())) {

                logger.warn("Form-based auth succeeded, but last URL was unexpected");
            }
            if (isFollowLoginRedirect()
                    && ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
                            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT))) {

                if (location == null) {
                    throw new HttpClientException("Redirect with no Location header, request URL: " + newUrl);
                }
                final GetMethod get2 = new GetMethod(location);
                //                    logger.debug("Result: " + res + ": " + location + ", following redirect");
                res = client.executeMethod(get2);
            } else if (res != HttpStatus.SC_OK) {
                throw new HttpClientException(
                        "Login didn't seem to work: " + res + ": " + login.getResponseBodyAsString());
            }
            logger.debug("Result: " + res);
        }
    } catch (MalformedURLException e) {
        throw new HttpClientException("Bad URL", e);
    } catch (HttpException e) {
        throw new HttpClientException("HTTP Error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new HttpClientException(
                "Error occurred while trying to authenticate to server: " + e.getMessage(), e);
    }

    return true;
}