Example usage for java.io ByteArrayOutputStream reset

List of usage examples for java.io ByteArrayOutputStream reset

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream reset.

Prototype

public synchronized void reset() 

Source Link

Document

Resets the count field of this ByteArrayOutputStream to zero, so that all currently accumulated output in the output stream is discarded.

Usage

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

/**
 * HDFS-6374 setXAttr should require the user to be the owner of the file
 * or directory./*from w  w  w . j  av a  2  s .  c  o  m*/
 *
 * Test to make sure that only the owner of a file or directory can set
 * or remove the xattrs.
 *
 * As user1:
 * Create a directory (/foo) as user1, chown it to user1 (and user1's group),
 * grant rwx to "other".
 *
 * As user2:
 * Set an xattr (should fail).
 *
 * As user1:
 * Set an xattr (should pass).
 *
 * As user2:
 * Read the xattr (should pass).
 * Remove the xattr (should fail).
 *
 * As user1:
 * Read the xattr (should pass).
 * Remove the xattr (should pass).
 */
@Test(timeout = 30000)
public void testSetXAttrPermissionAsDifferentOwner() throws Exception {
    final String USER1 = "user1";
    final String GROUP1 = "mygroup1";
    final UserGroupInformation user1 = UserGroupInformation.createUserForTesting(USER1,
            new String[] { GROUP1 });
    final UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2",
            new String[] { "mygroup2" });
    MiniDFSCluster cluster = null;
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
        cluster.waitActive();

        final FileSystem fs = cluster.getFileSystem();
        fs.setOwner(new Path("/"), USER1, GROUP1);
        bak = System.err;

        final FsShell fshell = new FsShell(conf);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setErr(new PrintStream(out));

        // mkdir foo as user1
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell, new String[] { "-mkdir", "/foo" });
                assertEquals("Return should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Give access to "other"
                final int ret = ToolRunner.run(fshell, new String[] { "-chmod", "707", "/foo" });
                assertEquals("Return should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        // No permission to write xattr for non-owning user (user2).
        user2.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                final String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        // But there should be permission to write xattr for
        // the owning user.
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                final int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                return null;
            }
        });

        // There should be permission to read,but not to remove for
        // non-owning user (user2).
        user2.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                final String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        // But there should be permission to read/remove for
        // the owning user.
        user1.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 0", 0, ret);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test
public void testRemoteException() throws Exception {
    UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting("tmpname",
            new String[] { "mygroup" });
    MiniDFSCluster dfs = null;//  ww w  . j a  v  a2 s .c om
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        dfs = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
        FileSystem fs = dfs.getFileSystem();
        Path p = new Path("/foo");
        fs.mkdirs(p);
        fs.setPermission(p, new FsPermission((short) 0700));
        bak = System.err;

        tmpUGI.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                FsShell fshell = new FsShell(conf);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                PrintStream tmp = new PrintStream(out);
                System.setErr(tmp);
                String[] args = new String[2];
                args[0] = "-ls";
                args[1] = "/foo";
                int ret = ToolRunner.run(fshell, args);
                assertEquals("returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (dfs != null) {
            dfs.shutdown();
        }
    }
}

From source file:test.jamocha.languages.clips.SystemTest.java

