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:it.isislab.sof.core.engine.hadoop.sshclient.connection.SofManager.java

public static boolean existOnHost(EnvironmentSession session, String path) {
    String output = "";
    String cmd = "if ls " + path + "; then echo 0; else echo -1; fi";
    //System.out.println("Start check "+path+ " "+cmd);
    try {// w  w w  . j ava 2 s  .  com
        Channel channel;

        channel = session.getSession().openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);

        InputStream in = channel.getInputStream();
        //((ChannelExec) channel).setErrStream(System.err);
        channel.connect();
        byte[] b = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(b, 0, 1024);
                if (i < 0)
                    break;
                output += new String(b, 0, i).trim();
            }

            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                break;
            }
        }
        channel.disconnect();

        return !output.contains("-1");
    } catch (Exception e) {
        e.printStackTrace();
        return false;

    }
}

From source file:net.krotscheck.dfr.stream.AbstractStreamDecoderTest.java

/**
 * Test that the stream is closeable.//from w w  w .ja v  a  2s  .  c  o  m
 *
 * @throws Exception Should not throw an exception.
 */
@Test
public void testCloseWithStream() throws Exception {
    IStreamDecoder decoder = new TestStreamDecoder(testData);

    Assert.assertNull(decoder.getInputStream());
    InputStream stream = ResourceUtil.getResourceAsStream("test.bson");
    decoder.setInputStream(stream);
    Assert.assertEquals(stream, decoder.getInputStream());

    decoder.close();

    Assert.assertTrue(stream.available() == 0);
    Assert.assertNull(decoder.getInputStream());
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tgrep.TGrepWriter.java

/**
 * Produces a TGrep2 binary corpus file.
 *
 * @param aFilename/* w w  w .j a va 2s. co  m*/
 *            the name of the file from which a corpus file shall be created, without extension
 * @throws IOException
 *             if the employed tgrep2 process is interrupted or if it reports an error
 */
private void writeTgrepBinary(String aFilename) throws IOException {
    List<String> cmd = new ArrayList<String>();
    cmd.add(tgrep2File.getAbsolutePath());
    if (writeComments) {
        // enable writing comments
        cmd.add("-C");
    }
    // specify corpus
    cmd.add("-p");
    cmd.add(new File(outputPath, aFilename + EXT_CORPUS).getAbsolutePath());
    cmd.add(new File(outputPath, aFilename + EXT_BINARY + compression.getExtension()).getAbsolutePath());

    getLogger().info("Running tgrep2 command: [" + StringUtils.join(cmd, " ") + "].");

    Process tgrepProcess = null;
    try {
        tgrepProcess = new ProcessBuilder(cmd).start();
        tgrepProcess.waitFor();
    } catch (InterruptedException e) {
        throw new IOException();
    } finally {
        if (tgrepProcess != null) {
            InputStream stderr = tgrepProcess.getErrorStream();
            if (stderr.available() > 0) {
                byte[] data = new byte[stderr.available()];
                stderr.read(data);
                String error = new String(data, "UTF-8");
                getLogger().error(error);
                throw new IOException(error);
            }
        }
    }
}

From source file:com.esofthead.mycollab.module.ecm.service.impl.ResourceServiceImpl.java

@Override
public void saveContent(Content content, String createdUser, InputStream refStream, Integer sAccountId) {
    Integer fileSize = 0;//from  w  w w  .  j a va  2s.  c o m
    if (sAccountId != null) {
        try {
            fileSize = refStream.available();
            billingPlanCheckerService.validateAccountCanUploadMoreFiles(sAccountId, fileSize);
        } catch (IOException e) {
            LOG.error("Can not get available bytes", e);
        }
    }

    // detect mimeType and set to content
    String mimeType = MimeTypesUtil.detectMimeType(content.getPath());
    content.setMimeType(mimeType);
    content.setSize(Long.valueOf(fileSize));

    String contentPath = content.getPath();
    rawContentService.saveContent(contentPath, refStream);

    if (MimeTypesUtil.isImage(mimeType)) {
        try (InputStream newInputStream = rawContentService.getContentStream(contentPath)) {
            BufferedImage image = ImageUtil.generateImageThumbnail(newInputStream);
            if (image != null) {
                String thumbnailPath = String.format(".thumbnail/%d/%s.%s", sAccountId,
                        StringUtils.generateSoftUniqueId(), "png");
                File tmpFile = File.createTempFile("tmp", "png");
                ImageIO.write(image, "png", new FileOutputStream(tmpFile));
                rawContentService.saveContent(thumbnailPath, new FileInputStream(tmpFile));
                content.setThumbnail(thumbnailPath);
            }
        } catch (IOException e) {
            LOG.error("Error when generating thumbnail", e);
        }
    }

    contentJcrDao.saveContent(content, createdUser);

    SaveContentCommand saveContentCommand = CamelProxyBuilderUtil.build(EcmEndPoints.SAVE_CONTENT_ENDPOINT,
            SaveContentCommand.class);
    saveContentCommand.saveContent(content, createdUser, sAccountId);
}

From source file:li.klass.fhem.fhem.TelnetConnection.java

private String readUntil(InputStream inputStream, String... blockers) throws IOException {
    waitForFilledStream(inputStream, 3000);

    StringBuilder buffer = new StringBuilder();
    while (inputStream.available() > 0 || waitForFilledStream(inputStream, 300)) {
        char readChar = (char) inputStream.read();
        buffer.append(readChar);/*from  w  w w. ja  v  a  2s  . c om*/
        for (String blocker : blockers) {
            if (StringUtil.endsWith(buffer, blocker))
                return buffer.toString();
        }
    }
    LOG.error("read data, but did not find end token, read content was '{}'");
    return null;
}

From source file:com.falcon.nester.AboutActivity.java

private void setAboutInfo(String title, String assetFile) {
    //      int offset = 0;
    //      int len;
    //char[] buff = new char[32*1024];
    ((TextView) this.findViewById(R.id.about_title)).setText(title);

    try {//from w w  w  .  j ava2  s.co  m
        InputStream is = getAssets().open(assetFile);
        // 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.  
        int size = is.available();
        // Read the entire asset into a local byte buffer.  
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        // Finally stick the string into the text view.  
        TextView tv = (TextView) findViewById(R.id.about_info);
        tv.setText(EncodingUtils.getString(buffer, "GB2312"));

        //      scvInfo.setOverScrollMode(ScrollView.OVER_SCROLL_IF_CONTENT_SCROLLS);

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

}

From source file:mml.handler.post.MMLPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//from   w w w  . j  av  a  2  s  .co m
 */
void parseImportParams(HttpServletRequest request) throws MMLException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString(this.encoding);
                    if (fieldName.equals(Params.DOCID)) {
                        int index = contents.lastIndexOf(".");
                        if (index != -1)
                            contents = contents.substring(0, index);
                        docid = contents;
                    } else if (fieldName.equals(Params.AUTHOR))
                        this.author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        this.title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        this.style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        this.format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        this.section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        this.version1 = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.ANNOTATIONS))
                        annotations = (JSONArray) JSONValue.parse(contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null) {
                        if (type.startsWith("image/")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            ImageFile iFile = new ImageFile(item.getName(), item.getContentType(),
                                    bh.getData());
                            if (images == null)
                                images = new ArrayList<ImageFile>();
                            images.add(iFile);
                        } else if (type.equals("text/plain")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            String style = new String(bh.getData(), encoding);
                            if (files == null)
                                files = new ArrayList<String>();
                            files.add(style);
                        }
                    }
                } catch (Exception e) {
                    throw new MMLException(e);
                }
            }
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:com.example.google.maps.dataviz.MainActivity.java

