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:FastBufferedInputStream.java

/**
 * Reads bytes from this byte-input stream into the specified byte array,
 * starting at the given offset./*  w w w .  j  a  v  a  2  s.  co  m*/
 *
 * <p> This method implements the general contract of the corresponding
 * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
 * the <code>{@link InputStream}</code> class.  As an additional
 * convenience, it attempts to read as many bytes as possible by repeatedly
 * invoking the <code>read</code> method of the underlying stream.  This
 * iterated <code>read</code> continues until one of the following
 * conditions becomes true: <ul>
 *
 *   <li> The specified number of bytes have been read,
 *
 *   <li> The <code>read</code> method of the underlying stream returns
 *   <code>-1</code>, indicating end-of-file, or
 *
 *   <li> The <code>available</code> method of the underlying stream
 *   returns zero, indicating that further input requests would block.
 *
 * </ul> If the first <code>read</code> on the underlying stream returns
 * <code>-1</code> to indicate end-of-file then this method returns
 * <code>-1</code>.  Otherwise this method returns the number of bytes
 * actually read.
 *
 * <p> Subclasses of this class are encouraged, but not required, to
 * attempt to read as many bytes as possible in the same fashion.
 *
 * @param      b     destination buffer.
 * @param      off   offset at which to start storing bytes.
 * @param      len   maximum number of bytes to read.
 * @return     the number of bytes read, or <code>-1</code> if the end of
 *             the stream has been reached.
 * @exception  IOException  if this input stream has been closed by
 *            invoking its {@link #close()} method,
 *            or an I/O error occurs. 
 */
public int read(byte b[], int off, int len) throws IOException {
    getBufIfOpen(); // Check for closed stream
    if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return 0;
    }

    int n = 0;
    for (;;) {
        int nread = read1(b, off + n, len - n);
        if (nread <= 0)
            return (n == 0) ? nread : n;
        n += nread;
        if (n >= len)
            return n;
        // if not closed but no bytes available, return
        InputStream input = in;
        if (input != null && input.available() <= 0)
            return n;
    }
}

From source file:hk.hku.cecid.corvus.http.EnvelopQuerySender.java

/**
 * [@EVENT] This method is invoked when received the reply HTTP  response from the server.
 * <br/><br/>/*from   w w w  .j  a  v  a  2 s  .  c o  m*/
 * It saves the response body stream and then available to get through by {@link #getEnvelopStream()}
 */
protected void onResponse() throws Exception {
    HttpMethod post = this.getExecutedMethod();
    InputStream ins = post.getResponseBodyAsStream();

    /*
     * We have to pipe the content to either memory or storage because the response stream
     * is directly extracted from socket which is going to close upon the connection 
     * has been closed.
     */
    if (ins.available() < THRESHOLD) {
        byte[] envelop = IOHandler.readBytes(ins);
        this.envelopStream = new ByteArrayInputStream(envelop);
    } else {
        // Create a temporary file at TMP directory.
        File envelopTmp = new File(BASE_PATH + this.hashCode());
        envelopTmp.deleteOnExit();
        // Pipe the content to the TMP file.
        FileChannel fChannel = new FileInputStream(envelopTmp).getChannel();
        fChannel.transferFrom(Channels.newChannel(ins), 0, ins.available());
        fChannel.close();
        // Create an buffered stream to the file.
        this.envelopStream = new BufferedInputStream(new FileInputStream(envelopTmp));
        // InputStream is closed automatically.
    }
}

From source file:com.sshtools.daemon.authentication.AuthenticationProtocolServer.java

/**
 *
 *
 * @throws java.io.IOException//from  ww w  .  j  av a2 s.c o  m
 * @throws AuthenticationProtocolException
 */
protected void onServiceRequest() throws java.io.IOException {
    // Send a user auth banner if configured
    ServerConfiguration server = (ServerConfiguration) ConfigurationLoader
            .getConfiguration(ServerConfiguration.class);

    if (server == null) {
        throw new AuthenticationProtocolException("Server configuration unavailable");
    }

    availableAuths = new ArrayList();

    Iterator it = SshAuthenticationServerFactory.getSupportedMethods().iterator();
    String method;
    List allowed = server.getAllowedAuthentications();

    while (it.hasNext()) {
        method = (String) it.next();

        if (allowed.contains(method)) {
            availableAuths.add(method);
        }
    }

    if (availableAuths.size() <= 0) {
        throw new AuthenticationProtocolException("No valid authentication methods have been specified");
    }

    // Accept the service request
    sendServiceAccept();

    String bannerFile = server.getAuthenticationBanner();

    if (bannerFile != null) {
        if (bannerFile.length() > 0) {
            InputStream in = ConfigurationLoader.loadFile(bannerFile);

            if (in != null) {
                byte[] data = new byte[in.available()];
                in.read(data);
                in.close();

                SshMsgUserAuthBanner bannerMsg = new SshMsgUserAuthBanner(new String(data));
                transport.sendMessage(bannerMsg, this);
            } else {
                log.info("The banner file '" + bannerFile + "' was not found");
            }
        }
    }
}

From source file:com.github.hobbe.android.openkarotz.fragment.ColorFragment.java

private String loadJsonFromAsset(String filename) {
    String json = null;//from   ww  w  .  j a  v  a 2  s  .  c  om

    InputStream is = null;
    try {
        is = getActivity().getAssets().open(filename);

        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);

        json = new String(buffer, "UTF-8");

    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not load JSON asset " + filename, e);
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Ignored
            }
        }
    }

    return json;
}

