Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:net.vexelon.mobileops.GLBClient.java

private String doPostRequest(GLBRequestType requestType) throws HttpClientException {

    HttpResponse resp;//w w  w  .j a v a2  s  .  com
    try {
        List<NameValuePair> qparams = requestType.getParamsAsList();
        // Fix Issue #7 - Page does not exist
        qparams.add(new BasicNameValuePair("parameter", this.operationsHash.get(requestType)));

        //         for (NameValuePair nameValuePair : qparams) {
        //            Log.d(Defs.LOG_TAG, "Param: " + nameValuePair.getName() + " = " + nameValuePair.getValue());
        //         }

        HttpPost httpPost = createPostRequest(HTTP_MYTELENOR + requestType.getPath(), qparams);
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        httpPost.setHeader("X-Prototype-Version", "1.6.0.2");

        resp = httpClient.execute(httpPost, httpContext);
    } catch (Exception e) {
        throw new HttpClientException("Client protocol error!" + e.getMessage(), e);
    }

    StatusLine status = resp.getStatusLine();

    if (status.getStatusCode() != HttpStatus.SC_OK)
        throw new HttpClientException(status.getReasonPhrase(), status.getStatusCode());

    HttpEntity entity = resp.getEntity();
    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
        entity.writeTo(baos);
    } catch (Exception e) {
        throw new HttpClientException("Failed to load response! " + e.getMessage(), e);
    } finally {
        if (baos != null)
            try {
                baos.close();
            } catch (IOException e) {
            }
        ;
    }

    // bytes downloaded
    addDownloadedBytesCount(baos.size());

    try {
        return new String(baos.toByteArray(), RESPONSE_ENCODING);
    } catch (UnsupportedEncodingException e) {
        return new String(baos.toByteArray()); // XXX check this!
    }
}

From source file:org.apache.pig.piggybank.storage.XMLLoaderBufferedPositionedInputStream.java

/**
 * This is collect the from the matching tag.
 * This scans for the tags and do the pattern match byte by byte
 * This returns a part doc. it must be used along with 
 * XMLLoaderBufferedPositionedInputStream#collectUntilEndTag
 * //from   w  w w.  j av a 2s.c  o m
 * @param tagName the start tag to search for
 *
 * @param limit the end pointer for the block for this mapper
 *
 * @return the byte array containing match of the tag.
 *
 * @see loader.XMLLoaderBufferedPositionedInputStream.collectUntilEndTag
 *
 */
private byte[] skipToTag(String tagName, long limit) throws IOException {

    //@todo use the charset and get the charset encoding from the xml encoding.
    byte[] tmp = tagName.getBytes();
    byte[] tag = new byte[tmp.length + 1];
    tag[0] = (byte) '<';
    for (int i = 0; i < tmp.length; ++i) {
        tag[1 + i] = tmp[i];
    }

    ByteArrayOutputStream matchBuf = new ByteArrayOutputStream(512);
    int idxTagChar = 0;
    int state = S_START;

    /*
     * Read till the tag is found in this block. If a partial tag block is found
     * then continue on to the next block.matchBuf contains the data that is currently 
     * matched. If the read has reached the end of split and there are matched data 
     * then continue on to the next block.
     */
    while (splitBoundaryCriteria(wrapperIn) || (matchBuf.size() > 0)) {
        int b = -1;
        try {
            b = this.read();
            ++bytesRead; // Increment the bytes read by 1
            if (b == -1) {
                state = S_START;
                matchBuf.reset();
                this.setReadable(false);
                break;
            }
            switch (state) {
            case S_START:
                // start to match the target open tag
                if (b == tag[idxTagChar]) {
                    ++idxTagChar;
                    matchBuf.write((byte) (b));
                    if (idxTagChar == tag.length) {
                        state = S_MATCH_PREFIX;
                    }
                } else { // mismatch
                    idxTagChar = 0;
                    matchBuf.reset();
                }
                break;
            case S_MATCH_PREFIX:
                // tag match iff next character is whitespaces or close tag mark
                if (Character.isWhitespace(b) || b == '/' || b == '>') {
                    matchBuf.write((byte) (b));
                    state = S_MATCH_TAG;
                } else {
                    idxTagChar = 0;
                    matchBuf.reset();
                    state = S_START;
                }
                break;
            case S_MATCH_TAG:
                // keep copy characters until we hit the close tag mark
                matchBuf.write((byte) (b));
                break;
            default:
                throw new IllegalArgumentException("Invalid state: " + state);
            }
            if (state == S_MATCH_TAG && (b == '>' || Character.isWhitespace(b))) {
                break;
            }
            if (state != S_MATCH_TAG && this.getPosition() > limit) {
                // need to break, no record in this block
                break;
            }
        } catch (IOException e) {
            this.setReadable(false);
            return null;
        }
    }
    return matchBuf.toByteArray();
}

From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java

