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.wavemaker.common.util.ClassLoaderUtilsTest.java

public void testTempClassLoader_getResource() throws Exception {

    File sourceJar = new ClassPathResource("com/wavemaker/common/foojar.jar").getFile();
    File jar = File.createTempFile("testTempClassLoader_getClass", ".jar");
    jar.deleteOnExit();//from  w ww  .  j  a v a 2  s .  c  o  m
    FileUtils.copyFile(sourceJar, jar);

    try {
        ClassLoader cl = ClassLoaderUtils.getTempClassLoaderForFile(jar);
        InputStream is = ClassLoaderUtils.getResourceAsStream("foo/bar/baz/JarType.java", cl);
        assertNotNull(is);
        assertTrue(is.available() > 0);
        is.close();
    } finally {
        jar.delete();
    }
}

From source file:com.papteco.client.netty.QuartzMailBackupClientHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // Echo back the received object to the server.
    ClientRequestBean bean = (ClientRequestBean) msg;
    bean.setActionType(NettyConstant.MAILBKP_UP_ACTION_TYPE);
    String[] lastMailFile = FileActionUtils.getLastModifiedFile(EnvConstant.LCL_MAILFILE_PATH);
    if (lastMailFile != null && StringUtils.isNotEmpty(lastMailFile[1])) {
        if (bean.getTimestamp() != null && Long.valueOf(lastMailFile[1]) <= Long.valueOf(bean.getTimestamp())) {
            // System.out.println("No Mail-File's update.");
        } else {/*w ww .  j  av a  2  s .com*/
            File file = new File(lastMailFile[0]);
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            bean.setPrjObj(buffer);
            bean.setTimestamp(lastMailFile[1]);
            bean.setMailfileSuffix(lastMailFile[2]);
        }
    }
    ctx.write(bean);
}

From source file:com.epam.wilma.test.server.PerformanceTestHandler.java

/**
 * Constructor reads xml from file.//from ww w.  j a  v  a2s. c  o  m
 * @throws IOException when converting to byte array fails.
 */
public PerformanceTestHandler() throws IOException {
    InputStream xmlLarge = getXmlFromFile("response_large.fis");
    xmlLargeAsBytes = IOUtils.toByteArray(xmlLarge, xmlLarge.available());

    InputStream xmlMax = getXmlFromFile("response_max.fis");
    xmlMaxAsBytes = IOUtils.toByteArray(xmlMax, xmlMax.available());

    InputStream xmlMin = getXmlFromFile("response_min.fis");
    xmlMinAsBytes = IOUtils.toByteArray(xmlMin, xmlMin.available());

    InputStream xmlSmall = getXmlFromFile("response_small.fis");
    xmlSmallAsBytes = IOUtils.toByteArray(xmlSmall, xmlSmall.available());

}

From source file:Functions.UploadFileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String houseId = "";
    String owner = (String) request.getSession().getAttribute("username");
    String url = "/errorPage.jsp";
    String message = "fgd";
    //System.out.println("houseId= "+houseId);
    //System.out.println("owner= "+owner);
    response.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/*from  w ww  .  j a v  a2  s .  c om*/
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do something
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte b[] = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    if ("houseIddd".equals(fieldName)) {
                        houseId = value;
                    }
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                } else {
                    System.out.println("MPHKE STO ELSE GIA NA BALEI SPITIA");
                    //upload file
                    String path = getServletContext().getRealPath("/");
                    //String path = getServletContext().getContextPath()+"/";

                    if (FileUpload.processFile(path, item, houseId, owner)) {
                        System.out.println("MPHKE STO processfile!");
                        //response.getWriter().println("file uploaded successfully");
                        message = "file uploaded successfully";

                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                    } else {
                        message = "file uploading failed";
                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                        //response.getWriter().println("file uploading failed");
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            //Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }
}

From source file:base.compilations.JavaCompilation.java

@Override
protected List<CompilationError> processStream(InputStream stream) throws IOException {
    System.out.println("stream: " + stream.available());

    List<CompilationError> errors = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
        int partsCount = 2;
        int count = 0;
        String colonSymbol = ":";
        String fileExtKeyWord = fileExtention + colonSymbol;
        String errorKeyWord = "error" + colonSymbol;
        String line;//from   w  w  w .j a  v a  2  s . com
        while ((line = reader.readLine()) != null) {
            if (count > 0) {
                CompilationError error = errors.get(errors.size() - 1);
                error.setCode(error.getCode() + line + "\n");
                count--;
            } else if (line.contains(fileExtention) && line.contains(errorKeyWord)) {
                CompilationError error = new CompilationError();

                int firstColon = line.indexOf(fileExtKeyWord) + fileExtKeyWord.length();
                int secondColon = line.indexOf(colonSymbol, firstColon);
                String lineAsStr = line.substring(firstColon, secondColon);
                int lineNum = Integer.parseInt(lineAsStr);
                error.setLine(lineNum);

                int startingErrorText = line.indexOf(errorKeyWord) + errorKeyWord.length();
                String errorText = line.substring(startingErrorText);
                error.setErrorText(errorText);

                errors.add(error);
                count = partsCount;
            }
            //                if (count % 3 == 2) {
            //                    CompilationError error = errors.get(errors.size() - 1);
            //                    error.setCode(line);
            //                }
            //                else {
            //                    CompilationError error = errors.get(errors.size() - 1);
            //                    String code = error.getCode() + "\n";
            //                    code += line;
            //                    error.setCode(code);
            //                }
            //                count ++;
        }
    }
    System.out.println("---------------");
    for (CompilationError error : errors) {
        System.out.println(error);
    }
    System.out.println("---------------");
    return errors;
}

