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:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testAvailableWithBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, true));
    assertEquals(7, in.available());
}

From source file:com.examples.with.different.packagename.coverage.BOMInputStreamTest.java

public void testAvailableWithoutBOM() throws Exception {
    byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    InputStream in = new BOMInputStream(createDataStream(data, false));
    assertEquals(4, in.available());
}

From source file:de.hshannover.f4.trust.ifmapj.channel.ApacheCoreCommunicationHandler.java

@Override
public InputStream doActualRequest(InputStream is) throws IOException {
    InputStreamEntity ise = null;/* w  w  w  . j a v  a2  s .co  m*/
    HttpResponse response = null;
    InputStream ret = null;
    Header hdr = null;
    HttpEntity respEntity = null;
    StatusLine status = null;

    ise = new InputStreamEntity(is, is.available());
    ise.setChunked(false);
    mHttpPost.setEntity(ise);

    // do the actual request
    try {
        mHttpConnection.sendRequestHeader(mHttpPost);
        mHttpConnection.sendRequestEntity(mHttpPost);
        response = mHttpConnection.receiveResponseHeader();
        mHttpConnection.receiveResponseEntity(response);
    } catch (HttpException e) {
        throw new IOException(e);
    }

    // check if we got a 200 status back, otherwise go crazy
    status = response.getStatusLine();
    if (status.getStatusCode() != 200) {
        throw new IOException("HTTP Status Code: " + status.getStatusCode() + " " + status.getReasonPhrase());
    }

    // check whether the response uses gzip
    hdr = response.getFirstHeader("Content-Encoding");
    mResponseGzip = hdr == null ? false : hdr.getValue().contains("gzip");
    respEntity = response.getEntity();

    if (respEntity != null) {
        ret = respEntity.getContent();
    }

    if (ret == null) {
        throw new IOException("no content in response");
    }

    return ret;
}

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

