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:org.opencredo.cloud.storage.s3.JetS3Template.java

/**
 * @param containerName/*ww  w. j  av  a2 s  .co m*/
 * @param objectName
 * @param is
 * @see org.opencredo.cloud.storage.StorageOperations#send(java.lang.String,
 *      java.lang.String, java.io.InputStream)
 */
public String send(String containerName, String objectName, InputStream is) {
    Assert.notNull(containerName, BUCKET_NAME_CANNOT_BE_NULL);
    Assert.hasText(objectName, BLOB_NAME_MUST_BE_SET);
    LOG.debug(SEND_INPUT_STREAM_TO_BUCKET_WITH_KEY, containerName, objectName);
    try {
        S3Object s3ObjectToSend = new S3Object(objectName);
        s3ObjectToSend.setDataInputStream(is);
        s3ObjectToSend.setContentLength(is.available());
        s3Service.putObject(new S3Bucket(containerName), s3ObjectToSend);
    } catch (IOException e) {
        throw new StorageCommunicationException(SENDING_INPUT_STREAM_IO_PROBLEM, e);
    } catch (S3ServiceException e) {
        throw new StorageCommunicationException(SENDING_INPUT_STREAM_PROBLEM, e);
    }
    return objectName;
}

From source file:es.us.lsi.restest.engine.UnirestTest.java

@Test
public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException,
        URISyntaxException, UnirestException, IOException {
    final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI()));
    final byte[] bytes = new byte[stream.available()];
    stream.read(bytes);/*from  w w  w. ja v  a  2s.  c  o m*/
    stream.close();
    HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark")
            .field("file", bytes, "image.jpg").asJson();
    assertTrue(jsonResponse.getHeaders().size() > 0);
    assertTrue(jsonResponse.getBody().toString().length() > 0);
    assertFalse(jsonResponse.getRawBody() == null);
    assertEquals(200, jsonResponse.getStatus());

    JsonNode json = jsonResponse.getBody();
    assertFalse(json.isArray());
    assertNotNull(json.getObject());
    assertNotNull(json.getArray());
    assertEquals(1, json.getArray().length());
    assertNotNull(json.getArray().get(0));
    assertNotNull(json.getObject().getJSONObject("files"));

    assertTrue(json.getObject().getJSONObject("files").getString("file")
            .contains("data:application/octet-stream"));
    assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

