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:at.medevit.elexis.ehc.core.internal.EhcCoreServiceTest.java

@Test
public void testWriteXdm() throws Exception {
    EhcCoreServiceImpl service = new EhcCoreServiceImpl();
    CdaChVacd cda = service.getVaccinationsDocument(patient, mandant);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    CDAUtil.save(cda.getDocRoot().getClinicalDocument(), output);

    ConvenienceCommunication conCom = new ConvenienceCommunication();
    DocumentMetadata metaData = conCom.addChDocument(DocumentDescriptor.CDA_R2,
            new ByteArrayInputStream(output.toByteArray()));
    assertNotNull(metaData);/* ww  w . j  a va2s.  co  m*/
    List<Identificator> ids = cda.getPatient().getIds();
    if (!ids.isEmpty()) {
        metaData.setDestinationPatientId(ids.get(0));
    }
    output.reset();
    conCom.createXdmContents(output);
    assertTrue(output.size() > 0);
}

From source file:ca.ualberta.app.activity.CreateAnswerActivity.java

/**
 * compress the image to 64kb/*w  w  w  .  ja va  2s.c om*/
 * 
 * @return return the imageString after compressed
 */
private String compressImage() {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    int quality = 100;
    while (stream.toByteArray().length > 65536 && quality != 0) {
        stream.reset();
        image.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        quality -= 10;
    }
    if (quality == 0)
        return null;
    return Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
}

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

@Test
public void testVariableBinding() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    run(network, "(unwatch all)");
    {//from w  w  w  . j  a  va2s.  c  om
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(bind ?x 2)");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        final long two = Long.parseLong((String) value);
        assertEquals(2L, two);
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
}

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

@Test
public void testVariableUnbinding() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    run(network, "(unwatch all)");
    {//from   ww w. j av  a2  s .  c  o  m
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(bind ?x 2)");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        final long two = Long.parseLong((String) value);
        assertEquals(2L, two);
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(bind ?x)");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(0));
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
}

From source file:net.zionsoft.obadiah.model.Bible.java

private void downloadTranslation(String url, String translationShortName, OnDownloadProgressListener onProgress)
        throws Exception {
    ZipInputStream zis = null;//from   w w w.  ja  v  a  2  s .  c  o m
    SQLiteDatabase db = null;
    try {
        db = mDatabaseHelper.openDatabase();
        if (db == null) {
            Analytics.trackException("Failed to open database.");
            throw new Exception("Failed to open database for writing");
        }
        db.beginTransaction();

        TranslationHelper.createTranslationTable(db, translationShortName);

        zis = new ZipInputStream(NetworkHelper.getStream(url));

        final byte buffer[] = new byte[2048];
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        int downloaded = 0;
        int read;
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            os.reset();
            while ((read = zis.read(buffer, 0, 2048)) != -1)
                os.write(buffer, 0, read);
            final byte[] bytes = os.toByteArray();
            String fileName = entry.getName();
            fileName = fileName.substring(0, fileName.length() - 5); // removes the trailing ".json"
            if (fileName.equals("books")) {
                TranslationHelper.saveBookNames(db, new JSONObject(new String(bytes, "UTF8")));
            } else {
                final String[] parts = fileName.split("-");
                final int bookIndex = Integer.parseInt(parts[0]);
                final int chapterIndex = Integer.parseInt(parts[1]);
                TranslationHelper.saveVerses(db, translationShortName, bookIndex, chapterIndex,
                        new JSONObject(new String(bytes, "UTF8")));
            }

            onProgress.onProgress(++downloaded / 12);
        }

        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            if (db.inTransaction()) {
                db.endTransaction();
            }
            mDatabaseHelper.closeDatabase();
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
                // we can't do much here
            }
        }
    }
}

From source file:URLEncoder.java

