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:in.com.ralarm.AlarmActivity.java

public String loadJSONFromAsset() {
    String json = null;/* w  w  w  .  jav a2s. co  m*/
    try {
        InputStream is = AlarmActivity.this.getAssets().open("med.txt");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

From source file:me.kafeitu.activiti.extra.helper.ProcessDefinitionHelper.java

/**
 * //w  w w  . j  a va  2s. co  m
 * 
 * @return 
 */
public String exportDiagramToFile(ProcessDefinition processDefinition, String exportDir) throws IOException {
    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();
    }
    if (diagramResourceName.contains("/")) {
        diagramResourceName = diagramResourceName.replaceAll("/", ".");
    }
    diagramPath = diagramDir + "/" + diagramResourceName;
    File file = new File(diagramPath);

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

    logger.debug("export diagram to : {}", diagramPath);

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

From source file:corpixmgr.handler.CorpixPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from   w w  w  .jav  a 2s. c o  m*/
 */
protected void parseImportParams(HttpServletRequest request) throws CorpixException {
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //System.out.println("Parsing import params");
        if (isMultipart) {
            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("UTF-8");
                        processField(fieldName, contents);
                    }
                } else if (item.getName().length() > 0) {
                    fileName = item.getName();
                    InputStream is = item.getInputStream();
                    ByteArrayOutputStream bh = new ByteArrayOutputStream();
                    while (is.available() > 0) {
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        bh.write(b);
                    }
                    fileData = bh.toByteArray();
                }
            }
        } else {
            Map tbl = request.getParameterMap();
            Set<String> keys = tbl.keySet();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String[] values = (String[]) tbl.get(key);
                for (int i = 0; i < values.length; i++)
                    processField(key, values[i]);
            }
        }
    } catch (Exception e) {
        throw new CorpixException(e);
    }
}

From source file:com.feilong.controller.DownloadController.java

public HttpServletResponse download(String path, HttpServletResponse response) {
    try {/*from  w  w  w. j  a v  a  2 s .  c o  m*/
        // path
        File file = new File(path);
        // ???
        String filename = file.getName();
        // ????
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();
        // responseHeader
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return response;
}

From source file:info.magnolia.cms.filters.MultipartRequestFilterTempFileDeletionTest.java

private void checkMultipartForm(MultipartForm form, String expectedDocumentType) throws IOException {
    assertNotNull("MultipartForm request attribute expected", form);
    assertEquals(3, form.getParameters().size());
    assertEquals("value1", form.getParameter("param1"));
    assertEquals("", form.getParameter("param2"));

    String[] value3 = form.getParameterValues("param3");
    assertNotNull("multi-value parameter has not been parsed", value3);
    assertEquals(2, value3.length);//w  w w. j a v a 2 s.co  m

    assertEquals(1, form.getDocuments().size());

    Document document = form.getDocument("document");
    assertNotNull("expected non-null Document", document);
    assertEquals("document", document.getAtomName());
    assertEquals("xml", document.getExtension());
    assertEquals("pom", document.getFileName());
    assertEquals("pom.xml", document.getFileNameWithExtension());
    assertEquals(testFile.length(), document.getLength());

    assertEquals(expectedDocumentType, document.getType());

    assertTrue(document.getType().startsWith("text/xml"));

    File documentFile = document.getFile();
    assertTrue(documentFile.exists());
    assertTrue(documentFile.canRead());
    InputStream stream1 = document.getStream();
    assertEquals(testFile.length(), stream1.available());
    assertEquals(testFile.length(), stream1.skip(testFile.length()));
    assertEquals(0, stream1.available());
    documentFile.deleteOnExit();
}

From source file:de.elomagic.mag.AbstractTest.java

protected Future<byte[]> createFileExistsFuture(Path file) {

    ExecutorService executor = Executors.newFixedThreadPool(2);

    FutureTask<byte[]> futureTask = new FutureTask<>(() -> {
        byte[] result = null;
        do {/*from www  .  j  av a2  s .  co  m*/
            if (Files.exists(file)) {
                InputStream in = Files.newInputStream(file, StandardOpenOption.READ);
                result = IOUtils.readFully(in, in.available());
            }

            Thread.sleep(100);
        } while (result == null);

        return result;
    });

    executor.execute(futureTask);

    return futureTask;
}

From source file:org.mobisocial.corral.CorralS3Connector.java

public void uploadToServer(String ticket, final EncRslt rslt, String datestr, String objName,
        final UploadProgressCallback callback) throws ClientProtocolException, IOException {
    callback.onProgress(UploadState.PREPARING_UPLOAD, 0);
    Log.d(TAG, "-----UPLOAD START-----");
    Log.d(TAG, "URI: " + rslt.uri.toString());
    Log.d(TAG, "length: " + rslt.length);
    Log.d(TAG, "ticket: " + ticket);
    Log.d(TAG, SERVER_URL + objName);
    Log.d(TAG, "Authorization: AWS " + ticket);
    Log.d(TAG, "Content-Md5: " + rslt.md5);
    Log.d(TAG, "Content-Type: " + CONTENT_TYPE);
    Log.d(TAG, "Date: " + datestr);

    InputStream in = mContext.getContentResolver().openInputStream(rslt.uri);
    final int contentLength = in.available();

    HttpClient http = new DefaultHttpClient();
    HttpPut put = new HttpPut(SERVER_URL + objName);

    put.setHeader("Authorization", "AWS " + ticket);
    put.setHeader("Content-Md5", rslt.md5);
    put.setHeader("Content-Type", CONTENT_TYPE);
    put.setHeader("Date", datestr);

    HttpEntity progress = new ProgressEntity(callback, rslt, contentLength);

    put.setEntity(progress);//from  w  ww . j  a  v a  2  s. c o m
    HttpResponse response = http.execute(put);
    final int responseCode = response.getStatusLine().getStatusCode();

    // FOR DEBUG
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException("invalid response code, " + responseCode);
    }
}