public void importInitDatabase(Context context) {
    String dirPath = "/data/data/com.android.launcher3/databases";
    File dir = new File(dirPath);
    if (!dir.exists()) {
        dir.mkdir();/* w  ww.ja  va2s . c  o  m*/
    }

    File dbfile = new File(dir, "db_weather.db");
    try {
        if (!dbfile.exists()) {
            dbfile.createNewFile();
        }

        InputStream is = context.getResources().openRawResource(R.raw.db_weather);
        FileOutputStream fos = new FileOutputStream(dbfile);
        byte[] buffere = new byte[is.available()];
        is.read(buffere);
        fos.write(buffere);
        is.close();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.google.android.apps.body.LayersLoader.java

/** Synchronously loads a single layer. */
private Render.DrawGroup[] load(Context context, int layerResource) {
    // TODO(thakis): this method is kinda ugly.
    // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion
    //               needs to happen at load time. The utf8 stuff is clever, but mostly overhead
    //               for local files.

    // Timers for different loading phases.
    float jsonReadS = 0;
    float jsonParseS = 0;
    float textureS = 0;
    float fileReadS = 0;
    float fileDecodeS = 0;
    float colorBufferS = 0;

    Render.DrawGroup[] drawGroups = null;

    long jsonReadStartNS = System.nanoTime();
    JSONObject object = loadJsonResource(context, layerResource);
    jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f;

    long jsonParseStartNS = System.nanoTime();
    Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>();
    try {//from  ww w  .ja v  a2  s.  c  o m
        JSONArray dataDrawGroups = object.getJSONArray("draw_groups");
        drawGroups = new Render.DrawGroup[dataDrawGroups.length()];
        for (int i = 0; i < drawGroups.length; ++i) {
            if (mCancelled)
                return null;

            JSONObject drawGroup = dataDrawGroups.getJSONObject(i);
            drawGroups[i] = new Render.DrawGroup();
            if (drawGroup.has("texture"))
                drawGroups[i].texture = drawGroup.getString("texture");
            else if (drawGroup.has("diffuse_color")) {
                JSONArray color = drawGroup.getJSONArray("diffuse_color");
                drawGroups[i].diffuseColor = new float[3];
                for (int j = 0; j < 3; ++j)
                    drawGroups[i].diffuseColor[j] = (float) color.getDouble(j);
            }
            JSONArray draws = drawGroup.getJSONArray("draws");
            drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length());
            for (int j = 0; j < draws.length(); ++j) {
                JSONObject jsonDraw = draws.getJSONObject(j);
                Render.Draw draw = new Render.Draw();
                draw.geometry = jsonDraw.getString("geometry");
                draw.offset = jsonDraw.getJSONArray("range").getInt(0);
                draw.count = jsonDraw.getJSONArray("range").getInt(1);
                drawGroups[i].draws.add(draw);
            }
            long textureReadStartNS = System.nanoTime();
            loadTexture(mContext, drawGroups[i]);
            textureS += (System.nanoTime() - textureReadStartNS) / 1e9f;

            String indices = drawGroup.getString("indices");
            FP.FPEntry indicesFP = FP.get(indices);
            if (toBeLoaded.get(indicesFP.file) == null)
                toBeLoaded.put(indicesFP.file, new ArrayList<Loader>());
            toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP));

            String attribs = drawGroup.getString("attribs");
            FP.FPEntry attribsFP = FP.get(attribs);
            if (toBeLoaded.get(attribsFP.file) == null)
                toBeLoaded.put(attribsFP.file, new ArrayList<Loader>());
            toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP));

            drawGroups[i].numIndices = drawGroup.getInt("numIndices");
        }
    } catch (JSONException e) {
        Log.e("Body", e.toString());
    }
    jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS;

    for (int resource : toBeLoaded.keySet()) {
        if (mCancelled)
            return null;

        long fileReadStartNS = System.nanoTime();
        char[] data = new char[0];
        InputStream is = mContext.getResources().openRawResource(resource);
        try {
            // Comment from the ApiDemo content/ReadAsset.java in the Android SDK:
            // "We guarantee that the available method returns the total
            //  size of the asset...  of course, this does mean that a single
            //  asset can't be more than 2 gigs."
            data = new char[is.available()];
            Reader in = new InputStreamReader(is, "UTF-8");
            in.read(data, 0, data.length);
        } catch (UnsupportedEncodingException e) {
            Log.e("Body", e.toString());
        } catch (IOException e) {
            Log.e("Body", e.toString());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e("Body", e.toString());
            }
        }
        fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f;
        long fileDecodeStartNS = System.nanoTime();
        for (Loader l : toBeLoaded.get(resource)) {
            if (mCancelled)
                return null;

            l.load(data);
        }
        fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f;
    }

    long colorBufferStartNS = System.nanoTime();
    for (Render.DrawGroup drawGroup : drawGroups) {
        if (mCancelled)
            return null;
        createColorBuffer(drawGroup);
    }
    colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f;

    Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS
            + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS);

    return drawGroups;
}

From source file:es.us.lsi.restest.engine.UnirestTest.java

@Test
public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException,
        URISyntaxException, UnirestException, IOException {
    final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI()));
    final byte[] bytes = new byte[stream.available()];
    stream.read(bytes);// w w w.  j  a v a2s .  c o m
    stream.close();
    Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test")
            .asJsonAsync(new Callback<JsonNode>() {

                public void failed(UnirestException e) {
                    fail();
                }

                public void completed(HttpResponse<JsonNode> response) {
                    assertTrue(response.getHeaders().size() > 0);
                    assertTrue(response.getBody().toString().length() > 0);
                    assertFalse(response.getRawBody() == null);
                    assertEquals(200, response.getStatus());

                    JsonNode json = response.getBody();
                    assertFalse(json.isArray());
                    assertNotNull(json.getObject());
                    assertNotNull(json.getArray());
                    assertEquals(1, json.getArray().length());
                    assertNotNull(json.getArray().get(0));

                    assertEquals("This is a test file",
                            json.getObject().getJSONObject("files").getString("file"));
                    assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));

                    status = true;
                    lock.countDown();
                }

                public void cancelled() {
                    fail();
                }

            });

    lock.await(10, TimeUnit.SECONDS);
    assertTrue(status);
}

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

