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.apache.shindig.gadgets.servlet.ServletUtilTest.java

@Test
public void testFromHttpServletRequest() throws Exception {
    HttpServletRequest original = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(original.getScheme()).andReturn("https");
    EasyMock.expect(original.getServerName()).andReturn("www.example.org");
    EasyMock.expect(original.getServerPort()).andReturn(444);
    EasyMock.expect(original.getRequestURI()).andReturn("/path/foo");
    EasyMock.expect(original.getQueryString()).andReturn("one=two&three=four");
    Vector<String> headerNames = new Vector<String>();
    headerNames.add("Header1");
    headerNames.add("Header2");
    EasyMock.expect(original.getHeaderNames()).andReturn(headerNames.elements());
    EasyMock.expect(original.getHeaders("Header1")).andReturn(makeEnumeration("HVal1", "HVal3"));
    EasyMock.expect(original.getHeaders("Header2")).andReturn(makeEnumeration("HVal2", "HVal4"));
    EasyMock.expect(original.getMethod()).andReturn("post");
    final ByteArrayInputStream bais = new ByteArrayInputStream("post body".getBytes());
    ServletInputStream sis = new ServletInputStream() {
        @Override//w  w w. j  ava  2  s .  c  o  m
        public int read() throws IOException {
            return bais.read();
        }
    };
    EasyMock.expect(original.getInputStream()).andReturn(sis);
    EasyMock.expect(original.getRemoteAddr()).andReturn("1.2.3.4");

    EasyMock.replay(original);
    HttpRequest request = ServletUtil.fromHttpServletRequest(original);
    EasyMock.verify(original);

    assertEquals(Uri.parse("https://www.example.org:444/path/foo?one=two&three=four"), request.getUri());
    assertEquals(3, request.getHeaders().size());
    assertEquals("HVal1", request.getHeaders("Header1").get(0));
    assertEquals("HVal3", request.getHeaders("Header1").get(1));
    assertEquals("HVal2", request.getHeaders("Header2").get(0));
    assertEquals("HVal4", request.getHeaders("Header2").get(1));
    assertEquals("post", request.getMethod());
    assertEquals("post body", request.getPostBodyAsString());
    assertEquals("1.2.3.4", request.getParam(ServletUtil.REMOTE_ADDR_KEY));
}

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

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    //GIVEN/*w ww.j  a v  a2s .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:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *//*from w w w.  j  a  va 2 s  . c  o m*/
@Test
public void testDoPost() 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://www.ua.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:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *///from w  ww  .  j a va  2  s .com
@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.nokia.carbide.installpackages.InstallPackages.java

private URL getAvailablePackagesURL() throws Exception {
    URL url = null;//from w w  w.  j  a  va  2s . c  o  m

    // see if the file is local (Ed's hack for testing...)
    String masterFilePathStr = getMasterFilePath();
    url = new URL(masterFilePathStr);
    if (url.getProtocol().equals("file")) {
        return url;
    }

    // else, read the file to a local temporary location
    GetMethod getMethod = new GetMethod(masterFilePathStr);
    HttpClient client = new HttpClient();
    setProxyData(client, getMethod);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    int serverStatus = 0;
    byte[] responseBody;
    try {
        serverStatus = client.executeMethod(getMethod);
        responseBody = getMethod.getResponseBody();
    } catch (Exception e) {
        // could be HttpException or IOException
        throw new Exception(e);
    } finally {
        getMethod.releaseConnection();
    }

    // HTTP status codes: 2xx = Success
    if (serverStatus >= 200 && serverStatus < 300) {
        File tempDir = FileUtils.getTemporaryDirectory();
        IPath path = new Path(tempDir.getAbsolutePath());
        IPath masterFilePath = path.append(getMasterFileName());
        File masterFile = masterFilePath.toFile();
        if (masterFile.exists())
            masterFile.delete();
        FileOutputStream fos = new FileOutputStream(masterFile);
        BufferedOutputStream out = new BufferedOutputStream(fos);
        ByteArrayInputStream in = new ByteArrayInputStream(responseBody);
        boolean foundOpenBrace = false;
        int c;
        while ((c = in.read()) != -1) {
            if (c == '<')
                foundOpenBrace = true;
            if (foundOpenBrace)
                out.write(c);
        }
        out.close();
        in.close();
        url = masterFile.toURI().toURL();

        return url;
    }
    return null;
}