/**
 * Tests that the PurchaseOrderService would performPrintPurchaseOrderPDFOnly
 *
 * @throws Exception/*w  w  w.ja  va  2  s  . c om*/
 */
public void testPerformPrintPurchaseOrderPDFOnly() throws Exception {
    PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS
            .createPurchaseOrderDocument();
    po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN);

    po.refreshNonUpdateableReferences();

    po.prepareForSave();
    AccountingDocumentTestUtils.saveDocument(po, docService);

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        DateTimeService dtService = SpringContext.getBean(DateTimeService.class);
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(dtService.getCurrentDate().getTime());
        sbFilename.append(".pdf");
        poService.performPrintPurchaseOrderPDFOnly(po.getDocumentNumber(), baosPDF);
        assertTrue(baosPDF.size() > 0);
    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }
}

From source file:org.commoncrawl.util.CompressedURLFPList.java

public static void validateURLFPFlagSerializationRootDomain() {
    TreeMultimap<Integer, URLFP> sourceMap = TreeMultimap.create();
    TreeMultimap<Integer, URLFP> destMap = TreeMultimap.create();
    ;//from   w w w.j a  v  a2  s  .c  o  m

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID | FLAG_SERIALIZE_URLFP_FLAGS);

    for (int i = 0; i < 12; ++i) {
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "0_" + i, 1, (255 | (65535 << 16)));
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "1_" + i, 2, (255 | (65535 << 16)));
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "2_" + i, 3, (255 | (65535 << 16)));
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "3_" + i, 4, 0);
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "4_" + i, 5, 0);
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "5_" + i, 6, 0);
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "6_" + i, 7, (255 | (65535 << 16)));
        insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "7_" + i, 8, 255);
    }
    insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "8", 8, 255);

    addMapToBuilder(firstBuilder, sourceMap);

    try {
        // flush to byte stream ...
        firstBuilder.flush(byteStream);
        // now set up to read the stream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0,
                byteStream.size());
        Reader reader = new Reader(inputStream);

        while (reader.hasNext()) {
            URLFP fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

        Assert.assertTrue(sourceMap.equals(destMap));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.microsoft.azure.storage.blob.CloudBlobClientEncryptionTests.java

@Test
public void testBlockBlobValidateEncryption() throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, StorageException, IOException, InvalidAlgorithmParameterException,
        URISyntaxException, InterruptedException, ExecutionException {
    int size = 5 * 1024 * 1024;
    byte[] buffer = TestHelper.getRandomBuffer(size);

    CloudBlockBlob blob = container.getBlockBlobReference("blob1");

    // Create the Key to be used for wrapping.
    SymmetricKey aesKey = TestHelper.getSymmetricKey();

    // Create the encryption policy to be used for upload.
    BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

    // Set the encryption policy on the request options.
    BlobRequestOptions uploadOptions = new BlobRequestOptions();
    uploadOptions.setEncryptionPolicy(uploadPolicy);

    // Upload the encrypted contents to the blob.
    ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
    blob.upload(stream, size, null, uploadOptions, null);

    // Encrypt locally.
    String metadata = blob.getMetadata().get(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA);
    BlobEncryptionData encryptionData = BlobEncryptionData.deserialize(metadata);

    Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptionData.getContentEncryptionIV());

    byte[] contentEncryptionKey = aesKey.unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
            encryptionData.getWrappedContentKey().getAlgorithm()).get();
    SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES");

    myAes.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);

    CipherInputStream encryptedStream = new CipherInputStream(new ByteArrayInputStream(buffer), myAes);

    // Download the encrypted contents from the blob.
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    blob.download(outputStream);/*from ww w .jav  a 2  s.  c  o m*/

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    for (int i = 0; i < outputStream.size(); i++) {
        assertEquals(encryptedStream.read(), inputStream.read());
    }

    encryptedStream.close();
}

From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java

/**
 * Tests that the PurchaseOrderService would performPurchaseOrderPreviewPrinting
 *
 * @throws Exception//from  ww w  . j  a v a 2  s .c  o m
 */
public void testPerformPurchaseOrderPreviewPrinting() throws Exception {
    PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS
            .createPurchaseOrderDocument();
    po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN);

    po.refreshNonUpdateableReferences();

    po.prepareForSave();
    AccountingDocumentTestUtils.saveDocument(po, docService);

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        DateTimeService dtService = SpringContext.getBean(DateTimeService.class);
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(dtService.getCurrentDate().getTime());
        sbFilename.append(".pdf");
        poService.performPurchaseOrderPreviewPrinting(po.getDocumentNumber(), baosPDF);
        assertTrue(baosPDF.size() > 0);
    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }
}

From source file:org.commoncrawl.util.CompressedURLFPListV2.java

