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:gaffer.jsonserialisation.JSONSerialiser.java

/**
 * @param stream the {@link java.io.InputStream} containing the bytes of the object to deserialise
 * @param clazz  the class of the object to deserialise
 * @param <T>    the type of the object
 * @return the deserialised object/*  ww w .  ja v a 2 s .co m*/
 * @throws SerialisationException if the bytes fail to deserialise
 */
public <T> T deserialise(final InputStream stream, final Class<T> clazz) throws SerialisationException {
    try {
        final byte[] bytes = IOUtils.readFully(stream, stream.available(), true);
        return deserialise(bytes, clazz);
    } catch (IOException e) {
        throw new SerialisationException(e.getMessage(), e);
    } finally {
        try {
            if (null != stream) {
                stream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to close stream : " + e.getMessage(), e);
        }
    }
}

From source file:com.jeffreyawest.weblogic.rest.WebLogicDemoRestAdapter.java

private String getFileData(String assetName) throws IOException {

    String returnMe = null;//ww  w. j a  v a 2 s.c  om
    InputStream is = null;

    try {

        is = WebLogicMonitor.getInstance().getResources().getAssets().open(assetName);
        byte[] buffer = new byte[is.available()];
        int bytesRead = is.read(buffer);

        if (bytesRead != buffer.length) {
            throw new IOException("Read [" + bytesRead + "] bytes but expected [" + buffer.length + "]");
        }
        is.close();
        returnMe = new String(buffer);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
            }
        }
    }
    return returnMe;
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override/*  w  w  w. j a  va  2s  .  c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:jp.co.tis.gsp.tools.dba.mojo.ImportSchemaMojo.java

/**
 * Jar?????/*from  ww w  .  j ava2  s. c o m*/
 * 
 * @param jar
 * @param destDir
 * @throws IOException
 */
private void extractJarAll(JarFile jar, String destDir) throws IOException {
    Enumeration<JarEntry> enumEntries = jar.entries();
    while (enumEntries.hasMoreElements()) {
        java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
        java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
        if (file.isDirectory()) {
            f.mkdir();
            continue;
        }
        java.io.InputStream is = jar.getInputStream(file);
        java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
        while (is.available() > 0) {
            fos.write(is.read());
        }
        fos.close();
        is.close();
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java

public String getContentAsString() {
    if (rootPart == null)
        return null;

    if (responseContent == null) {
        try {/* www  . j  a v  a  2  s.  co  m*/
            InputStream in = rootPart.getInputStream();
            StringBuffer buf = new StringBuffer();
            while (in.available() > 0)
                buf.append((char) in.read());

            responseContent = buf.toString();

            if (wsdlRequest.getSettings().getBoolean(WsdlSettings.PRETTY_PRINT_RESPONSE_MESSAGES)) {
                responseContent = XmlUtils.prettyPrintXml(responseContent);
            }

            return responseContent;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return responseContent;
}

From source file:com.turn.splicer.Config.java

private Config() {
    try {//from w w w .j a v a  2s. c  o  m
        InputStream is = getClass().getClassLoader().getResourceAsStream(CONFIG_FILE);
        if (is != null) {
            LOG.info("Loaded {} bytes of configuration", is.available());
        }

        properties.load(is);
    } catch (IOException e) {
        LOG.error("Could not load " + CONFIG_FILE, e);
    }
}

From source file:net.doubledoordev.backend.webserver_old.SimpleWebServer.java

/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and HTTP parameters.
 *///  ww  w  .  ja va  2  s .c  o  m
public Response serveResourceFile(String uri) {
    Response res;
    try {
        InputStream stream = getClass().getResourceAsStream(rootDir + uri);
        int fileLen = stream.available();
        res = createResponse(Response.Status.OK, getMimeTypeForFile(uri), stream);
        res.addHeader("Content-Length", "" + fileLen);
    } catch (IOException ioe) {
        res = getForbiddenResponse("Reading file failed.");
    }

    return res;
}

From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java

private int readFileToEnd(AsterixDecoder decoder, InputStream is, FinalFrameReader ffReader)
        throws IOException {
    int receivedBytes = 0;
    while (is.available() > 0) {
        byte[] ffPayload = ffReader.read(is);
        if (ffPayload != null) {
            decoder.decode(ffPayload, 0, ffPayload.length);
            receivedBytes += ffPayload.length + 12;
        }/*from w w w  . j  a  v a2s .  c o m*/
    }
    return receivedBytes;
}

From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java

public static void copy(InputStream in, OutputStream out, boolean doPartial, boolean doSkip)
        throws IOException {
    final int BUF_SIZE = 1024;
    byte[] tmp = new byte[BUF_SIZE];

    int initAvail = in.available();

    int skipAt = 0;
    if (doSkip) {
        skipAt = (FILE_SIZE % BUF_SIZE) - 1;
    }/*from   w  w w  .  j av a  2 s.co m*/

    int numRead = 0;
    int totRead = 0;
    int iteration = 0;
    while ((numRead = cycleRead(in, tmp, iteration)) != -1) {
        cycleWrite(out, tmp, numRead, iteration);
        totRead += numRead;

        if (doPartial && (totRead >= PARTIAL_SIZE)) {
            // just return
            return;
        }
        if (doSkip && (totRead >= skipAt)) {
            long toSkip = FILE_SIZE - totRead;
            long skipped = in.skip(toSkip);
            if (skipped != toSkip) {
                throw new IOException("skipped wrong?");
            }
        }

        ++iteration;
    }

    if (totRead > 0) {
        if (initAvail < 0) {
            throw new IOException("no bytes?");
        }
    }

    out.flush();
    if (in.available() != 0) {
        throw new IOException("more bytes?");
    }
}

From source file:com.pentaho.repository.importexport.StreamToTransNodeConverter.java

public IRepositoryFileData convert(final InputStream inputStream, final String charset, final String mimeType) {
    try {//from w  w  w  . j a  v  a  2  s.c o  m
        long size = inputStream.available();
        TransMeta transMeta = new TransMeta();
        Repository repository = connectToRepository();
        Document doc = PDIImportUtil.loadXMLFrom(inputStream);
        transMeta.loadXML(doc.getDocumentElement(), repository, false);
        TransDelegate delegate = new TransDelegate(repository, this.unifiedRepository);
        saveSharedObjects(repository, transMeta);
        return new NodeRepositoryFileData(delegate.elementToDataNode(transMeta), size);
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}