protected void handleStaticData(HttpServletRequest request, HttpServletResponse response) {
    String resourceUri = request.getServletPath();
    Engine.logContext.debug("Serving static ressource: " + resourceUri);

    // TODO: enhance to support content types according to file extension
    if (resourceUri.endsWith(".xml") || resourceUri.endsWith(".cxml") || resourceUri.endsWith(".pxml"))
        response.setContentType(MimeType.TextXml.value());
    else/* www .  j  a  v a  2  s . c o  m*/
        response.setContentType(MimeType.Html.value());

    try {
        InputStream is = getServletContext().getResourceAsStream(resourceUri);
        if (is == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Static resource " + resourceUri + " not found");
            return;
        }

        byte array[] = new byte[4096];

        OutputStream os = response.getOutputStream();
        while (is.available() != 0) {
            int nb = is.read(array);
            os.write(array, 0, nb);
        }
        os.flush();

    } catch (IOException e) {
        Engine.logContext.trace("Error serving static resource: " + resourceUri);
    }
}

From source file:de.micromata.genome.test.web.SimHttpServletRequest.java

protected void setInputStream(final InputStream servletIs) {
    this.servletIs = new ServletInputStream() {

        public int available() throws IOException {
            return servletIs.available();
        }/*from w  w w. j  av  a 2s .  co m*/

        public void close() throws IOException {
            servletIs.close();
        }

        public boolean equals(Object obj) {
            return servletIs.equals(obj);
        }

        public int hashCode() {
            return servletIs.hashCode();
        }

        public void mark(int readlimit) {
            servletIs.mark(readlimit);
        }

        public boolean markSupported() {
            return servletIs.markSupported();
        }

        public int read(byte[] b, int off, int len) throws IOException {
            return servletIs.read(b, off, len);
        }

        public int read(byte[] b) throws IOException {
            return servletIs.read(b);
        }

        public void reset() throws IOException {
            servletIs.reset();
        }

        public long skip(long n) throws IOException {
            return servletIs.skip(n);
        }

        public String toString() {
            return servletIs.toString();
        }

        @Override
        public int read() throws IOException {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.netflix.simianarmy.basic.sniper.BasicSniperMonkey.java

private Event killProcess(InstanceGroup group, String inst) {
    Validate.notNull(group);//from   w  ww  .  j  a va  2  s  .  c o m
    Validate.notEmpty(inst);
    String prop = NS + "leashed";
    if (cfg.getBoolOrElse(prop, false)) {
        LOGGER.info("leashed SniperMonkey prevented from killing {} from group {} [{}], set {}=false",
                new Object[] { inst, group.name(), group.type(), prop });
        reportEventForSummary(EventTypes.SNIPER_TERMINATION_SKIPPED, group, inst);
        return null;
    } else {
        try {
            Event evt = recordTermination(group, inst);
            sendTerminationNotification(group, inst);
            try {
                JSch jsch = new JSch();

                jsch.addIdentity(privateKey, "");
                Session session = jsch.getSession(user, inst, 22);

                session.setPassword("");
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);

                session.connect();

                // String command="mkdir /data";
                String command = "ps -ef | grep " + process
                        + " | grep -v grep | awk '{print $2}' | xargs sudo kill -9";
                String sudo_pass = null;

                sudo_pass = "";

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

                ((ChannelExec) channel).setPty(true);

                // man sudo
                // -S The -S (stdin) option causes sudo to read the password from
                // the
                // standard input instead of the terminal device.
                // -p The -p (prompt) option allows you to override the default
                // password prompt and use a custom one.
                ((ChannelExec) channel).setCommand("sudo -S -p '' " + command);

                InputStream in = channel.getInputStream();
                OutputStream out = channel.getOutputStream();
                ((ChannelExec) channel).setErrStream(System.err);

                channel.connect();

                out.write((sudo_pass + "\n").getBytes());
                out.flush();

                byte[] tmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0)
                            break;
                        System.out.print(new String(tmp, 0, i));
                    }
                    if (channel.isClosed()) {
                        System.out.println("exit-status: " + channel.getExitStatus());
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ee) {
                    }
                }
                channel.disconnect();
                session.disconnect();
            } catch (Exception e) {
                System.out.println(e);
            }
            LOGGER.info("Terminated {} from group {} [{}]", new Object[] { inst, group.name(), group.type() });
            reportEventForSummary(EventTypes.SNIPER_TERMINATION, group, inst);
            return evt;
        } catch (NotFoundException e) {
            LOGGER.warn(
                    "Failed to terminate " + inst + ", it does not exist. Perhaps it was already terminated");
            reportEventForSummary(EventTypes.SNIPER_TERMINATION_SKIPPED, group, inst);
            return null;
        } catch (Exception e) {
            handleTerminationError(inst, e);
            reportEventForSummary(EventTypes.SNIPER_TERMINATION_SKIPPED, group, inst);
            return null;
        }
    }
}

