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:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {/*from w  w w . j ava 2  s .  co m*/
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}

From source file:edu.ucla.cs.nopainnogame.WatchActivity.java

public void setFileData(String userName, String fileSuffix, String today, int value) {
    String filename = userName + fileSuffix;
    FileOutputStream fos;//from  www.j  a va 2s .  com
    InputStream is;
    int numBytes = 0;
    //String test = "";//for debugging
    try {
        is = openFileInput(filename);
        numBytes = is.available();
        InputStreamReader ir = new InputStreamReader(is);
        char[] buf = new char[numBytes];
        ir.read(buf);
        fos = openFileOutput(filename, Context.MODE_PRIVATE);
        String data = today + " " + value + "\n";
        data = data + String.valueOf(buf);
        fos.write(data.getBytes());
        //fos.write(test.getBytes());//for debugging
        fos.flush();
        ir.close();
        is.close();
        fos.close();
    } catch (FileNotFoundException fe) {
        System.err.println("Error: User file not found.");
        fe.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

@Override
public String store(String path, InputStream data) {
    if (StringUtils.startsWith(path, "/")) {
        path = path.substring(1);//from   w w w.j  a  v  a 2s .  co  m
    }
    if (StringUtils.isBlank(path) || data == null) {
        return null;
    }
    int maxFileSizeMBytes = Config.getConfigInt("para.s3.max_filesize_mb", 10);
    try {
        if (data.available() > 0 && data.available() <= (maxFileSizeMBytes * 1024 * 1024)) {
            ObjectMetadata om = new ObjectMetadata();
            om.setCacheControl("max-age=15552000, must-revalidate"); // 180 days
            if (path.endsWith(".gz")) {
                om.setContentEncoding("gzip");
                path = path.substring(0, path.length() - 3);
            }
            path = System.currentTimeMillis() + "." + path;
            PutObjectRequest por = new PutObjectRequest(bucket, path, data, om);
            por.setCannedAcl(CannedAccessControlList.PublicRead);
            por.setStorageClass(StorageClass.ReducedRedundancy);
            s3.putObject(por);
            return Utils.formatMessage(baseUrl, Config.AWS_REGION, bucket, path);
        }
    } catch (IOException e) {
        logger.error(null, e);
    } finally {
        try {
            data.close();
        } catch (IOException ex) {
            logger.error(null, ex);
        }
    }
    return null;
}

From source file:com.weibo.api.motan.protocol.grpc.http.NettyHttpRequestHandler.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected FullHttpResponse buildHttpResponse(Response response, boolean keepAlive) throws Exception {
    Object value = response.getValue();
    byte[] responseBytes = null;
    if (value instanceof Message) {
        Marshaller marshaller = ProtoUtils.jsonMarshaller(
                (Message) value.getClass().getMethod("getDefaultInstance", null).invoke(null, null));
        InputStream is = marshaller.stream(value);
        responseBytes = new byte[is.available()];
        is.read(responseBytes);//www  .j a v  a 2 s.c o m
    } else {
        // TODO not pb
    }

    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(responseBytes));
    httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/x-www-form-urlencoded");
    httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());

    if (keepAlive) {
        httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    return httpResponse;
}

From source file:com.akalizakeza.apps.ishusho.activity.NewPostUploadTaskFragment.java

public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(
            mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;/*from  w  w  w.j  a va 2s .  c  om*/
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public final void verify(final String host, final SSLSocket ssl) throws IOException {
    if (host == null) {
        throw new NullPointerException("host to verify is null");
    }//ww w .j  a  v  a  2  s .  c o  m

    SSLSession session = ssl.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 = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:
                
        #1.  Clean up the certificate chain that your server
             is presenting (e.g. edit "/etc/apache2/server.crt"
             or wherever it is your server's certificate chain
             is defined).
                
                                   OR
                
        #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
              to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if (session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
    try {//from  ww w .  j a v a2 s .  co m
        setAsciiStream(parameterIndex, x, x == null ? 0 : x.available());
    } catch (IOException e) {
        throw new SQLException(e);
    }
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
    try {/* w ww  . ja va2 s.  c  o m*/
        setBinaryStream(parameterIndex, x, x == null ? 0 : x.available());
    } catch (IOException e) {
        throw new SQLException(e);
    }
}

From source file:io.sightly.tck.TCK.java

private void extract(String extractDir) throws IOException {
    File extractFolder = new File(extractDir);
    if (extractFolder.exists()) {
        if (!extractFolder.isDirectory()) {
            throw new IOException("File entry " + extractFolder.getAbsolutePath()
                    + " already exists and it is not a folder.");
        }/*from   w w  w. ja  va 2 s . com*/
        if (!extractFolder.canWrite()) {
            throw new IOException(
                    "Folder " + extractFolder.getAbsolutePath() + " exists but it is not writable.");
        }
    } else {
        if (!extractFolder.mkdirs()) {
            throw new IOException("Unable to create folder " + extractFolder.getAbsolutePath() + ".");
        }
    }
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith(TESTFILES)) {
            File file = new File(extractFolder, entryName);
            if (entry.isDirectory()) {
                if (!file.mkdir()) {
                    throw new IOException("Unable to create folder " + file.getAbsolutePath());
                }
                continue;
            }
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = jarFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            } catch (IOException e) {
                LOG.error("Unable to extract file " + file.getAbsolutePath());
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        }
    }
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.license.impl.LicenseServiceImpl.java

@Override
@Transactional/*from   w  ww  . j av a 2 s  . com*/
public Integer create(License newInstance) {

    try {

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

        return licenseDao.create(newInstance);

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

}