public static void validateURLFPSerializationMultiDomain() {

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID);

    TreeMultimap<Long, URLFPV2> sourceMap = TreeMultimap.create();
    TreeMultimap<Long, URLFPV2> destMap = TreeMultimap.create();
    ;/*from   w  ww .j a  v  a 2  s.c  o  m*/

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1, 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2, 1);

    // top level domain with matching sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1, 1);
    insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_2, 1);

    // two sub domains with two urls each
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1, 1);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_2, 1);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1, 1);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_2, 1);

    addMapToBuilder(firstBuilder, sourceMap);

    try {
        // flush to byte stream ...
        firstBuilder.flush(byteStream);
        // now set up to read the stream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0,
                byteStream.size());
        Reader reader = new Reader(inputStream);

        while (reader.hasNext()) {
            URLFPV2 fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

        // dump both lists
        for (long rootDomain : sourceMap.keySet()) {
            for (URLFPV2 URLFPV2 : sourceMap.get(rootDomain)) {
                System.out.println("SourceFP Root:" + URLFPV2.getRootDomainHash() + " Domain:"
                        + URLFPV2.getDomainHash() + " URL:" + URLFPV2.getUrlHash());
            }
        }
        for (long rootDomain : destMap.keySet()) {
            for (URLFPV2 URLFPV2 : destMap.get(rootDomain)) {
                System.out.println("DestFP Root:" + URLFPV2.getRootDomainHash() + " Domain:"
                        + URLFPV2.getDomainHash() + " URL:" + URLFPV2.getUrlHash());
            }
        }

        Assert.assertTrue(sourceMap.equals(destMap));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java

/**
 * Tests that the PurchaseOrderService would performPurchaseOrderFirstTransmitViaPrinting
 *
 *
 * @throws Exception/*from   www  . jav a2  s. c o m*/
 */
public void testPerformPurchaseOrderFirstTransmitViaPrinting() throws Exception {
    PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS
            .createPurchaseOrderDocument();
    po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN);

    po.refreshNonUpdateableReferences();

    po.prepareForSave();
    AccountingDocumentTestUtils.saveDocument(po, docService);

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        DateTimeService dtService = SpringContext.getBean(DateTimeService.class);
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_REQUEST_LIST");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(dtService.getCurrentDate().getTime());
        sbFilename.append(".pdf");
        poService.performPurchaseOrderFirstTransmitViaPrinting(po.getDocumentNumber(), baosPDF);
        assertTrue(baosPDF.size() > 0);
    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }
}

From source file:org.ejbca.core.model.log.CsvLogExporter.java

/** @see org.ejbca.core.model.log.ILogExporter */
@Override// w  ww . j ava 2  s  . c o  m
public byte[] export(final Admin admin, final Collection<LogEntry> logentries) throws Exception {
    log.trace(">export");
    byte[] ret = null;
    if (logentries != null) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintWriter pw = new PrintWriter(baos);
        try {
            for (final LogEntry next : logentries) {
                pw.print(next.getTime());
                pw.print("\t");
                pw.print(next.getAdminType());
                pw.print("\t");
                pw.print(next.getAdminData());
                pw.print("\t");
                pw.print(next.getCAId());
                pw.print("\t");
                pw.print(next.getModule());
                pw.print("\t");
                pw.print(next.getEvent());
                pw.print("\t");
                pw.print(next.getEventName());
                pw.print("\t");
                pw.print(next.getUsername());
                pw.print("\t");
                pw.print(next.getCertificateSNR());
                pw.print("\t");
                pw.print(next.getComment());
                pw.print("\n");
            }
            pw.close();
            if (baos.size() > 0) {
                ret = baos.toByteArray();
            }
        } finally {
            try {
                pw.close();
                baos.close();
            } catch (IOException e) {
                log.error("Error closing ByteArrayOutputStream: ", e);
            }
        }
    }
    // Sign the result if we have a signing CA
    if (log.isDebugEnabled()) {
        log.debug("Signing CA is '" + signingCA + "'");
    }
    if (ret != null && StringUtils.isNotEmpty(signingCA)) {
        try {
            final int caid = Integer.parseInt(signingCA);
            final CmsCAServiceRequest request = new CmsCAServiceRequest(ret, CmsCAServiceRequest.MODE_SIGN);
            final CAAdminSession caAdminSession = new EjbLocalHelper().getCaAdminSession();
            final CmsCAServiceResponse resp = (CmsCAServiceResponse) caAdminSession.extendedService(admin, caid,
                    request);
            ret = resp.getCmsDocument();
        } catch (IllegalExtendedCAServiceRequestException e) {
            log.error("Bad CA service", e);
        } catch (CADoesntExistsException e) {
            log.error("Bad CA", e);
        } catch (ExtendedCAServiceRequestException e) {
            log.error("", e);
        } catch (ExtendedCAServiceNotActiveException e) {
            throw e;
        }
    }
    if (log.isTraceEnabled()) {
        int no = 0;
        if (logentries != null) {
            no = logentries.size();
        }
        log.trace("<export: " + no + " entries");
    }
    return ret;
}