private void addDataToMap() {
    ArrayList<LatLng> coords = new ArrayList<LatLng>();
    ArrayList<Double> samples = new ArrayList<Double>();
    double minElevation = Integer.MAX_VALUE;
    double maxElevation = Integer.MIN_VALUE;

    try {/*  w  w w  .  ja v  a  2 s.  c  om*/
        Resources res = getResources();
        InputStream istream = res.openRawResource(R.raw.elevation);
        byte[] buff = new byte[istream.available()];
        istream.read(buff);
        istream.close();

        String json = new String(buff);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject sample = jsonArray.getJSONObject(i);

            double elevation = sample.getDouble("elevation");
            minElevation = elevation < minElevation ? elevation : minElevation;
            maxElevation = elevation > maxElevation ? elevation : maxElevation;

            JSONObject location = sample.getJSONObject("location");
            LatLng position = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

            coords.add(position);
            samples.add(elevation);
        }
    } catch (IOException e) {
        Log.e(this.getClass().getName(), "Error accessing elevation data file.");
        return;
    } catch (JSONException e) {
        Log.e(this.getClass().getName(), "Error processing elevation data (JSON).");
        return;
    }

    for (int i = 0; i < coords.size(); i++) {
        double elevation = samples.get(i);
        int height = (int) (elevation / maxElevation * MARKER_HEIGHT);

        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = Bitmap.createBitmap(MARKER_WIDTH, height, conf);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPaint(mPaint);

        // Invert the bitmap (top red, bottom blue).
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

        LatLng position = coords.get(i);
        BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromBitmap(bitmap);
        mMap.addMarker(new MarkerOptions().position(position).icon(bitmapDesc).alpha(.8f)
                .title(new DecimalFormat("#.## meters").format(elevation)));
    }
}