From source file:ConcatInputStream.java

/**
 * Returns the number of bytes that can be read (or skipped over) from this input
 * stream without blocking by the next caller of a method for this input stream.
 * The next caller might be the same thread or or another thread.
 *
 * @throws IOException If an I/O error occurs
 *
 * @since ostermillerutils 1.04.00/*from w w w.ja  v a 2s.co m*/
 */
@Override
public int available() throws IOException {
    if (closed)
        throw new IOException("InputStream closed");
    InputStream in = getCurrentInputStream();
    if (in == null)
        return 0;
    return in.available();
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {//from   w ww. ja  v  a 2 s . c om
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.uwca.operation.modules.api.company.web.CompanyController.java

@RequestMapping(value = "getCompanyInfo")
@ResponseBody//from   ww  w  .  j  av  a 2 s .c om
public CompanyVo getCompanyInfo(@RequestParam("token") String token) {
    CompanyVo companyVo = new CompanyVo();
    Result result = companyVo.new Result();

    try {
        if (StringUtils.isEmpty(token)) {
            companyVo.setReturncode(1);
            companyVo.setMessage("??");
            companyVo.setResult(result);
            return companyVo;
        }

        Company company = companyService.getCompanyInfo(TokenTool.getMobile(token));
        String businesslicense = company.getBusinesslicense();
        if (StringUtils.isNotEmpty(businesslicense)) {
            @SuppressWarnings("resource")
            InputStream in = new FileInputStream(Global.getUserfilesBaseDir() + businesslicense);
            if (null != in) {
                byte[] bytes = new byte[in.available()];
                company.setBusinesslicense(Encodes.encodeBase64(bytes));
            }
        }
        CompanyResult companyResult = new CompanyResult();
        BeanUtils.copyProperties(company, companyResult);
        result.setCompanyResult(companyResult);
        companyVo.setResult(result);
        companyVo.setReturncode(0);
        companyVo.setMessage("ok");
        return companyVo;
    } catch (Exception e) {
        companyVo.setReturncode(1);
        companyVo.setMessage("???");
        companyVo.setResult(result);
        e.printStackTrace();
        return companyVo;
    }
}

From source file:com.funtl.framework.smoke.core.modules.act.service.ActProcessService.java

/**
 * /*from   w ww . j  a v a 2 s  .c om*/
 */
public List<String> exportDiagrams(String exportDir) throws IOException {
    List<String> files = new ArrayList<String>();
    List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();

    for (ProcessDefinition processDefinition : list) {
        String diagramResourceName = processDefinition.getDiagramResourceName();
        String key = processDefinition.getKey();
        int version = processDefinition.getVersion();
        String diagramPath = "";

        InputStream resourceAsStream = repositoryService
                .getResourceAsStream(processDefinition.getDeploymentId(), diagramResourceName);
        byte[] b = new byte[resourceAsStream.available()];

        @SuppressWarnings("unused")
        int len = -1;
        resourceAsStream.read(b, 0, b.length);

        // create file if not exist
        String diagramDir = exportDir + "/" + key + "/" + version;
        File diagramDirFile = new File(diagramDir);
        if (!diagramDirFile.exists()) {
            diagramDirFile.mkdirs();
        }
        diagramPath = diagramDir + "/" + diagramResourceName;
        File file = new File(diagramPath);

        // 
        if (file.exists()) {
            // ????(????)
            logger.debug("diagram exist, ignore... : {}", diagramPath);

            files.add(diagramPath);
        } else {
            file.createNewFile();
            logger.debug("export diagram to : {}", diagramPath);

            // wirte bytes to file
            FileUtils.writeByteArrayToFile(file, b, true);

            files.add(diagramPath);
        }

    }

    return files;
}

From source file:io.cslinmiso.line.model.LineBase.java

public boolean sendFile(String name, InputStream is) throws Exception {
    String fileName = "SendByLineAPI4J";
    String fileSize = String.valueOf(is.available());
    try {//w ww .  j  a va  2s .c  o  m
        if (StringUtils.isNotEmpty(name)) {
            fileName = name;
        }

        LineMessage message = new LineMessage();
        message.setTo(getId());
        message.setContentType(ContentType.FILE);

        Map<String, String> contentMetadata = new HashMap<String, String>();
        contentMetadata.put("FILE_NAME", fileName);
        contentMetadata.put("FILE_SIZE", fileSize);
        message.setContentMetadata(contentMetadata);

        Message sendMessage = client.sendMessage(0, message);
        String messageId = sendMessage.getId();

        // preparing params which is detail of image to upload server
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("name", fileName);
        objectNode.put("oid", messageId);
        objectNode.put("size", fileSize);
        objectNode.put("type", "file");
        objectNode.put("ver", "1.0");

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("params", objectMapper.writeValueAsString(objectNode));

        String url = LineApi.LINE_UPLOADING_URL;
        LineApiImpl api = (LineApiImpl) client.getApi();
        boolean isUploaded = api.postContent(url, data, is);

        if (isUploaded == false) {
            throw new Exception("Fail to upload file.");
        }
        return true;
    } catch (Exception e) {
        throw e;
    }
}

From source file:jp.co.cyberagent.jenkins.plugins.DeployStrategyAndroid.java

private String getStringFromManifest(final String name) {
    File tempApk = null;/*from   w w w.  ja  va 2 s .  c om*/
    InputStream is = null;
    ZipFile zip = null;
    try {
        tempApk = File.createTempFile(getBuild().getId(), "nr-" + getBuild().getNumber());
        mApkFile.copyTo(new FileOutputStream(tempApk));
        zip = new ZipFile(tempApk);
        ZipEntry mft = zip.getEntry("AndroidManifest.xml");
        is = zip.getInputStream(mft);

        byte[] xml = new byte[is.available()];
        is.read(xml);

        String string = AndroidUtils.decompressXML(xml);
        int start = string.indexOf(name + "=\"") + name.length() + 2;
        int end = string.indexOf("\"", start);
        String version = string.substring(start, end);

        if (version.startsWith("resourceID 0x")) {
            int resId = Integer.parseInt(version.substring(13), 16);
            return getStringFromResource(tempApk, resId);
        } else {
            return version;
        }
    } catch (Exception e) {
        getLogger().println(TAG + "Error: " + e.getMessage());
    } finally {
        if (tempApk != null)
            tempApk.delete();
        if (zip != null)
            try {
                zip.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                getLogger().println(TAG + "Error: " + e.getMessage());
            }
    }
    return null;
}