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.yunmel.syncretic.utils.io.IOUtils.java

/**
 * (??)/*from   w ww.  j a  va  2 s . com*/
 * 
 * @param response
 * @param is ?
 * @param realName ??
 */
public static void downloadFile(HttpServletResponse response, InputStream is, String realName) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        response.setContentType("text/html;charset=UTF-8");
        // request.setCharacterEncoding("UTF-8");
        long fileLength = is.available();

        response.setContentType("application/octet-stream");
        realName = new String(realName.getBytes("GBK"), "ISO8859-1");
        response.setHeader("Content-disposition", "attachment; filename=" + realName);
        response.setHeader("Content-Length", String.valueOf(fileLength));
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (Exception e) {
        // e.printStackTrace();//???
    } finally {
        try {
            bos.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.enioka.jqm.tools.DeliverableTest.java

/**
 * Same as above, except authentication is disabled as well as SSL.
 *//*from www.  j a  va 2  s .  c  om*/
@Test
public void testGetOneDeliverableWithoutAuth() throws Exception {
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);
    Helpers.setSingleParam("enableWsApiSsl", "false", em);

    int jobId = JqmSimpleTest.create(em, "pyl.EngineApiSendDeliverable")
            .addDefParameter("filepath", TestHelpers.node.getDlRepo())
            .addDefParameter("fileName", "jqm-test-deliverable3.txt").run(this);

    File f = new File(TestHelpers.node.getDlRepo() + "jqm-test-deliverable3.txt");
    Assert.assertEquals(false, f.exists()); // file should have been moved

    List<com.enioka.jqm.api.Deliverable> files = JqmClientFactory.getClient().getJobDeliverables(jobId);
    Assert.assertEquals(1, files.size());

    InputStream tmp = JqmClientFactory.getClient().getDeliverableContent(files.get(0));
    Assert.assertTrue(tmp.available() > 0);
    String res = IOUtils.toString(tmp);
    Assert.assertTrue(res.startsWith("Hello World!"));

    tmp.close();
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w .ja va2s . c  o  m
 *
 * @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[] Fielname = new String[2];
    CallableStatement pro;
    int i = 0;
    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);
                        if (i == 0) {
                            Fielname[0] = new String(b);
                        } else {
                            Fielname[1] = new String(b);
                        }
                        i++;
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT(?,?,?)}");
                pro.setString(1, name);
                pro.setString(2, Fielname[0]);
                pro.setString(3, Fielname[1]);
                pro.executeQuery();
                pro.close();
                connect.close();
                request.setAttribute("message", "File Uploaded Successfully");
                request.setAttribute("name", name);
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
        out.print("Description:" + Fielname[0]);
        out.print("Locator:" + Fielname[1]);
        String pathReal = getServletContext().getRealPath("\\uploads\\");
        request.setAttribute("Description", Fielname[0]);
        request.setAttribute("Locator", Fielname[1]);
        request.setAttribute("path", pathReal);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:com.enioka.jqm.tools.DeliverableTest.java

/**
 * Retrieve a remote file with authentication, without SSL.
 *//*w  ww.j a v  a  2s.  c  o  m*/
@Test
public void testGetOneDeliverableWithAuth() throws Exception {
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "true", em);
    Helpers.setSingleParam("enableWsApiSsl", "false", em);

    int jobId = JqmSimpleTest.create(em, "pyl.EngineApiSendDeliverable")
            .addDefParameter("filepath", TestHelpers.node.getDlRepo())
            .addDefParameter("fileName", "jqm-test-deliverable2.txt").run(this);

    File f = new File(TestHelpers.node.getDlRepo() + "jqm-test-deliverable2.txt");
    Assert.assertEquals(false, f.exists()); // file should have been moved

    List<com.enioka.jqm.api.Deliverable> files = JqmClientFactory.getClient().getJobDeliverables(jobId);
    Assert.assertEquals(1, files.size());

    InputStream tmp = JqmClientFactory.getClient().getDeliverableContent(files.get(0));

    Assert.assertTrue(tmp.available() > 0);
    String res = IOUtils.toString(tmp);
    Assert.assertTrue(res.startsWith("Hello World!"));

    tmp.close();
}