From source file:org.apache.hadoop.hbase.io.hfile.TestFixedFileTrailer.java

@Test
public void testTrailerForV2NonPBCompatibility() throws Exception {
    if (version == 2) {
        FixedFileTrailer t = new FixedFileTrailer(version, HFileReaderV2.MINOR_VERSION_NO_CHECKSUM);
        t.setDataIndexCount(3);//w  ww .ja v  a  2 s .  co  m
        t.setEntryCount(((long) Integer.MAX_VALUE) + 1);
        t.setLastDataBlockOffset(291);
        t.setNumDataIndexLevels(3);
        t.setComparatorClass(KeyValue.COMPARATOR.getClass());
        t.setFirstDataBlockOffset(9081723123L); // Completely unrealistic.
        t.setUncompressedDataIndexSize(827398717L); // Something random.
        t.setLoadOnOpenOffset(128);
        t.setMetaIndexCount(7);
        t.setTotalUncompressedBytes(129731987);

        {
            DataOutputStream dos = new DataOutputStream(baos); // Limited scope.
            serializeAsWritable(dos, t);
            dos.flush();
            assertEquals(FixedFileTrailer.getTrailerSize(version), dos.size());
        }

        byte[] bytes = baos.toByteArray();
        baos.reset();
        assertEquals(bytes.length, FixedFileTrailer.getTrailerSize(version));

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        {
            DataInputStream dis = new DataInputStream(bais);
            FixedFileTrailer t2 = new FixedFileTrailer(version, HFileReaderV2.MINOR_VERSION_NO_CHECKSUM);
            t2.deserialize(dis);
            assertEquals(-1, bais.read()); // Ensure we have read everything.
            checkLoadedTrailer(version, t, t2);
        }
    }
}

From source file:org.apache.hadoop.hbase.io.hfile.TestFixedFileTrailer.java