@Test
public void testEquivalenceClasses() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    {/*from w w w  . j a  v a  2s .c o m*/
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(unwatch all)\n(watch facts)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate t1 (slot s1 (type INTEGER)))\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate t2 (slot s1 (type INTEGER)))\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(defrule r1 (t1 (s1 ?x)) (t2 (s1 ?x)) => (assert (t1 (s1 999))) )\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t1 (s1 5)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-2>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-2\t(t1 (s1 5))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t2 (s1 9)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-3>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-3\t(t2 (s1 9))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t2 (s1 5)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-4>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-4\t(t2 (s1 5))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-5\t(t1 (s1 999))", lines[0]);
        out.reset();
    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print the list of PO Quote requests./* ww  w  .  ja v a  2s .c o m*/
 *
 * @param mapping  An ActionMapping
 * @param form     An ActionForm
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printPoQuoteListOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_LIST_");
        sbFilename.append(poDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class)
                .printPurchaseOrderQuoteRequestsListPDF(poDocId, baosPDF);

        if (!success) {
            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(OLEConstants.MAPPING_PORTAL);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

/**
 * check command error outputs and exit statuses.
 */// w w w  . ja v  a 2s.c  om
@Test
public void testErrOutPut() throws Exception {
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = null;
    PrintStream bak = null;
    try {
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
        FileSystem srcFs = cluster.getFileSystem();
        Path root = new Path("/nonexistentfile");
        bak = System.err;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream tmp = new PrintStream(out);
        System.setErr(tmp);
        String[] argv = new String[2];
        argv[0] = "-cat";
        argv[1] = root.toUri().getPath();
        int ret = ToolRunner.run(new FsShell(), argv);
        assertEquals(" -cat returned 1 ", 1, ret);
        String returned = out.toString();
        assertTrue("cat does not print exceptions ", (returned.lastIndexOf("Exception") == -1));
        out.reset();
        argv[0] = "-rm";
        argv[1] = root.toString();
        FsShell shell = new FsShell();
        shell.setConf(conf);
        ret = ToolRunner.run(shell, argv);
        assertEquals(" -rm returned 1 ", 1, ret);
        returned = out.toString();
        out.reset();
        assertTrue("rm prints reasonable error ", (returned.lastIndexOf("No such file or directory") != -1));
        argv[0] = "-rmr";
        argv[1] = root.toString();
        ret = ToolRunner.run(shell, argv);
        assertEquals(" -rmr returned 1", 1, ret);
        returned = out.toString();
        assertTrue("rmr prints reasonable error ", (returned.lastIndexOf("No such file or directory") != -1));
        out.reset();
        argv[0] = "-du";
        argv[1] = "/nonexistentfile";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue(" -du prints reasonable error ", (returned.lastIndexOf("No such file or directory") != -1));
        out.reset();
        argv[0] = "-dus";
        argv[1] = "/nonexistentfile";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue(" -dus prints reasonable error", (returned.lastIndexOf("No such file or directory") != -1));
        out.reset();
        argv[0] = "-ls";
        argv[1] = "/nonexistenfile";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue(" -ls does not return Found 0 items", (returned.lastIndexOf("Found 0") == -1));
        out.reset();
        argv[0] = "-ls";
        argv[1] = "/nonexistentfile";
        ret = ToolRunner.run(shell, argv);
        assertEquals(" -lsr should fail ", 1, ret);
        out.reset();
        srcFs.mkdirs(new Path("/testdir"));
        argv[0] = "-ls";
        argv[1] = "/testdir";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue(" -ls does not print out anything ", (returned.lastIndexOf("Found 0") == -1));
        out.reset();
        argv[0] = "-ls";
        argv[1] = "/user/nonxistant/*";
        ret = ToolRunner.run(shell, argv);
        assertEquals(" -ls on nonexistent glob returns 1", 1, ret);
        out.reset();
        argv[0] = "-mkdir";
        argv[1] = "/testdir";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertEquals(" -mkdir returned 1 ", 1, ret);
        assertTrue(" -mkdir returned File exists", (returned.lastIndexOf("File exists") != -1));
        Path testFile = new Path("/testfile");
        OutputStream outtmp = srcFs.create(testFile);
        outtmp.write(testFile.toString().getBytes());
        outtmp.close();
        out.reset();
        argv[0] = "-mkdir";
        argv[1] = "/testfile";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertEquals(" -mkdir returned 1", 1, ret);
        assertTrue(" -mkdir returned this is a file ", (returned.lastIndexOf("not a directory") != -1));
        out.reset();
        argv = new String[3];
        argv[0] = "-mv";
        argv[1] = "/testfile";
        argv[2] = "file";
        ret = ToolRunner.run(shell, argv);
        assertEquals("mv failed to rename", 1, ret);
        out.reset();
        argv = new String[3];
        argv[0] = "-mv";
        argv[1] = "/testfile";
        argv[2] = "/testfiletest";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue("no output from rename", (returned.lastIndexOf("Renamed") == -1));
        out.reset();
        argv[0] = "-mv";
        argv[1] = "/testfile";
        argv[2] = "/testfiletmp";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertTrue(" unix like output", (returned.lastIndexOf("No such file or") != -1));
        out.reset();
        argv = new String[1];
        argv[0] = "-du";
        srcFs.mkdirs(srcFs.getHomeDirectory());
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertEquals(" no error ", 0, ret);
        assertTrue("empty path specified", (returned.lastIndexOf("empty string") == -1));
        out.reset();
        argv = new String[3];
        argv[0] = "-test";
        argv[1] = "-d";
        argv[2] = "/no/such/dir";
        ret = ToolRunner.run(shell, argv);
        returned = out.toString();
        assertEquals(" -test -d wrong result ", 1, ret);
        assertTrue(returned.isEmpty());
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.linkedin.databus.core.TestDbusEventBufferMult.java

@Test
public void testSubscriptionStream() throws Exception {
    final Logger log = Logger.getLogger("TestDbusEventBufferMult.testSubscriptionStream");
    log.info("start");

    TestSetup t = new TestSetup();

    PhysicalPartition pp100 = new PhysicalPartition(100, "multBufferTest1");
    PhysicalPartitionKey pk1 = new PhysicalPartitionKey(pp100);
    PhysicalPartition pp101 = new PhysicalPartition(101, "multBufferTest2");
    PhysicalPartitionKey pk2 = new PhysicalPartitionKey(pp101);

    //generate events in pp100
    byte[] schema = "abcdefghijklmnop".getBytes(Charset.defaultCharset());
    DbusEventBufferAppendable buf100 = t._eventBuffer.getDbusEventBufferAppendable(pp100);
    buf100.startEvents();/*ww  w.j av  a 2  s. c om*/
    assertTrue(buf100.appendEvent(new DbusEventKey(1), (short) 100, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 1, schema, new byte[100], false, null));
    assertTrue(buf100.appendEvent(new DbusEventKey(10), (short) 100, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 1, schema, new byte[100], false, null));
    assertTrue(buf100.appendEvent(new DbusEventKey(11), (short) 100, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 1, schema, new byte[100], false, null));
    assertTrue(buf100.appendEvent(new DbusEventKey(2), (short) 100, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    buf100.endEvents(100, null);
    buf100.startEvents();
    assertTrue(buf100.appendEvent(new DbusEventKey(3), (short) 100, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    assertTrue(buf100.appendEvent(new DbusEventKey(4), (short) 100, (short) 1,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    buf100.endEvents(200, null);

    //generate events in pp100
    DbusEventBufferAppendable buf101 = t._eventBuffer.getDbusEventBufferAppendable(pp101);
    buf101.startEvents();
    assertTrue(buf101.appendEvent(new DbusEventKey(51), (short) 101, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 11, schema, new byte[100], false, null));
    assertTrue(buf101.appendEvent(new DbusEventKey(52), (short) 101, (short) 0,
            System.currentTimeMillis() * 1000000, (short) 12, schema, new byte[100], false, null));
    assertTrue(buf101.appendEvent(new DbusEventKey(53), (short) 101, (short) 2,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    buf101.endEvents(120, null);
    buf101.startEvents();
    assertTrue(buf101.appendEvent(new DbusEventKey(54), (short) 101, (short) 2,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    assertTrue(buf101.appendEvent(new DbusEventKey(55), (short) 101, (short) 2,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    assertTrue(buf101.appendEvent(new DbusEventKey(56), (short) 101, (short) 2,
            System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
    buf101.endEvents(200, null);

    //initialization
    DatabusSubscription sub1 = DatabusSubscription
            .createPhysicalPartitionReplicationSubscription(new PhysicalPartition(100, "multBufferTest1"));

    DbusFilter filter1 = t._eventBuffer.constructFilters(Arrays.asList(sub1));
    assertNotNull(filter1);

    CheckpointMult cpMult1 = new CheckpointMult();
    Checkpoint cp100 = new Checkpoint();
    cp100.init();
    cp100.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    cp100.setWindowScn(10L);
    cp100.setWindowOffset(-1);
    cpMult1.addCheckpoint(pp100, cp100);

    String[] pnames = { "multBufferTest1:100", "multBufferTest2:101" };
    StatsCollectors<DbusEventsStatisticsCollector> statsColls1 = createStats(pnames);
    DbusEventsStatisticsCollector statsCol1 = statsColls1.getStatsCollector("multBufferTest1:100");
    DbusEventsStatisticsCollector statsCol2 = statsColls1.getStatsCollector("multBufferTest2:101");

    //read an entire buffer
    DbusEventBufferBatchReadable reader1 = t._eventBuffer.getDbusEventBufferBatchReadable(cpMult1,
            Arrays.asList(pk1), statsColls1);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Try a call with 20 bytes of fetch size, we should see the event size in the first return with 0 events read.
    StreamEventsResult result = reader1.streamEvents(false, 20, Channels.newChannel(baos), Encoding.BINARY,
            filter1);
    assertEquals(0, result.getNumEventsStreamed());
    assertEquals(161, result.getSizeOfPendingEvent());

    result = reader1.streamEvents(false, 1000000, Channels.newChannel(baos), Encoding.BINARY, filter1);
    int eventsRead = result.getNumEventsStreamed();
    assertEquals(eventsRead, 8); //4 events + 1 eop + 2 events + 1 eop
    assertEquals(statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumSysEvents(), 2);
    assertEquals(statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumDataEvents(), 6);
    assertEquals(result.getSizeOfPendingEvent(), 0, "Size of pending event not zero");

    // Now that we have read all the events, we should not see a pending event even if we offer a small fetch size.

    result = reader1.streamEvents(false, 20, Channels.newChannel(baos), Encoding.BINARY, filter1);

    assertEquals(0, result.getNumEventsStreamed(), "There should be no more events in the buffer now");
    assertEquals(0, result.getSizeOfPendingEvent(),
            "We should not see pending event size since there are no events in buffer");
    baos.reset();
    statsCol1.reset();
    statsCol2.reset();

    //read from two buffers, filtering out one
    cpMult1 = new CheckpointMult();
    cp100.init();
    cp100.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    cp100.setWindowScn(10L);
    cp100.setWindowOffset(-1);
    cpMult1.addCheckpoint(pp100, cp100);
    reader1 = t._eventBuffer.getDbusEventBufferBatchReadable(cpMult1, Arrays.asList(pk1, pk2), statsColls1);

    eventsRead = reader1.streamEvents(false, 1000000, Channels.newChannel(baos), Encoding.BINARY, filter1)
            .getNumEventsStreamed();
    assertEquals(eventsRead, 10); //4 events + 1 eop + 1 eop from the other buffer + 2 events +
                                  //1 eop + 1 eop from the other buffer
    assertEquals(statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumSysEvents(), 2);
    assertEquals(statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumDataEvents(), 6);

    baos.reset();
    statsCol1.reset();

    //read from one buffer and one source partition
    DatabusSubscription sub2 = new DatabusSubscription(PhysicalSource.MASTER_PHISYCAL_SOURCE,
            new PhysicalPartition(101, "multBufferTest2"),
            new LogicalSourceId(new LogicalSource(2, "srcName2"), (short) 2));

    DbusFilter filter2 = t._eventBuffer.constructFilters(Arrays.asList(sub2));
    assertNotNull(filter2);

    CheckpointMult cpMult2 = new CheckpointMult();
    Checkpoint cp101 = new Checkpoint();
    cp101.init();
    cp101.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    cp101.setWindowScn(10L);
    cp101.setWindowOffset(-1);
    cpMult2.addCheckpoint(pp101, cp101);
    DbusEventBufferBatchReadable reader2 = t._eventBuffer.getDbusEventBufferBatchReadable(cpMult2,
            Arrays.asList(pk2), statsColls1);

    eventsRead = reader2.streamEvents(false, 1000000, Channels.newChannel(baos), Encoding.BINARY, filter2)
            .getNumEventsStreamed();
    assertEquals(eventsRead, 6); //1 events + 1 eop + 3events + 1 eop

    baos.reset();
    statsCol1.reset();
    statsCol2.reset();

    //read all partitions for a source
    DatabusSubscription sub3 = new DatabusSubscription(PhysicalSource.MASTER_PHISYCAL_SOURCE,
            PhysicalPartition.ANY_PHYSICAL_PARTITION,
            LogicalSourceId.createAllPartitionsWildcard(new LogicalSource(2, "srcName2")));

    DbusFilter filter3 = t._eventBuffer.constructFilters(Arrays.asList(sub3));
    assertNotNull(filter3);

    CheckpointMult cpMult3 = new CheckpointMult();
    cp100.init();
    cp100.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    cp100.setWindowScn(10L);
    cp100.setWindowOffset(-1);
    cpMult1.addCheckpoint(pp100, cp100);
    cp101.init();
    cp101.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    cp101.setWindowScn(10L);
    cp101.setWindowOffset(-1);
    cpMult2.addCheckpoint(pp101, cp101);
    DbusEventBufferBatchReadable reader3 = t._eventBuffer.getDbusEventBufferBatchReadable(cpMult3,
            Arrays.asList(pk1, pk2), statsColls1);
    eventsRead = reader3.streamEvents(false, 1000000, Channels.newChannel(baos), Encoding.BINARY, filter3)
            .getNumEventsStreamed();
    assertEquals(eventsRead, 11); //1 events + 1 eop + 1 events + 1 eop + 2 events + 1 eop + 3 events + 1 eop
    assertEquals(statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumSysEvents(), 2);
    assertEquals(statsColls1.getStatsCollector("multBufferTest2:101").getTotalStats().getNumSysEvents(), 2);
    assertEquals(
            statsColls1.getStatsCollector("multBufferTest1:100").getTotalStats().getNumDataEventsFiltered(), 3);
    assertEquals(
            statsColls1.getStatsCollector("multBufferTest2:101").getTotalStats().getNumDataEventsFiltered(), 4);

    baos.reset();
    statsCol1.reset();
    statsCol2.reset();

    log.info("end");
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print the list of PO Quote requests./*from   w  w w.  ja  v a2  s.com*/
 *
 * @param mapping An ActionMapping
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPoQuoteListOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_LIST_");
        sbFilename.append(poDocId);
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class)
                .printPurchaseOrderQuoteRequestsListPDF(poDocId, baosPDF);

        if (!success) {
            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(KFSConstants.MAPPING_PORTAL);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        String useJavascript = request.getParameter("useJavascript");
        if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
            sbContentDispValue.append("attachment");
        } else {
            sbContentDispValue.append("inline");
        }
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:com.wwpass.connection.WWPassConnectionTest.java

@Test
public void testReadWriteData()
        throws UnsupportedEncodingException, IOException, WWPassProtocolException, DecoderException {

    InputStream dataIs;// w w  w .  jav  a  2  s.c  o  m
    BufferedInputStream bis = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Invalid ticket read case
    try {
        conn.readData(tickets.get(1));
        fail("Expected an WWPassProtocolException with message \"Invalid ticket URL\"");
    } catch (WWPassProtocolException e) {
        assertTrue("Expected message: \"Invalid ticket URL\", actual message: " + e.getMessage(),
                e.getMessage().contains("Invalid ticket URL"));
    }

    // Invalid ticket format read case
    try {
        conn.readData(tickets.get(2));
        fail("Expected an WWPassProtocolException with message \"Invalid ticket format\"");
    } catch (WWPassProtocolException e) {
        assertTrue("Expected message: \"Invalid ticket format\", actual message: " + e.getMessage(),
                e.getMessage().contains("Invalid ticket format"));
    }
    // Invalid ticket write case
    try {
        conn.writeData(tickets.get(1), "invalid ticket case");
        fail("Expected an WWPassProtocolException with message \"Invalid ticket URL\"");
    } catch (WWPassProtocolException e) {
        assertTrue("Expected message: \"Invalid ticket URL\", actual message: " + e.getMessage(),
                e.getMessage().contains("Invalid ticket URL"));
    }
    // Write and read string data case
    conn.writeData(tickets.get(0), "test data");
    dataIs = conn.readData(tickets.get(0));

    try {
        bis = new BufferedInputStream(dataIs);

        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        assertArrayEquals("Expected an empty string", "test data".getBytes(), baos.toByteArray());
    } finally {
        bis.close();
        baos.reset();
        baos.close();
    }

    // Write and read byte data (small size)
    conn.writeData(tickets.get(0), BYTE_DATA, "testbyte");
    dataIs = conn.readData(tickets.get(0), "testbyte");

    try {
        bis = new BufferedInputStream(dataIs);

        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        assertArrayEquals("Expected an non string data", BYTE_DATA, baos.toByteArray());
    } finally {
        bis.close();
        baos.reset();
        baos.close();
    }

    // Write and read byte data (large size)
    conn.writeData(tickets.get(0), imgData);
    dataIs = conn.readData(tickets.get(0));
    try {
        bis = new BufferedInputStream(dataIs);

        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        assertArrayEquals("Expected an image represented as bytes array data", imgData, baos.toByteArray());
    } finally {
        bis.close();
        baos.reset();
        baos.close();
    }

    // Valid ticket/container doesn't exist case
    dataIs = conn.readData(tickets.get(0), "doesn't exist");
    try {
        bis = new BufferedInputStream(dataIs);

        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        assertArrayEquals("Expected \"None\", but returned: " + new String(baos.toByteArray()),
                "None".getBytes(), baos.toByteArray());
    } finally {
        bis.close();
        baos.reset();
        baos.close();
    }

    // Valid container/valid ticket case
    conn.writeData(tickets.get(0), "test data", "test");
    dataIs = conn.readData(tickets.get(0), "test");
    try {
        bis = new BufferedInputStream(dataIs);

        byte[] buffer = new byte[8192];
        int bytesRead;

        while ((bytesRead = bis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        assertArrayEquals("Expected \"test data\", but returned: " + new String(baos.toByteArray()),
                "test data".getBytes(), baos.toByteArray());
    } finally {
        bis.close();
        baos.reset();
        baos.close();
    }

    // Invalid container/valid ticket case
    try {
        conn.readData(tickets.get(0), "0123456789ABCDEFG");
        fail("Expected an WWPassProtocolException with message \"Container ID too long\"");
    } catch (WWPassProtocolException e) {
        assertTrue("Expected message: \"Container ID too long\", actual message: " + e.getMessage(),
                e.getMessage().contains("Container ID too long"));
    }

    // Valid ticket/invalid container case
    try {
        conn.writeData(tickets.get(0), "test data", "0123456789ABCDEFG");
        fail("Expected an WWPassProtocolException with message \"Container ID too long\"");
    } catch (WWPassProtocolException e) {
        assertTrue("Expected message: \"Container ID too long\", actual message: " + e.getMessage(),
                e.getMessage().contains("Container ID too long"));
    }

}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test(timeout = 30000)
public void testSetXAttrPermission() throws Exception {
    UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[] { "mygroup" });
    MiniDFSCluster cluster = null;/*from w w  w.java 2 s. c om*/
    PrintStream bak = null;
    try {
        final Configuration conf = new HdfsConfiguration();
        cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
        cluster.waitActive();

        FileSystem fs = cluster.getFileSystem();
        Path p = new Path("/foo");
        fs.mkdirs(p);
        bak = System.err;

        final FsShell fshell = new FsShell(conf);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setErr(new PrintStream(out));

        // No permission to write xattr
        fs.setPermission(p, new FsPermission((short) 0700));
        user.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                int ret = ToolRunner.run(fshell,
                        new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });

        int ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" });
        assertEquals("Returned should be 0", 0, ret);
        out.reset();

        // No permission to read and remove
        fs.setPermission(p, new FsPermission((short) 0750));
        user.doAs(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                // Read
                int ret = ToolRunner.run(fshell, new String[] { "-getfattr", "-n", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                String str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                // Remove
                ret = ToolRunner.run(fshell, new String[] { "-setfattr", "-x", "user.a1", "/foo" });
                assertEquals("Returned should be 1", 1, ret);
                str = out.toString();
                assertTrue("Permission denied printed", str.indexOf("Permission denied") != -1);
                out.reset();
                return null;
            }
        });
    } finally {
        if (bak != null) {
            System.setErr(bak);
        }
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Print a particular selected PO Quote as a PDF.
 *
 * @param mapping  An ActionMapping//ww  w .  jav a 2 s.c  o m
 * @param form     An ActionForm -- The PO Quote must be selected here.
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // String poDocId = request.getParameter("docId");
    // PurchaseOrderDocument po = (PurchaseOrderDocument)
    // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId);
    // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId"));
    KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
    PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument();
    PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request));
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            poVendorQuote.setPdfDisplayedToUserOnce(false);

            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(OLEConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}