From source file:com.mycollab.module.file.servlet.UserAvatarHttpServletRequestHandler.java

@Override
protected void onHandleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (SiteConfiguration.isDemandEdition()) {
        throw new MyCollabException("This servlet support file system setting only");
    }/*from   w w  w .ja  va  2s. c o m*/

    String path = request.getPathInfo();

    if (path != null) {
        path = FilenameUtils.getBaseName(path);
        int lastIndex = path.lastIndexOf("_");
        if (lastIndex > 0) {
            String username = path.substring(0, lastIndex);
            int size = Integer.valueOf(path.substring(lastIndex + 1, path.length()));
            FileStorage fileStorage = (FileStorage) StorageFactory.getInstance();
            File avatarFile = fileStorage.getAvatarFile(username, size);
            InputStream avatarInputStream;
            if (avatarFile != null) {
                avatarInputStream = new FileInputStream(avatarFile);
            } else {
                String userAvatarPath = String.format("assets/icons/default_user_avatar_%d.png", size);
                avatarInputStream = UserAvatarHttpServletRequestHandler.class.getClassLoader()
                        .getResourceAsStream(userAvatarPath);
                if (avatarInputStream == null) {
                    LOG.error("Error to get avatar",
                            new MyCollabException("Invalid request for avatar " + path));
                    throw new ResourceNotFoundException("Invalid path " + path);
                }
            }

            response.setHeader("Content-Type", "image/png");
            response.setHeader("Content-Length", String.valueOf(avatarInputStream.available()));

            try (BufferedInputStream input = new BufferedInputStream(avatarInputStream);
                    BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream())) {
                byte[] buffer = new byte[8192];
                int length;
                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
            }
        } else {
            throw new ResourceNotFoundException("Invalid path " + path);
        }
    }
}

From source file:org.opencredo.cloud.storage.s3.JetS3Template.java

public String sendAndReceiveUrl(String containerName, String objectName, InputStream is) {
    Assert.notNull(containerName, BUCKET_NAME_CANNOT_BE_NULL);
    Assert.hasText(objectName, BLOB_NAME_MUST_BE_SET);
    LOG.debug(SEND_INPUT_STREAM_TO_BUCKET_WITH_KEY, containerName, objectName);
    try {//from   w  w w.  j a  va  2 s.c o  m
        S3Object s3ObjectToSend = new S3Object(objectName);
        s3ObjectToSend.setDataInputStream(is);
        s3ObjectToSend.setKey(objectName);
        s3ObjectToSend.setContentLength(is.available());
        s3Service.putObject(new S3Bucket(containerName), s3ObjectToSend);
        return "http://s3.amazonaws.com/" + containerName + "/" + s3ObjectToSend.getKey();
    } catch (IOException e) {
        throw new StorageCommunicationException(SENDING_INPUT_STREAM_IO_PROBLEM, e);
    } catch (S3ServiceException e) {
        throw new StorageCommunicationException(SENDING_INPUT_STREAM_PROBLEM, e);
    }
}