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.hive.accumulo.predicate.TestPrimitiveComparisonFilter.java

@Test
public void testNumericBase64ConstantEncode() throws IOException {
    PrimitiveComparisonFilter filter = new PrimitiveComparisonFilter();
    Map<String, String> options = new HashMap<String, String>();
    IntWritable writable = new IntWritable();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);

    for (int i = 0; i < 500; i++) {
        writable.set(i);/*from w w  w  .j  a  v a2s.  c o  m*/
        writable.write(out);

        options.put(PrimitiveComparisonFilter.CONST_VAL, new String(Base64.encodeBase64(baos.toByteArray())));

        byte[] bytes = filter.getConstant(options);

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        DataInputStream in = new DataInputStream(bais);
        writable.readFields(in);

        Assert.assertEquals(i, writable.get());

        baos.reset();
    }
}

From source file:J2MESearchMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from w ww  .  j av  a2s .  c  o m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "A", "B", "M" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
            String inputString;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            if (recordstore.getNumRecords() > 0) {
                filter = new Filter("Mary");
                recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                while (recordEnumeration.hasNextElement()) {
                    recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt();
                    alert = new Alert("Reading", inputString, null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                filter.filterClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//  ww w.  ja va 2 s.c  om
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:com.hurence.logisland.redis.service.RedisKeyValueCacheService.java

private <K, Record> Tuple<byte[], byte[]> serialize(final K key, final Record value,
        final Serializer<K> keySerializer, final Serializer<Record> valueSerializer) throws IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] k = null;

    try {//from w  w  w  .  j  a  va  2 s  .c o m
        keySerializer.serialize(out, key);
        k = out.toByteArray();
    } catch (Throwable t) {
        // do nothing
    }
    out.reset();

    byte[] v = null;
    try {
        valueSerializer.serialize(out, value);
        v = out.toByteArray();
    } catch (Throwable t) {
        // do nothing
    }

    return new Tuple<>(k, v);
}

From source file:J2MESortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  ww  w.  j  av a2s.c  om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();

            String[] inputString = new String[3];
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            }
        } catch (Exception error) {
            alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCliTest.java

/**
 * @param  keyStore  Path to JKS keystore file.
 * @param  storeType  Keystore type. Uses default type if null.
 * @param  cert  Certificate/certificate chain file.
 *
 * @throws  Exception  On test failure./*from   w  w w  .j  a  v  a2  s. c o m*/
 */
@Test(groups = { "cli", "keystore" }, dataProvider = "trustedcertdata")
public void testImportTrustedCert(final String keyStore, final String storeType, final String cert)
        throws Exception {
    new File(TEST_OUTPUT_DIR).mkdir();

    final PrintStream oldStdOut = System.out;
    final String keyStorePath = TEST_OUTPUT_DIR + keyStore;

    final String testAlias = "testng";
    final OptionData keyStoreOption = new OptionData("keystore", keyStorePath);
    final OptionData storeTypeOption = storeType == null ? null : new OptionData("storetype", storeType);
    final OptionData storePassOption = new OptionData("storepass", "changeit");
    final OptionData aliasOption = new OptionData("alias", testAlias);
    final OptionData[] listOptions = new OptionData[] { new OptionData("list"), keyStoreOption, storeTypeOption,
            storePassOption, };
    final OptionData[] importOptions = new OptionData[] { new OptionData("import"), keyStoreOption,
            storeTypeOption, storePassOption, new OptionData("cert", CERT_DIR_PATH + cert), aliasOption, };
    try {
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outStream));

        logger.info("Importing trusted cert into keystore with command line "
                + CliHelper.toCommandLine(importOptions));
        KeyStoreCli.main(CliHelper.toArgs(importOptions));
        AssertJUnit.assertTrue(new File(keyStorePath).exists());

        // Verify imported entry is present and has correct length
        // when we list contents
        outStream.reset();
        KeyStoreCli.main(CliHelper.toArgs(listOptions));

        final String output = outStream.toString();
        logger.info("Keystore listing output:\n" + output);
        AssertJUnit.assertTrue(output.indexOf(testAlias) != -1);

        outStream.reset();
    } finally {
        // Restore STDOUT
        System.setOut(oldStdOut);
    }
}

From source file:com.project.test.parquet.TestParquetTBaseScheme.java

