Example usage for java.io ByteArrayInputStream read

List of usage examples for java.io ByteArrayInputStream read

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream read.

Prototype

public synchronized int read() 

Source Link

Document

Reads the next byte of data from this input stream.

Usage

From source file:org.biokoframework.http.RequestWrapper.java

@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

    ServletInputStream inputStream = new ServletInputStream() {
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }//from   w ww .ja  va  2s . com

        @Override
        public boolean isFinished() {
            return byteArrayInputStream.available() > 0;
        }

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

        @Override
        public void setReadListener(ReadListener readListener) {
            // TODO Auto-generated method stub

        }
    };

    return inputStream;
}

From source file:com.google.jstestdriver.server.gateway.GatewayServletTest.java

License:asdf

public void testService_POST() throws Exception {
    expect(request.getMethod()).andStubReturn("POST");
    expect(request.getRequestURI()).andStubReturn("/relativeUri");
    final ByteArrayInputStream input = new ByteArrayInputStream("ASDF".getBytes());
    ServletInputStream in = new ServletInputStream() {
        @Override/* w w  w. j a v  a  2 s  .  c  o  m*/
        public int read() throws IOException {
            return input.read();
        }
    };
    expect(request.getInputStream()).andStubReturn(in);
    expect(request.getHeaderNames())
            .andStubReturn(Iterators.asEnumeration(ImmutableList.of("Host").iterator()));
    expect(request.getHeaders("Host"))
            .andStubReturn(Iterators.asEnumeration(ImmutableList.of("jstd:80").iterator()));
    expect(request.getQueryString()).andStubReturn("id=123");
    // TODO(rdionne): Feed fake response values into the captured HttpMethod and assert they are
    // properly converted to equivalent HttpServletResponse fields.
    Capture<HttpMethodBase> methodCapture = new Capture<HttpMethodBase>();
    expect(client.executeMethod(EasyMock.capture(methodCapture))).andStubReturn(200);
    /* expect */ response.setStatus(200);
    expect(request.getHeaders("Pragma")).andStubReturn(Iterators.asEnumeration(Iterators.emptyIterator()));
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    ServletOutputStream out = new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            output.write(b);
        }
    };
    expect(response.getOutputStream()).andStubReturn(out);
    control.replay();
    gateway.handleIt();
    ByteArrayOutputStream requestBody = new ByteArrayOutputStream();
    ((EntityEnclosingMethod) methodCapture.getValue()).getRequestEntity().writeRequest(requestBody);
    assertEquals("POST", methodCapture.getValue().getName());
    assertEquals("http://hostname/relativeUri?id=123", methodCapture.getValue().getURI().toString());
    assertEquals("hostname:80", methodCapture.getValue().getRequestHeader("Host").getValue());
    assertEquals("id=123", methodCapture.getValue().getQueryString());
    assertEquals("ASDF", requestBody.toString());
    assertEquals("", output.toString());
}

From source file:com.zk.common.waf.request.WafRequestWrapper.java

@Override
public ServletInputStream getInputStream() throws IOException {
    String bizBindMsg = "";
    ServletInputStream stream = null;/*from  w w  w.j a  v  a2  s .c o  m*/
    try {
        stream = request.getInputStream();
        bizBindMsg = IOUtils.toString(stream, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] buffer = null;
    try {
        buffer = bizBindMsg.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
    ServletInputStream newStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return bais.read();
        }
    };
    return newStream;
}

From source file:com.atolcd.alfresco.RequestWrapper.java

/**
 * Override of the getInputStream() method.
 * /*from w w w  .  j  av a  2 s .  c o  m*/
 * Return a new inputStream created from the stringRequest rather than
 * return the current inputStream, which may have been already read.
 */
@Override
public ServletInputStream getInputStream() throws IOException {
    ServletInputStream inputStream;
    if (!this.stringRequest.isEmpty()) {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringRequest.getBytes());
        inputStream = new ServletInputStream() {
            @Override
            public int read() throws IOException {
                try {
                    return byteArrayInputStream.read();
                } catch (Exception e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(e.getMessage(), e);
                    }
                    return 0;
                }
            }
        };
    } else
        inputStream = this.getRequest().getInputStream();

    return inputStream;
}

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  a v a2  s .c  o  m*/
    };
    return servletInputStream;
}

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

/**
 * Test of parseRequest method, of class Helper.
 *//*from   ww w  .ja  v a2  s .c  o  m*/