From source file:br.com.bluesoft.pronto.controller.SprintController.java

@RequestMapping("/sprint/imagem.action")
public String imagem(final HttpServletResponse response, final int sprintKey) throws Exception {

    final String folderPath = Config.getImagesFolder() + "/sprints/";

    final File arquivo = new File(folderPath + sprintKey);

    final byte[] bytes;
    if (arquivo.exists()) {
        final FileInputStream fis = new FileInputStream(arquivo);
        final int numberBytes = fis.available();
        bytes = new byte[numberBytes];
        fis.read(bytes);//from w  w  w.  ja va  2  s  .  co  m
        fis.close();
    } else {
        final InputStream resource = this.getClass().getResourceAsStream("/noImage.jpg");
        final int numberBytes = resource.available();
        bytes = new byte[numberBytes];
        resource.read(bytes);
        resource.close();
    }

    response.getOutputStream().write(bytes);
    return null;

}

From source file:gov.nih.nci.restgen.util.JarHelper.java

public void unjar(File jarFile, String destdir) throws IOException {
    java.util.jar.JarFile jarfile = new java.util.jar.JarFile(jarFile);
    java.util.Enumeration<java.util.jar.JarEntry> enu = jarfile.entries();
    while (enu.hasMoreElements()) {
        java.util.jar.JarEntry je = enu.nextElement();

        java.io.File fl = new java.io.File(destdir + File.separator + je.getName());
        if (!fl.exists()) {
            fl.getParentFile().mkdirs();
            fl = new java.io.File(destdir + File.separator + je.getName());
        }//from   w  w  w  .jav  a2s. co m
        if (je.isDirectory()) {
            continue;
        }
        java.io.InputStream is = jarfile.getInputStream(je);
        java.io.FileOutputStream fo = new java.io.FileOutputStream(fl);
        while (is.available() > 0) {
            fo.write(is.read());
        }
        fo.close();
        is.close();
    }
}

From source file:com.turn.splicer.Config.java

public void writeAsJson(JsonGenerator jgen) throws IOException {
    if (properties == null) {
        jgen.writeStartObject();//  ww  w  . j  a va  2  s.  c o m
        jgen.writeEndObject();
        return;
    }

    TreeMap<String, String> map = new TreeMap<>();
    for (Map.Entry<Object, Object> e : properties.entrySet()) {
        map.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
    }

    InputStream is = getClass().getClassLoader().getResourceAsStream(VERSION_FILE);
    if (is != null) {
        LOG.debug("Loaded {} bytes of version file configuration", is.available());
        Properties versionProps = new Properties();
        versionProps.load(is);
        for (Map.Entry<Object, Object> e : versionProps.entrySet()) {
            map.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
    } else {
        LOG.error("No version file found on classpath. VERSION_FILE={}", VERSION_FILE);
    }

    jgen.writeStartObject();
    for (Map.Entry<String, String> e : map.entrySet()) {
        if (e.getValue().indexOf(',') > 0) {
            splitList(e.getKey(), e.getValue(), jgen);
        } else {
            jgen.writeStringField(e.getKey(), e.getValue());
        }
    }
    jgen.writeEndObject();
}