From source file:com.wavemaker.commons.util.utils.ClassLoaderUtilsTest.java

@Test
public void tempClassLoader_getResourceTest() throws Exception {

    File sourceJar = new ClassPathResource("com/wavemaker/commons/foojar.jar").getFile();
    File jar = File.createTempFile("tempClassLoader_getClassTest", ".jar");
    jar.deleteOnExit();/*from  w w w  . ja  va  2s  . co m*/
    FileUtils.copyFile(sourceJar, jar);

    try {
        ClassLoader cl = ClassLoaderUtils.getTempClassLoaderForFile(jar);
        InputStream is = ClassLoaderUtils.getResourceAsStream("foo/bar/baz/JarType.java", cl);
        assertNotNull(is);
        assertTrue(is.available() > 0);
        is.close();
    } finally {
        jar.delete();
    }
}

From source file:VideoTestServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w . j av a  2s.  c om*/
 *
 * @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();

    final Part filePart = request.getPart("file");
    String filename = getFileName(filePart);
    InputStream filecontent = filePart.getInputStream();
    byte[] bytes = new byte[filecontent.available()];
    filecontent.read(bytes);

    /*OutputStream PDFprint = response.getOutputStream();
    PDFprint.write(bytes);
    if(PDFprint != null){
    PDFprint.close();
    }*/

    byte[] encoded = Base64.encodeBase64(bytes);
    String encodedString = new String(encoded);
    System.out.println(encodedString);
    String title = "Video Servlet";
    String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

    out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"
            + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n"
            + "<video width=\"320\" hieght=\"240\" controls>"
            + "<source type=\"video/webm\" src=\"data:video/webm;base64," + encodedString + "\">"
            + "Your browser does not support the video element" + "</video>" + "</body></html>");

}

From source file:com.navercorp.pinpoint.profiler.instrument.classloading.Java9DefineClassTest.java

@Test
public void defineClass() throws ClassNotFoundException, IOException {
    URL location = CodeSourceUtils.getCodeLocation(Logger.class);
    logger.debug("location:{}", location);

    URL[] empty = {};//from www.  jav a2 s .  c  om
    URLClassLoader classLoader = new URLClassLoader(empty, null);
    try {
        classLoader.loadClass(Logger.class.getName());
        Assert.fail();
    } catch (ClassNotFoundException ignore) {
    }

    String className = JavaAssistUtils.javaClassNameToJvmResourceName(Logger.class.getName());
    InputStream classStream = Logger.class.getClassLoader().getResourceAsStream(className);
    byte[] bytes = IOUtils.readFully(classStream, classStream.available());

    DefineClass defineClass = new Java9DefineClass();
    Class<?> defineClassSlf4jLogger = defineClass.defineClass(classLoader, Logger.class.getName(), bytes);
    Class<?> slf4jLogger = classLoader.loadClass(Logger.class.getName());

    Assert.assertSame(defineClassSlf4jLogger, slf4jLogger);
    Assert.assertSame(slf4jLogger.getClassLoader(), classLoader);

    Assert.assertNotSame(slf4jLogger.getClassLoader(), Logger.class.getClassLoader());

}

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

@Test
public void testMain() throws Exception {

    greeUser.deliver(createMimeMessage("TestFile.pdf"));

    main.start();//ww  w . ja  va 2 s .  c om

    Future future = createPutServletFuture(putServlet);
    future.get(500, TimeUnit.SECONDS);

    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    int fileSize = in.available();
    byte[] send = IOUtils.readFully(in, fileSize);

    Assert.assertEquals(fileSize, putServlet.lastContentLength);
    Assert.assertArrayEquals(send, putServlet.lastContent);
    Assert.assertTrue("Put filename doesn't match.",
            putServlet.requestedUri.startsWith("/inbox/unsorted/TestFile")
                    && putServlet.requestedUri.endsWith(".pdf"));
    Assert.assertNotEquals("/inbox/unsorted/TestFile", putServlet.requestedUri);
}

From source file:fr.mixit.android.io.JsonExecutor.java

public void executeAndInsert(Context context, String assetName, JsonHandlerApply handler)
        throws JsonHandlerException {
    try {/*from w  w w . j  a v  a 2s  .  co m*/
        final InputStream input = context.getAssets().open(assetName);
        final byte[] buffer = new byte[input.available()];
        while (input.read(buffer) != -1) {
            ;
        }
        final String jsontext = new String(buffer);
        executeAndInsert(jsontext, handler);
    } catch (final JsonHandlerException e) {
        throw e;
    } catch (final IOException e) {
        throw new JsonHandlerException("Problem parsing local asset: " + assetName, e);
    }
}