@Test
public void testParseRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    URL url = this.getClass().getResource("/prueba.txt");
    File testFile = new File(url.getFile());
    Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile),
            new FilePart("comon_file", testFile) };

    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());

    Helper.parseRequest(request);

}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterOutbound.java

@Override
public void receive(GeoEvent geoEvent) {

    stringBuffer.setLength(0);//w w w. java2  s.c  o  m
    GeoEventDefinition definition = geoEvent.getGeoEventDefinition();
    System.out.println("Creating Event to marshal...");
    Event event = new Event();
    for (FieldDefinition fieldDefinition : definition.getFieldDefinitions()) {
        try {
            String attributeName = fieldDefinition.getName();
            Object value;
            if ((value = geoEvent.getField(attributeName)) != null) {

                if (attributeName.equalsIgnoreCase("version")) {
                    event.setVersion((Double) value);
                } else if (attributeName.equalsIgnoreCase("uid")) {
                    event.setUid(value.toString());
                } else if (attributeName.equalsIgnoreCase("type")) {
                    event.setType(value.toString());
                } else if (attributeName.equalsIgnoreCase("how")) {
                    event.setHow(value.toString());
                } else if (attributeName.equalsIgnoreCase("time")) {
                    event.setTime((Date) value);
                } else if (attributeName.equalsIgnoreCase("start")) {
                    event.setStart((Date) value);
                } else if (attributeName.equalsIgnoreCase("stale")) {
                    event.setStale((Date) value);
                } else if (attributeName.equalsIgnoreCase("access")) {
                    event.setAccess(value.toString());
                } else if (attributeName.equalsIgnoreCase("opex")) {
                    event.setOpex(value.toString());
                } else if (attributeName.equalsIgnoreCase("qos")) {
                    event.setQos(value.toString());
                } else if (attributeName.equalsIgnoreCase("detail")) {
                    event.setDetail(this.unpackDetial(fieldDefinition, geoEvent.getFieldGroup("detail")));

                    // GETALLFIELDS
                    // CHECK ITS TYPE IF GROUP THEN INSPECT THEM
                } else if (attributeName.equalsIgnoreCase("point")) {
                    Point p = pointFromJson(value);
                    event.setPoint(pointFromJson(p));
                }
            }

        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

    }

    /////////////////////////
    String xmlResult = null;
    StringBuilder myResult = new StringBuilder();
    int content;

    System.out.println("Event created.");

    System.out.println("Marshalling Event into XML.");

    try {

        JAXBContext contextObj = JAXBContext.newInstance(Event.class);
        Marshaller marshallerObj = contextObj.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        marshallerObj.marshal(event, os);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());

        while ((content = bais.read()) != -1) {
            myResult.append((char) content);
        }

        xmlResult = fixEscapeCharacters(myResult.toString());
        System.out.println("**** XML RESULTS ***");
        System.out.println(xmlResult);
        //this.byteListener.receive(ByteBuffer.wrap(xmlResult.getBytes()), "");
        super.receive(ByteBuffer.wrap(xmlResult.getBytes()), "", geoEvent);
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Done");
}

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);/*  ww  w .  java2s .  com*/
    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.github.davidcarboni.encryptedfileupload.StreamingTest.java

/**
 * Test for FILEUPLOAD-135//from w w w .j  av  a  2  s.  co m
 */
public void testFILEUPLOAD135() throws IOException, FileUploadException {
    byte[] request = newShortRequest();
    final ByteArrayInputStream bais = new ByteArrayInputStream(request);
    List<FileItem> fileItems = parseUpload(new InputStream() {
        @Override
        public int read() throws IOException {
            return bais.read();
        }

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

    }, request.length);
    Iterator<FileItem> fileIter = fileItems.iterator();
    assertTrue(fileIter.hasNext());
    FileItem item = fileIter.next();
    assertEquals("field", item.getFieldName());
    byte[] bytes = item.get();
    assertEquals(3, bytes.length);
    assertEquals((byte) '1', bytes[0]);
    assertEquals((byte) '2', bytes[1]);
    assertEquals((byte) '3', bytes[2]);
    assertTrue(!fileIter.hasNext());
}

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//from  www.j a  v a 2s .com
        public int read() throws IOException {
            return inputStream.read();
        }
    };
    when(postRequest.getInputStream()).thenReturn(servletInputStream);
    return postRequest;
}