From source file:jp.co.applibot.backup.BackupController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String json = "";
    String className = "";
    String key = "";
    Long now = new Date().getTime();
    if (request != null) {
        BufferedReader bufferReaderBody = new BufferedReader(request.getReader());
        String body = bufferReaderBody.readLine();
        json = body;// w w w.  j a  va 2 s.  c om
    }

    int indexLast = json.indexOf("\":");
    if (indexLast > 0) {
        className = json.substring(1, indexLast);
    }
    className = className.replaceAll("\"", "");

    JSONParser parser = new JSONParser();
    //      try {
    //          
    //         Object wrapObj = parser.parse(json);
    //   
    //         JSONObject jsonWrapObject = (JSONObject) wrapObj;
    //    
    //         String jsonObj = jsonWrapObject.get(className).toString();
    //         
    //         Object obj = parser.parse(jsonObj);
    //         
    //         JSONObject jsonObject = (JSONObject) obj;
    //         
    //         key = jsonObject.get("id").toString();
    //    
    //      } catch (ParseException e) {
    //         e.printStackTrace();
    //      }

    JSch jsch = new JSch();
    String host = "107.167.177.138";
    String user = "dmlogging";
    String passwd = "Applibot12345";
    try {
        Session session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.connect(30000);
        Channel channel = session.openChannel("exec");
        // ((ChannelExec)channel).setCommand("\"" + json +"\"" +  ">> /home/komiya_sakura_applibot_co_jp/test.txt");
        ((ChannelExec) channel).setCommand("mkdir /home/komiya_sakura_applibot_co_jp/logfiles");
        LOGGER.warning("command set");
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                LOGGER.warning(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                LOGGER.warning("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    GcsFilename fileName = new GcsFilename(BUCKETNAME, className + "_" + now.toString() + "_" + key);
    GcsFileOptions options = new GcsFileOptions.Builder().mimeType("text/html").acl("public-read").build();
    GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);

    outputChannel.write(ByteBuffer.wrap(json.getBytes("UTF8")));
    outputChannel.close();

    //reply
    PrintWriter out = response.getWriter();
    out.println(json);
}

From source file:eu.openanalytics.rsb.component.JobsResource.java

/**
 * Handles a multi-part form job upload.
 * /*  w ww.j  a v  a2s . c o m*/
 * @param parts
 * @param httpHeaders
 * @param uriInfo
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
@POST
@Consumes(Constants.MULTIPART_CONTENT_TYPE)
// force content type to plain XML and JSON (browsers choke on subtypes)
@Produces({ Constants.XML_CONTENT_TYPE, Constants.JSON_CONTENT_TYPE })
public Response handleMultipartFormJob(final List<Attachment> parts, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {
    String applicationName = null;
    final Map<String, Serializable> jobMeta = new HashMap<String, Serializable>();

    for (final Attachment part : parts) {
        final String partName = getPartName(part);
        if (StringUtils.equals(partName, Constants.APPLICATION_NAME_HTTP_HEADER)) {
            applicationName = part.getObject(String.class);
        } else if (StringUtils.startsWith(partName, Constants.RSB_META_HEADER_HTTP_PREFIX)) {
            final String metaName = StringUtils.substringAfter(partName, Constants.RSB_META_HEADER_HTTP_PREFIX);
            final String metaValue = part.getObject(String.class);
            if (StringUtils.isNotEmpty(metaValue)) {
                jobMeta.put(metaName, metaValue);
            }
        }
    }

    final String finalApplicationName = applicationName;

    return handleNewJob(finalApplicationName, httpHeaders, uriInfo, new JobBuilder() {
        @Override
        public AbstractJob build(final String applicationName, final UUID jobId,
                final GregorianCalendar submissionTime) throws IOException {

            final MultiFilesJob job = new MultiFilesJob(Source.REST, applicationName, getUserName(), jobId,
                    submissionTime, jobMeta);

            for (final Attachment part : parts) {
                if (StringUtils.equals(getPartName(part), Constants.JOB_FILES_MULTIPART_NAME)) {
                    final InputStream data = part.getDataHandler().getInputStream();
                    if (data.available() == 0) {
                        // if the form is submitted with no file attached, we get
                        // an empty part
                        continue;
                    }
                    MultiFilesJob.addDataToJob(part.getContentType().toString(), getPartFileName(part), data,
                            job);
                }
            }

            return job;
        }
    });
}