public String encode(String path) {
    int maxBytesPerChar = 10;
    int caseDiff = ('a' - 'A');
    StringBuffer rewrittenPath = new StringBuffer(path.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer = null;
    try {/*from   w w w . j  a v a 2  s .  c o  m*/
        writer = new OutputStreamWriter(buf, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        writer = new OutputStreamWriter(buf);
    }

    for (int i = 0; i < path.length(); i++) {
        int c = (int) path.charAt(i);
        if (safeCharacters.get(c)) {
            rewrittenPath.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write((char) c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                // Converting each byte in the buffer
                byte toEncode = ba[j];
                rewrittenPath.append('%');
                int low = (int) (toEncode & 0x0f);
                int high = (int) ((toEncode & 0xf0) >> 4);
                rewrittenPath.append(hexadecimal[high]);
                rewrittenPath.append(hexadecimal[low]);
            }
            buf.reset();
        }
    }
    return rewrittenPath.toString();
}

From source file:org.fusesource.hawtjni.generator.HawtJNI.java

private void generateFromResource(String resource, File target) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
    FileSupport.copy(is, out);/*from   w  w w.java 2  s .co  m*/
    String content = new String(out.toByteArray(), "UTF-8");
    String[] parts = content.split(Pattern.quote("/* == HEADER-SNIP-LOCATION == */"));
    if (parts.length == 2) {
        content = parts[1];
    }
    out.reset();
    PrintStream ps = new PrintStream(out);
    ps.print(JNIGenerator.fixDelimiter(getCopyright()));
    ps.print(JNIGenerator.fixDelimiter(content));
    ps.close();
    if (FileSupport.write(out.toByteArray(), target)) {
        progress("Wrote: " + target);
    }
}

From source file:com.joyent.manta.client.crypto.EncryptingEntityTest.java

private void canBeWrittenIdempotently(final SupportedCipherDetails cipherDetails) throws Exception {
    final SecretKey secretKey = SecretKeyUtils.generate(cipherDetails);
    final String content = STRING_GENERATOR.generate(RandomUtils.nextInt(500, 1500));
    final ExposedStringEntity contentEntity = new ExposedStringEntity(content, StandardCharsets.UTF_8);

    final ByteArrayOutputStream referenceEncrypted = new ByteArrayOutputStream(content.length());
    {/*from www.j a v a 2  s. co m*/

        final EncryptingEntity referenceEntity = new EncryptingEntity(secretKey, cipherDetails, contentEntity);

        referenceEntity.writeTo(referenceEncrypted);
        validateCiphertext(cipherDetails, secretKey, contentEntity.getBackingBuffer().array(),
                referenceEntity.getCipher().getIV(), referenceEncrypted.toByteArray());
    }

    final ByteArrayOutputStream retryEncrypted = new ByteArrayOutputStream(content.length());
    final FailingOutputStream output = new FailingOutputStream(retryEncrypted, content.length() / 2);
    {
        final EncryptingEntity retryingEntity = new EncryptingEntity(secretKey, cipherDetails, contentEntity);

        Assert.assertThrows(IOException.class, () -> {
            retryingEntity.writeTo(output);
        });

        // clear the data written so we only see what makes it into the second request
        retryEncrypted.reset();
        output.setMinimumBytes(FailingOutputStream.NO_FAILURE);

        retryingEntity.writeTo(output);
        validateCiphertext(cipherDetails, secretKey, contentEntity.getBackingBuffer().array(),
                retryingEntity.getCipher().getIV(), retryEncrypted.toByteArray());
    }
}

From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java

static String urlDecode(final String str, final Charset charset) throws ParseException {
    int percent = str.indexOf('%');
    if (percent == -1)
        return str;

    final StringBuffer sb = new StringBuffer(str.length()); // buffer to build the converted string
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(8); // buffer for conversion of contiguous %-encoded bytes
    int last = 0;
    final int len = str.length();
    do {/* w  w w  .  jav a 2s  . co  m*/
        sb.append(str.substring(last, percent)); // write non-encoded part

        // loop to convert sequence of %-encoded tokens into bytes. Contiguous byte-sequences have to be dealt with
        // in one block before decoding, because - dependant on the charset - more than one byte may be needed to
        // represent a single character. If the conversion to bytes was done sequentially, decoding might fail
        do {
            if (percent + 3 > str.length())
                throw new ParseException("unexpected end of input", percent + 3);
            final String token = str.substring(percent + 1, percent + 3);
            if (!token.matches("[0-9a-fA-F]{2}"))
                throw new ParseException("illegal url-encoded token '" + token + "'", percent);

            final int tokenValue = Integer.parseInt(token, 16) & 0xFF;
            baos.write(tokenValue);
            percent += 3;
        } while (percent < len && str.charAt(percent) == '%');

        if (baos.size() > 0) {
            final CharBuffer decoded = charset.decode(ByteBuffer.wrap(baos.toByteArray()));
            baos.reset(); // reuse the ByteArrayOutputStream in the next run
            for (int i = 0; i < decoded.length(); i++) {
                final char c = decoded.charAt(i);
                switch (c) {
                case '#':
                    sb.append("%23");
                    continue;
                case '%':
                    sb.append("%25");
                    continue;
                case '&':
                    sb.append("%26");
                    continue;
                case '=':
                    sb.append("%3D");
                    continue;
                case '?':
                    sb.append("%3F");
                    continue;
                default:
                    sb.append(c);
                    continue;
                }
            }
        }

        last = percent; // byte after the token
        percent = str.indexOf('%', last); // search for next token, returns -1 if last > len
    } while (percent != -1);
    return sb.append(str.substring(last)).toString();
}

From source file:hudson.Util.java

/**
 * Escapes non-ASCII characters in URL./*from   www .ja va  2  s.com*/
 *
 * <p>
 * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
 * such as '#'.
 * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
 * a single path component to that method (it will encode /, but this method does not).
 */
public static String encode(String s) {
    try {
        boolean escaped = false;

        StringBuilder out = new StringBuilder(s.length());

        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8");

        for (int i = 0; i < s.length(); i++) {
            int c = s.charAt(i);
            if (c < 128 && c != ' ') {
                out.append((char) c);
            } else {
                // 1 char -> UTF8
                w.write(c);
                w.flush();
                for (byte b : buf.toByteArray()) {
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
                buf.reset();
                escaped = true;
            }
        }

        return escaped ? out.toString() : s;
    } catch (IOException e) {
        throw new Error(e); // impossible
    }
}