@Override
@Transactional// w  w  w .  j  a  va 2  s .c o m
public Integer create(PersonalLicense newInstance) {

    try {

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

        return personalLicenseDao.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:ca.bitwit.postcard.PostcardAdaptor.java

public String loadJSONFile(String file) {
    try {/* w  w w.j ava2s.c om*/
        String jsonString;

        Context context = this.activity.getApplicationContext();

        InputStream is = context.getAssets().open(file);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        jsonString = new String(buffer, "UTF-8");

        return jsonString;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

@PostConstruct
private void initializeFileRead() throws Exception {
    String pathToUse = this.modelFile;
    if (pathToUse.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
        pathToUse = pathToUse.replace(ResourceUtils.CLASSPATH_URL_PREFIX, "");
    }//ww w .j  a v  a  2 s.co m
    try {
        final InputStream file = new ClassPathResource(this.modelFile).getInputStream();
        if (file.available() > 1) {
            final String stringContent = FileCopyUtils
                    .copyToString(new BufferedReader(new InputStreamReader(file)));
            if (StringUtils.hasText(stringContent)) {
                this.actionModel = this.objectMapper.readTree(stringContent);
            } else {
                throw new Exception("Invalid content");
            }
        }
    } catch (FileNotFoundException exp) {
        LOGGER.error(String.format("Could not locate action-model file at %s", pathToUse), exp);
    } catch (IOException exp) {
        LOGGER.error(String.format("Could not read action-model file at %s", pathToUse), exp);
    } catch (Exception exp) {
        LOGGER.error(String.format("Generic exception when reading => %s", exp.getMessage()));
    }
    if (this.parseOnLoad) {
        // TODO add appropriate exception when actionModel is null
        this.parseActionModels();
    }
}

From source file:com.krikelin.spotifysource.AppInstaller.java

protected void extractJar(String destDir, String jarFile) throws IOException {
    File destination = new File(destDir);
    java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration<JarEntry> enu = jar.entries();
    while (enu.hasMoreElements()) {
        try {/*from   w  w w. j a va2  s.com*/
            java.util.jar.JarEntry file = (java.util.jar.JarEntry) enu.nextElement();
            java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
            if (file.isDirectory()) { // if its a directory, create it
                f.mkdir();
                continue;
            }
            java.io.InputStream is = jar.getInputStream(file); // get the input stream
            if (!(destination.exists())) {
                destination.createNewFile();
            }

            java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
            while (is.available() > 0) { // write contents of 'is' to 'fos'
                fos.write(is.read());
            }
            fos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.indiana.d2i.sloan.utils.SSHProxy.java

/**
 * execute a list of commands in blocking way
 * /*  w  ww.  j  ava2s .c om*/
 * @param cmds
 * @param requireSudo
 * @return
 * @throws JSchException
 * @throws IOException
 * @throws Exception
 */
public CmdsExecResult execCmdSync(Commands cmds) throws JSchException, IOException {
    String command = cmds.getConcatenatedForm();
    int exitCode = Integer.MIN_VALUE;

    if (cmds.isSudoCmds)
        command = SUDO_PREFIX + command;
    logger.info("ssh execute: " + command);

    StringBuilder screenOutput = new StringBuilder();

    Channel channel = session.openChannel("exec");

    ((ChannelExec) channel).setCommand(command);
    ((ChannelExec) channel).setErrStream(System.err);

    channel.connect();

    InputStream is = channel.getInputStream();

    byte[] buf = new byte[BUFFER_SIZE];

    while (true) {

        while (is.available() > 0) {
            int bytesRead = is.read(buf, 0, 1024);

            if (bytesRead < 0)
                break;

            screenOutput.append(new String(buf, 0, bytesRead));
        }

        if (channel.isClosed()) {
            exitCode = channel.getExitStatus();
            break;
        }

        /**
         * sleep a while waiting for more outputs
         */
        try {
            Thread.sleep(THREAD_SLEEP_DURATION);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
    }

    // disconnect
    channel.disconnect();

    return new CmdsExecResult(cmds, hostname, exitCode, screenOutput.toString());
}

From source file:com.epam.wilma.test.server.ExampleHandler.java

private void generateBadResponses(String path, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, Request baseRequest) throws IOException {
    if (PATH_SEND_BAD_FIS.equals(path)) {
        byte[] responseBodyAsBytes;
        if (httpServletRequest.getHeader(ACCEPT_HEADER).contains(FASTINFOSET_TYPE)) {
            InputStream xml = getXmlFromFile(EXAMPLE_XML);
            httpServletResponse.setContentType("application/fastinfoset");
            httpServletResponse.setCharacterEncoding("UTF-8");
            responseBodyAsBytes = IOUtils.toByteArray(xml, xml.available());

            //Encodes response body with gzip if client accepts gzip encoding
            if (httpServletRequest.getHeader(ACCEPT_ENCODING) != null
                    && httpServletRequest.getHeader(ACCEPT_ENCODING).contains(GZIP_TYPE)) {
                ByteArrayOutputStream gzipped = gzipCompressor
                        .compress(new ByteArrayInputStream(responseBodyAsBytes));
                responseBodyAsBytes = gzipped.toByteArray();
                httpServletResponse.addHeader(CONTENT_ENCODING, GZIP_TYPE);
            }/*ww w.java  2s .co  m*/

            httpServletResponse.getOutputStream().write(responseBodyAsBytes);
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    }
}

From source file:de.decidr.workflowmodeleditor.server.servicetask.WSDLUploadServletImpl.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* Make sure that session is valid and field set (by WebPortal) */
    if (request.getSession().getAttribute("authenticatedUser") == null) {
        response.getWriter().write("Invalid authentication!");
        return;//from ww  w. ja  v a  2 s .  c o  m
    } else {
        callingUser = new UserRole((Long) request.getSession().getAttribute("authenticatedUser"));
    }

    boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
    if (isMultipart) {
        FileItemStream uploadItem = getFileItem(request);
        if (uploadItem == null) {
            super.service(request, response);
            return;
        }

        response.setContentType("text/plain");
        FileFacade ff = new FileFacade(callingUser);
        InputStream data = receiveUpload(uploadItem.openStream());
        Set<Class<? extends FilePermission>> publicPermissions = new HashSet<Class<? extends FilePermission>>();
        publicPermissions.add(FileReadPermission.class);
        try {
            Long fileID = ff.createFile(data, (long) data.available(), uploadItem.getName(),
                    uploadItem.getContentType(), false, publicPermissions);
            response.getWriter().write(fileID.toString());
        } catch (TransactionException e) {
            e.printStackTrace();
            response.getWriter().write("Failed due to transaction exception!");
        }

    } else {
        super.service(request, response);
    }
}