From source file:edu.umich.eecs.lab11.summon.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init();
    wv = ((WebView) appView.getEngine().getView());
    wv.addJavascriptInterface(new JavaScriptInterface(getPackageManager()), "gateway");
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setSupportMultipleWindows(false);
    wv.getSettings().setNeedInitialFocus(false);
    wv.getSettings().setSupportZoom(false);
    wv.getSettings().setAllowFileAccess(true);
    wv.getSettings().setAppCacheEnabled(true);
    wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    wv.getSettings().setAppCachePath(wv.getContext().getCacheDir().getAbsolutePath());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setTaskDescription(new TaskDescription(null, null, Color.parseColor("#FFC107")));
    loadUrl(launchUrl);//from  w w w.j  a  va2s.  c o m
    try {
        InputStream is = getAssets().open("www/summon.android.js");
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        js = "javascript:(function(){ " + "s=document.createElement('script');" + "s.innerHTML = atob('"
                + Base64.encodeToString(buffer, Base64.NO_WRAP) + "'); "
                + "document.querySelector('head').appendChild(s); " + "})()";
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.xpn.xwiki.doc.XWikiAttachmentTest.java

/**
 * Create an attachment, populate it with enough data to make it flush to disk cache,
 * read back data and make sure it's the same.
 *//*from w w w  . j a  va 2  s .c o  m*/
@Test
public void testStoreContentInDiskCache() throws Exception {
    int attachLength = 20000;
    // Check for data dependent errors.
    int seed = (int) System.currentTimeMillis();
    final XWikiAttachment attach = new XWikiAttachment();
    final InputStream ris = new RandomInputStream(attachLength, seed);
    attach.setContent(ris);
    Assert.assertEquals("Not all of the stream was read", 0, ris.available());
    Assert.assertTrue(IOUtils.contentEquals(new RandomInputStream(attachLength, seed),
            attach.getAttachment_content().getContentInputStream()));
}

From source file:gemlite.core.internal.support.jpa.files.service.JarFileService.java

public ReleasedJarFile deploy(URL url) {
    RegistryMatchedContext m = null;//from   ww  w. java2s .  c o  m
    try {
        m = GemliteDeployer.getInstance().scan(url);
        if (m == null) {
            throw new GemliteException("No module define found.");
        }
        LogUtil.getCoreLog().info("Module " + m.getModuleName() + " type:" + m.getModuleType());
        ReleasedJarFile jarFile = new ReleasedJarFile();
        jarFile.setModuleName(m.getModuleName());
        jarFile.setModuleType(m.getModuleType());
        // Gemlite-runtime-0.0.1-SNAPSHOT.jar
        String fname = null;
        try {
            fname = url.toURI().toURL().getFile();
        } catch (MalformedURLException | URISyntaxException e) {
            throw new GemliteException("Not a vaild url:" + url, e);
        }
        if (!splitVersion(jarFile, fname)) {
            LogUtil.getCoreLog().warn("Cann't find version no for file {}.", fname);
        }
        byte[] bytes = null;
        try {
            InputStream in = url.openStream();
            bytes = new byte[in.available()];
            in.read(bytes);
            in.close();
        } catch (IOException e) {
            throw new GemliteException(fname + " can not read bytes.", e);
        }
        jarFile.setFileName(fname);
        jarFile.setContent(bytes);
        jarFile.setMd5_str(Util.makeMD5String(bytes));
        jarFile.setUpdate_count(1);
        jarFile.setUpload_time(new Date());

        if (!checkDuplicate(jarFile)) {
            LogUtil.getCoreLog().warn("{} has no change.", jarFile.getFileName());
            // throw new GemliteException(jarFile.getFileName() + " has no change.");
        }
        return jarFile;
    } finally {
        if (m != null && m.getLoader() != null)
            m.getLoader().clean();
    }
}

From source file:de.jadehs.jadehsnavigator.fragment.NewsFragment.java

public String loadJSONFromAsset() {
    String json;/*from   ww  w  . j a v  a 2s. c o m*/
    try {
        InputStream is = getActivity().getAssets().open("origins.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        Log.wtf("JSON", "ERR", ex);
        return null;
    }
    return json;
}

From source file:net.krotscheck.util.ResourceUtilTest.java

/**
 * Assert that nonexistent files provide the expected response.
 *
 * @throws Exception Should not be thrown.
 *//*  w w  w .j av  a  2 s  .  c o  m*/
@Test
public void testGetNonexistentResource() throws Exception {
    String name = "/invalid-resource-file.txt";
    InputStream stream = ResourceUtil.getResourceAsStream(name);
    Assert.assertFalse(stream.available() > 0);

    String content = ResourceUtil.getResourceAsString(name);
    Assert.assertEquals("", content);
}