@Test
public void testTrailer() throws IOException {
    FixedFileTrailer t = new FixedFileTrailer(version, HFileReaderV2.PBUF_TRAILER_MINOR_VERSION);
    t.setDataIndexCount(3);/* w ww.ja va2s .c  o  m*/
    t.setEntryCount(((long) Integer.MAX_VALUE) + 1);

    t.setLastDataBlockOffset(291);
    t.setNumDataIndexLevels(3);
    t.setComparatorClass(KeyValue.COMPARATOR.getClass());
    t.setFirstDataBlockOffset(9081723123L); // Completely unrealistic.
    t.setUncompressedDataIndexSize(827398717L); // Something random.

    t.setLoadOnOpenOffset(128);
    t.setMetaIndexCount(7);

    t.setTotalUncompressedBytes(129731987);

    {
        DataOutputStream dos = new DataOutputStream(baos); // Limited scope.
        t.serialize(dos);
        dos.flush();
        assertEquals(dos.size(), FixedFileTrailer.getTrailerSize(version));
    }

    byte[] bytes = baos.toByteArray();
    baos.reset();

    assertEquals(bytes.length, FixedFileTrailer.getTrailerSize(version));

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

    // Finished writing, trying to read.
    {
        DataInputStream dis = new DataInputStream(bais);
        FixedFileTrailer t2 = new FixedFileTrailer(version, HFileReaderV2.PBUF_TRAILER_MINOR_VERSION);
        t2.deserialize(dis);
        assertEquals(-1, bais.read()); // Ensure we have read everything.
        checkLoadedTrailer(version, t, t2);
    }

    // Now check what happens if the trailer is corrupted.
    Path trailerPath = new Path(util.getDataTestDir(), "trailer_" + version);

    {
        for (byte invalidVersion : new byte[] { HFile.MIN_FORMAT_VERSION - 1, HFile.MAX_FORMAT_VERSION + 1 }) {
            bytes[bytes.length - 1] = invalidVersion;
            writeTrailer(trailerPath, null, bytes);
            try {
                readTrailer(trailerPath);
                fail("Exception expected");
            } catch (IllegalArgumentException ex) {
                // Make it easy to debug this.
                String msg = ex.getMessage();
                String cleanMsg = msg.replaceAll("^(java(\\.[a-zA-Z]+)+:\\s+)?|\\s+\\(.*\\)\\s*$", "");
                assertEquals("Actual exception message is \"" + msg + "\".\n" + "Cleaned-up message", // will be followed by " expected: ..."
                        "Invalid HFile version: " + invalidVersion, cleanMsg);
                LOG.info("Got an expected exception: " + msg);
            }
        }

    }

    // Now write the trailer into a file and auto-detect the version.
    writeTrailer(trailerPath, t, null);

    FixedFileTrailer t4 = readTrailer(trailerPath);

    checkLoadedTrailer(version, t, t4);

    String trailerStr = t.toString();
    assertEquals("Invalid number of fields in the string representation " + "of the trailer: " + trailerStr,
            NUM_FIELDS_BY_VERSION[version - 2], trailerStr.split(", ").length);
    assertEquals(trailerStr, t4.toString());
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.html.helper.DefaultHtmlContentGenerator.java

private boolean isPNG(final ByteArrayInputStream data) {
    final int[] PNF_FINGERPRINT = { 137, 80, 78, 71, 13, 10, 26, 10 };
    for (int i = 0; i < PNF_FINGERPRINT.length; i++) {
        if (PNF_FINGERPRINT[i] != data.read()) {
            return false;
        }/*ww w. java 2s. c  o  m*/
    }
    return true;
}

From source file:screenieup.MixtapeUpload.java

private void send(byte[] b, HttpURLConnection conn) throws IOException {
    System.out.println("entered sendfile");
    String introline = "------" + boundary;
    String padder = String.format("Content-Disposition: form-data; name=\"files[]\"; filename=\"" + filename
            + "." + extension + "\"\r\nContent-type: " + tmpfiletype + "\r\n");
    String outroline = "------" + boundary + "--";

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    DataOutputStream outstream;/*from ww w.  j a v a  2s .co m*/
    try {
        outstream = new DataOutputStream(conn.getOutputStream());
        outstream.writeBytes(introline);
        outstream.writeBytes("\r\n");
        outstream.writeBytes(padder);
        outstream.writeBytes("\r\n");

        int i;
        while ((i = bais.read()) > -1) {
            outstream.write(i);

        }
        bais.close();

        outstream.writeBytes("\r\n");
        outstream.writeBytes("\r\n");
        outstream.writeBytes(outroline);
        outstream.flush();
        outstream.close();
    } catch (IOException ex) {
        if (ex instanceof SSLHandshakeException) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null,
                    "You need to add Let's Encrypt's certificates to your Java CA Certificate store.");
        } else {
            throw ex;
        }
    }
}

From source file:com.github.devnied.emvnfccard.parser.EmvParser.java

/**
 * Extract list of application file locator from Afl response
 *
 * @param pAfl/*w  ww  . jav  a 2s.co m*/
 *            AFL data
 * @return list of AFL
 */
protected List<Afl> extractAfl(final byte[] pAfl) {
    List<Afl> list = new ArrayList<Afl>();
    ByteArrayInputStream bai = new ByteArrayInputStream(pAfl);
    while (bai.available() >= 4) {
        Afl afl = new Afl();
        afl.setSfi(bai.read() >> 3);
        afl.setFirstRecord(bai.read());
        afl.setLastRecord(bai.read());
        afl.setOfflineAuthentication(bai.read() == 1);
        list.add(afl);
    }
    return list;
}