private void createFileForRead() throws Exception {
    final Path fileToCreate = new Path(parquetInputPath + "/names.parquet");

    final Configuration conf = new Configuration();
    final FileSystem fs = fileToCreate.getFileSystem(conf);
    if (fs.exists(fileToCreate))
        fs.delete(fileToCreate, true);/*from www  .  ja  v  a 2 s  .  c o  m*/

    TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
    TaskAttemptID taskId = new TaskAttemptID("local", 0, true, 0, 0);
    ThriftToParquetFileWriter w = new ThriftToParquetFileWriter(fileToCreate,
            ContextUtil.newTaskAttemptContext(conf, taskId), protocolFactory, Name.class);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final TProtocol protocol = protocolFactory.getProtocol(new TIOStreamTransport(baos));

    Name n1 = new Name();
    n1.setFirst_name("Alice");
    n1.setLast_name("Practice");
    Name n2 = new Name();
    n2.setFirst_name("Bob");
    n2.setLast_name("Hope");
    Name n3 = new Name();
    n3.setFirst_name("Charlie");
    n3.setLast_name("Horse");

    n1.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    baos.reset();
    n2.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    baos.reset();
    n3.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    w.close();
}

From source file:parquet.cascading.TestParquetTBaseScheme.java

private void createFileForRead() throws Exception {
    final Path fileToCreate = new Path(parquetInputPath + "/names.parquet");

    final Configuration conf = new Configuration();
    final FileSystem fs = fileToCreate.getFileSystem(conf);
    if (fs.exists(fileToCreate))
        fs.delete(fileToCreate, true);/*  w  w w  . j a va 2s .co  m*/

    TProtocolFactory protocolFactory = new TCompactProtocol.Factory();
    TaskAttemptID taskId = new TaskAttemptID("local", 0, true, 0, 0);
    ThriftToParquetFileWriter w = new ThriftToParquetFileWriter(fileToCreate,
            new TaskAttemptContext(conf, taskId), protocolFactory, Name.class);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final TProtocol protocol = protocolFactory.getProtocol(new TIOStreamTransport(baos));

    Name n1 = new Name();
    n1.setFirst_name("Alice");
    n1.setLast_name("Practice");
    Name n2 = new Name();
    n2.setFirst_name("Bob");
    n2.setLast_name("Hope");
    Name n3 = new Name();
    n3.setFirst_name("Charlie");
    n3.setLast_name("Horse");

    n1.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    baos.reset();
    n2.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    baos.reset();
    n3.write(protocol);
    w.write(new BytesWritable(baos.toByteArray()));
    w.close();
}

From source file:fr.enseirb.odroidx.videomanager.Uploader.java

public void doUpload(Uri myFile) {
    createNotification();//from   ww  w.  ja  v a  2  s.co  m
    File f = new File(myFile.getPath());
    SendName(f.getName().replace(' ', '-'));
    Log.e(getClass().getSimpleName(), "test: " + f.exists());
    if (f.exists()) {
        Socket s;
        try {
            Log.e(getClass().getSimpleName(), "test: " + server_ip);
            s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug
            // using
            // variable
            // port
            OutputStream fluxsortie = s.getOutputStream();
            int nb_parts = (int) (f.length() / PART_SIZE);

            InputStream in = new BufferedInputStream(new FileInputStream(f));
            ByteArrayOutputStream byte_array = new ByteArrayOutputStream();
            BufferedOutputStream buffer = new BufferedOutputStream(byte_array);

            byte[] to_write = new byte[PART_SIZE];
            for (int i = 0; i < nb_parts; i++) {
                in.read(to_write, 0, PART_SIZE);
                buffer.write(to_write);
                buffer.flush();
                fluxsortie.write(byte_array.toByteArray());
                byte_array.reset();
                if ((i % 250) == 0) {
                    mBuilder.setProgress(nb_parts, i, false);
                    mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification());
                }
            }
            int remaining = (int) (f.length() - nb_parts * PART_SIZE);
            in.read(to_write, 0, remaining);
            buffer.write(to_write);
            buffer.flush();
            fluxsortie.write(byte_array.toByteArray());
            byte_array.reset();
            buffer.close();
            fluxsortie.close();
            in.close();
            s.close();
        } catch (ConnectException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        } catch (UnknownHostException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = UNKNOWN;
            Log.i(getClass().getSimpleName(), "Unknown host");
            e.printStackTrace();
        } catch (IOException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        }
    }
}

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

@Test
public void testTranslateRHSBind() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    run(network, "(unwatch all)\n");
    {/*from w ww  . ja v  a 2  s  . c om*/
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate f1 (slot s1 (type INTEGER)))\n"
                        + "(defrule r1 (f1 (s1 ?x)) => (bind ?y (+ ?x 2)) (assert (f1 (s1 ?y))) ) \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 (f1 (s1 5)))");
        final Queue<Object> left = returnValues.getLeft();
        assertThat(left, hasSize(1));
        assertThat(left.peek(), instanceOf(String.class));
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(watch facts)");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run 1)");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        final String output = out.toString();
        assertThat(output, not(isEmptyString()));
        final String[] lines = output.split(LINE_SEPARATOR);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-3\t(f1 (s1 7))", lines[0]);
        out.reset();
    }
}