Example usage for javax.servlet ServletInputStream ServletInputStream

List of usage examples for javax.servlet ServletInputStream ServletInputStream

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream ServletInputStream.

Prototype


protected ServletInputStream() 

Source Link

Document

Does nothing, because this is an abstract class.

Usage

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

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);//from w ww  .  ja  va  2  s . c  o  m
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    req.setAttribute(isA(String.class), isA(Boolean.class));
    expect(req.getContentType()).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getHeader("Content-Type")).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
    expect(req.getQueryString()).andReturn("").anyTimes();
    expect(req.getContentLength()).andReturn(Integer.valueOf((int) multipart.getContentLength())).anyTimes();
    expect(req.getInputStream()).andReturn(servletInputStream);
    req.setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            final Object[] args = getCurrentArguments();
            checkMultipartForm((MultipartForm) args[1], expectedDocumentType);
            return null;
        }
    });
    webCtx.pop();

    replay(req, res, filterChain, webCtx);
    filter.doFilter(req, res, filterChain);
    verify(req, res, filterChain, webCtx);
}

From source file:com.mockey.server.RedoRequestWrapper.java

@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }//  w  w  w .  j ava 2s . c  om
    };
    return servletInputStream;
}

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

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    //GIVEN/*from  ww  w. j a  v  a 2 s .c  o  m*/
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    //WHEN
    req.setAttribute(isA(String.class), isA(Boolean.class));
    when(req.getContentType()).thenReturn(multipart.getContentType());
    when(req.getHeader("Content-Type")).thenReturn(multipart.getContentType());
    when(req.getCharacterEncoding()).thenReturn("UTF-8");
    when(req.getQueryString()).thenReturn("");
    when(req.getContentLength()).thenReturn(Integer.valueOf((int) multipart.getContentLength()));
    when(req.getInputStream()).thenReturn(servletInputStream);

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final Object args = invocation.getArguments()[1];
            checkMultipartForm((MultipartForm) args, expectedDocumentType);
            webCtx.setPostedForm((MultipartForm) args);
            return null;
        }
    }).when(req).setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    when(file.exists()).thenReturn(true);

    webCtx.pop();

    //THEN
    filter.doFilter(req, res, filterChain);
}

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilterTest.java

private HttpServletRequest mockPostRequest() throws IOException {
    HttpServletRequest postRequest = mockRequest("POST");
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("oldValue".getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
        @Override/*  w ww. jav a2 s  .c  om*/
        public int read() throws IOException {
            return inputStream.read();
        }
    };
    when(postRequest.getInputStream()).thenReturn(servletInputStream);
    return postRequest;
}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *///from   w  w  w.ja v  a  2s.c  om
@Test
public void testDoPostURLFail() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://falsa.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:com.nominanuda.web.http.ServletHelper.java

@SuppressWarnings("unchecked")
private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength,
        String ct, String cenc) throws IOException {
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        try {//  w  w w  . j  a va 2 s  .c om
            items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) {
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStream() {
                        public int read() throws IOException {
                            return is.read();
                        }

                        public int read(byte[] arg0) throws IOException {
                            return is.read(arg0);
                        }

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

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isFinished() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isReady() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public void setReadListener(ReadListener arg0) {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                        }
                    };
                }
            });
        } catch (FileUploadException e) {
            throw new IOException(e);
        }
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (FileItem i : items) {
            multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName()));
        }
        return multipartEntity;
    } else {
        InputStreamEntity entity = new InputStreamEntity(is, contentLength);
        entity.setContentType(ct);
        if (cenc != null) {
            entity.setContentEncoding(cenc);
        }
        return entity;
    }
}

From source file:org.jtwig.util.render.RenderHttpServletRequest.java

@Override
public ServletInputStream getInputStream() throws IOException {
    return new ServletInputStream() {
        ReadListener readListener;/*from  www .  j  ava2  s .  co  m*/

        @Override
        public boolean isFinished() {
            try {
                return content.available() != 0;
            } catch (IOException e) {
                return true;
            }
        }

        @Override
        public boolean isReady() {
            return !this.isFinished();
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            this.readListener = readListener;
        }

        @Override
        public int read() throws IOException {
            return content.read();
        }
    };
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

/**
 * Set the request/response details/*from   www  .  j a v a2 s .  c om*/
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @param registry
 *            ServiceRegistry
 * @param rootNode
 *            NodeRef
 */
public void setDetails(final HttpServletRequest req, HttpServletResponse resp, WebDAVHelper davHelper,
        NodeRef rootNode) {
    // Wrap the request so that it is 'retryable'. Calls to getInputStream() and getReader() will result in the
    // request body being read into an intermediate file.
    this.m_request = new HttpServletRequestWrapper(req) {

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (WebDAVMethod.this.m_reader != null) {
                throw new IllegalStateException("Reader in use");
            }
            if (WebDAVMethod.this.m_inputStream == null) {
                final FileInputStream in = new FileInputStream(getRequestBodyAsFile(req));
                WebDAVMethod.this.m_inputStream = new ServletInputStream() {

                    @Override
                    public int read() throws IOException {
                        return in.read();
                    }

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

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

                    @Override
                    public long skip(long n) throws IOException {
                        return in.skip(n);
                    }

                    @Override
                    public int available() throws IOException {
                        return in.available();
                    }

                    @Override
                    public void close() throws IOException {
                        in.close();
                    }

                    @Override
                    public void mark(int readlimit) {
                        in.mark(readlimit);
                    }

                    @Override
                    public void reset() throws IOException {
                        in.reset();
                    }

                    @Override
                    public boolean markSupported() {
                        return in.markSupported();
                    }
                };
            }

            return WebDAVMethod.this.m_inputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (WebDAVMethod.this.m_inputStream != null) {
                throw new IllegalStateException("Input Stream in use");
            }
            if (WebDAVMethod.this.m_reader == null) {
                String encoding = req.getCharacterEncoding();
                WebDAVMethod.this.m_reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(getRequestBodyAsFile(req)),
                                encoding == null ? "ISO-8859-1" : encoding));
            }

            return WebDAVMethod.this.m_reader;
        }

    };
    this.m_response = resp;
    this.m_davHelper = davHelper;
    this.m_rootNodeRef = rootNode;

    this.m_strPath = m_davHelper.getRepositoryPath(m_request);
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

@Override
public ServletInputStream getInputStream() throws IOException {
    byte[] bodyBytes = request.getBody().getBytes();
    if (request.isBase64Encoded()) {
        bodyBytes = Base64.getDecoder().decode(request.getBody());
    }/*ww  w.  j a  va 2 s.co m*/
    ByteArrayInputStream requestBodyStream = new ByteArrayInputStream(bodyBytes);
    return new ServletInputStream() {

        private ReadListener listener;

        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            listener = readListener;
            try {
                listener.onDataAvailable();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int read() throws IOException {
            int readByte = requestBodyStream.read();
            if (requestBodyStream.available() == 0 && listener != null) {
                listener.onAllDataRead();
            }
            return readByte;
        }
    };
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

private ServletInputStream createInputStreamForString(final String string) {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(string.getBytes());
    // CHECKSTYLE:OFF
    final ServletInputStream inputStream = new ServletInputStream() {
        // CHECKSTYLE:ON
        @Override/*from   w w  w.  jav  a2 s .c o m*/
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            // nothing
        }
    };
    return inputStream;
}