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.cedarsoft.crypt.CertTest.java

@Test
public void testKey() throws Exception {
    InputStream inStream = new DataInputStream(getClass().getResource("/test.der").openStream());
    byte[] keyBytes = new byte[inStream.available()];
    inStream.read(keyBytes);//  w w  w .  j  av a 2 s.  c om
    inStream.close();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    // decipher private key
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
    assertNotNull(privKey);

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privKey);

    byte[] bytes = cipher.doFinal(PLAINTEXT.getBytes());
    assertEquals(SCRAMBLED, new String(Base64.encodeBase64(bytes)));
}

From source file:de.berlios.jedi.presentation.admin.UploadJispFileAction.java

/**
 * Returns the data from the file as a byte[].
 * /*from w ww.  j  a  va  2s  .c om*/
 * @param file
 *            The FormFile with the uploaded file.
 * @return The data get from the file.
 * @throws IOException
 *             If an I/O exception occured when getting the data.
 */
private byte[] getDataFromFile(FormFile file) throws IOException {
    byte[] data;
    InputStream in = null;
    try {
        in = file.getInputStream();

        int dataLength = in.available();
        data = new byte[dataLength];
        int dataReaded = 0;

        while ((dataLength - dataReaded) > 0) {
            dataReaded += in.read(data, dataReaded, dataLength - dataReaded);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return data;
}

From source file:com.atinternet.tracker.Configuration.java

/**
 * Get configuration defined in the UI/*  ww  w. ja v a2s.c  o m*/
 *
 * @param isTablet boolean
 * @return JSONObject
 */
private JSONObject getDefaultConfiguration(boolean isTablet) {
    JSONObject result = new JSONObject();
    String stringResult;
    try {
        InputStream inputStream = getClass().getResourceAsStream("/" + JSON_FILE);
        int size = inputStream.available();
        byte[] buffer = new byte[size];
        inputStream.read(buffer);
        inputStream.close();
        stringResult = new String(buffer, ENCODING);
        JSONObject json = new JSONObject(stringResult);
        if (isTablet) {
            result = json.getJSONObject(TABLET_CONFIGURATION);
        } else {
            result = json.getJSONObject(PHONE_CONFIGURATION);
        }
    } catch (Exception e) {
        try {
            result.put("log", "").put("logSSL", "").put("domain", "xiti.com").put("pixelPath", "/hit.xiti")
                    .put("site", "").put("secure", false).put("identifier", "androidId")
                    .put("enableCrashDetection", true).put("plugins", "").put("storage", "required")
                    .put("hashUserId", false).put("persistIdentifiedVisitor", true).put("tvtURL", "")
                    .put("tvtVisitDuration", 10).put("tvtSpotValidityTime", 5)
                    .put("campaignLastPersistence", false).put("campaignLifetime", 30)
                    .put("sessionBackgroundDuration", 60);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    }

    return result;
}

From source file:com.flowzr.rates.OpenExchangeRatesDownloaderTest.java

private String fileAsString(String fileName) {
    try {/* w w  w  .  jav a  2  s . c  o m*/
        InputStream is = getInstrumentation().getContext().getResources().getAssets().open(fileName);
        InputStreamEntity entity = new InputStreamEntity(is, is.available());
        return EntityUtils.toString(entity);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nasatrainedmonkeys.roboinstaller.RoboInstaller.java

/**
 * Takes the resource with the given name and installs it into the files dir
 * @param resid/*from   w ww  .  j a v a  2 s. c o m*/
 */
private void installFile(int resid) throws IOException {
    File targetFile = fileForResource(resid);
    Log.i(TAG, "Extracting file to " + targetFile.getAbsolutePath());
    FileOutputStream fos = new FileOutputStream(targetFile);
    InputStream is = ctx.getResources().openRawResource(resid);

    byte[] buffer = new byte[65000];

    while (is.available() > 0) {
        int read = is.read(buffer);
        fos.write(buffer, 0, read);
    }
    is.close();
    fos.close();

    sudo("chmod a+r " + targetFile.getAbsolutePath());
}

From source file:com.app.uploads.ImageTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www  . j a v a 2  s  .com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String type = "";
    CallableStatement pro;

    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        type = new String(b);
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT_TEST(?,?)}");
                pro.setInt(1, 2);
                pro.setString(2, name);
                pro.executeQuery();
                pro.close();
                connect.close();
                if (name != null) {
                    request.setAttribute("type", type);
                    request.setAttribute("success", "ok");
                }
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/SearchEngine.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:inti.core.codec.direct.DirectByteCodec.java

@Override
public byte[] decode(InputStream input) throws Exception {
    ByteArrayOutputStream output = outputs.get();
    byte[] transferBuffer = transferBuffers.get();
    int read;//ww w  . j  av a2  s.  co  m

    output.reset();
    while (input.available() > 0 && (read = input.read(transferBuffer)) != -1) {
        output.write(transferBuffer, 0, read);
    }

    return output.toByteArray();
}

From source file:br.ufac.sion.service.InscricaoService.java

private String geraCorpoEmailSolicitacaoInscricao(Inscricao inscricao) throws IOException {
    InputStream stream = getClass().getResourceAsStream("/comprovante.html");
    byte[] acessoBytes = new byte[stream.available()];
    stream.read(acessoBytes);/*from  w w w  .j a  v a  2s.c o  m*/
    stream.close();
    String body = new String(acessoBytes);
    body = body.replaceAll("@@@NOME_USUARIO@@@", inscricao.getCandidato().getNome());
    body = body.replaceAll("@@@CONCURSO@@@", inscricao.getCargoConcurso().getConcurso().getTitulo());
    body = body.replaceAll("@@@CARGO@@@", inscricao.getCargoConcurso().getCodigo() + " - "
            + inscricao.getCargoConcurso().getCargo().getDescricao());
    body = body.replaceAll("@@@CIDADE_PROVA@@@", inscricao.getCargoConcurso().getLocalidade().getNome());
    body = body.replaceAll("@@@BANCO@@@",
            inscricao.getCargoConcurso().getConcurso().getContaBancaria().getBanco().getDescricao());
    body = body.replaceAll("@@@NOME_FANTASIA@@@",
            inscricao.getCargoConcurso().getConcurso().getContaBancaria().getCedente().getNomeFantasia());
    body = body.replaceAll("@@@SIGLA@@@",
            inscricao.getCargoConcurso().getConcurso().getContaBancaria().getCedente().getSigla());
    return body;
}

From source file:com.networknt.body.BodyHandler.java

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // parse the body to map if content type is application/json
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType != null && contentType.startsWith("application/json")) {
        if (exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }//from   w  w  w. ja  v a 2s  . com
        exchange.startBlocking();
        InputStream is = exchange.getInputStream();
        if (is != null) {
            try {
                if (is.available() != -1) {
                    Object body;
                    String s = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
                    s = s.trim();
                    if (s.startsWith("{")) {
                        body = Config.getInstance().getMapper().readValue(s,
                                new TypeReference<HashMap<String, Object>>() {
                                });
                    } else if (s.startsWith("[")) {
                        body = Config.getInstance().getMapper().readValue(s,
                                new TypeReference<List<HashMap<String, Object>>>() {
                                });
                    } else {
                        // error here. The content type in head doesn't match the body.
                        Status status = new Status(CONTENT_TYPE_MISMATCH, contentType);
                        exchange.setStatusCode(status.getStatusCode());
                        exchange.getResponseSender().send(status.toString());
                        return;
                    }
                    exchange.putAttachment(REQUEST_BODY, body);
                }
            } catch (IOException e) {
                logger.error("IOException: ", e);
            }
        }
    }
    next.handleRequest(exchange);
}

From source file:com.aaasec.sigserv.cscommon.xmldsig.OfflineResolver.java

/**
 * Method engineResolve//from  ww  w  .j av  a 2s .c  o m
 *
 * @param uri
 * @param BaseURI
 *
 * @throws ResourceResolverException
 */
public XMLSignatureInput engineResolve(Attr uri, String BaseURI) throws ResourceResolverException {
    try {
        String URI = uri.getNodeValue();

        if (OfflineResolver._uriMap.containsKey(URI)) {
            String newURI = OfflineResolver._uriMap.get(URI);

            log.debug("Mapped " + URI + " to " + newURI);

            InputStream is = new FileInputStream(newURI);

            log.debug("Available bytes = " + is.available());

            XMLSignatureInput result = new XMLSignatureInput(is);

            // XMLSignatureInput result = new XMLSignatureInput(inputStream);
            result.setSourceURI(URI);
            result.setMIMEType((String) OfflineResolver._mimeMap.get(URI));

            return result;
        } else {
            Object exArgs[] = { "The URI " + URI + " is not configured for offline work" };

            throw new ResourceResolverException("generic.EmptyMessage", exArgs, uri, BaseURI);
        }
    } catch (IOException ex) {
        throw new ResourceResolverException("generic.EmptyMessage", ex, uri, BaseURI);
    }
}