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:org.kuali.mobility.push.dao.PushDaoImpl.java

@SuppressWarnings("unchecked")
private boolean sendPushToIOS(Push push, Device device, SSLSocket socket) {
    String payload = preparePayload(push);
    LOG.info("Push: " + push);
    LOG.info("Device: " + device);
    String token = device.getRegId();

    try {//from w  w w.  ja v  a2 s  .  c om
        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Command Byte. 
        baos.write(0);
        // Device ID Length
        baos.write(0);
        baos.write(32);
        // Device ID
        baos.write(b);
        // Payload Length
        baos.write(0);
        baos.write(payload.length());
        // Payload
        baos.write(payload.getBytes());
        LOG.info("Payload: Final size: " + baos.size());

        if (socket != null) {
            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();
            out.write(baos.toByteArray());
            out.flush();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.ohmage.request.Request.java

/**
 * Reads the HttpServletRequest for a key-value pair and returns the value
 * where the key is equal to the given key.
 * //  ww  w . j a v  a  2s  .  c  o m
 * @param httpRequest A "multipart/form-data" request that contains the 
 *                  parameter that has a key value 'key'.
 * 
 * @param key The key for the value we are after in the 'httpRequest'.
 * 
 * @return Returns null if there is no such key in the request or if, 
 *          after reading the object, it has a length of 0. Otherwise, it
 *          returns the value associated with the key as a byte array.
 * 
 * @throws ServletException Thrown if the 'httpRequest' is not a 
 *                      "multipart/form-data" request.
 * 
 * @throws IOException Thrown if there is an error reading the value from
 *                   the request's input stream.
 * 
 * @throws IllegalStateException Thrown if the entire request is larger
 *                          than the maximum allowed size for a 
 *                          request or if the value of the requested
 *                          key is larger than the maximum allowed 
 *                          size for a single value.
 */
protected byte[] getMultipartValue(HttpServletRequest httpRequest, String key) throws ValidationException {
    try {
        Part part = httpRequest.getPart(key);
        if (part == null) {
            return null;
        }

        // Get the input stream.
        InputStream partInputStream = part.getInputStream();

        // Wrap the input stream in a GZIP de-compressor if it is GZIP'd.
        String contentType = part.getContentType();
        if ((contentType != null) && contentType.contains("gzip")) {
            LOGGER.info("Part was GZIP'd: " + key);
            partInputStream = new GZIPInputStream(partInputStream);
        }

        // Parse the data.
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] chunk = new byte[4096];
        int amountRead;
        while ((amountRead = partInputStream.read(chunk)) != -1) {
            outputStream.write(chunk, 0, amountRead);
        }

        if (outputStream.size() == 0) {
            return null;
        } else {
            return outputStream.toByteArray();
        }
    } catch (ServletException e) {
        LOGGER.error("This is not a multipart/form-data POST.", e);
        setFailed(ErrorCode.SYSTEM_GENERAL_ERROR,
                "This is not a multipart/form-data POST which is what we expect for the current API call.");
        throw new ValidationException(e);
    } catch (IOException e) {
        LOGGER.info("There was a problem with the zipping of the data.", e);
        throw new ValidationException(ErrorCode.SERVER_INVALID_GZIP_DATA,
                "The zipped data was not valid zip data.", e);
    }
}

From source file:org.dbmfs.DatabaseFilesystem.java

public int write(String path, Object fh, boolean isWritepage, ByteBuffer buf, long offset)
        throws FuseException {
    log.info("write  path:" + path + " offset:" + offset + " isWritepage:" + isWritepage + " buf.limit:"
            + buf.limit());//from w  w  w. java 2 s .co  m
    if (readOnlyMount)
        throw new FuseException("Read Only").initErrno(FuseException.EACCES);
    try {

        if (fh == null)
            return Errno.EBADE;

        // ????offset limit???
        path = DbmfsUtil.convertRealPath(path.trim());

        synchronized (syncFileAccess[((path.hashCode() << 1) >>> 1) % syncFileAccess.length]) {

            if (bufferedSaveData.containsKey(fh)) {

                Map bufferedData = bufferedSaveData.get(fh);
                ByteArrayOutputStream bufferedByteData = (ByteArrayOutputStream) bufferedData
                        .get(bufferedDataBodyKey);
                long bOffset = ((Long) bufferedData.get(bufferedDataOffset)).longValue();

                if ((bOffset + bufferedByteData.size()) == offset) {

                    byte[] nowWriteBytes = new byte[buf.limit()];
                    buf.get(nowWriteBytes);
                    bufferedByteData.write(nowWriteBytes);

                    return 0;
                }
            } else {

                Map bufferedData = new HashMap();

                bufferedData.put("path", path);
                bufferedData.put("fh", fh);
                bufferedData.put("isWritepage", isWritepage);

                ByteArrayOutputStream bufferedByteData = new ByteArrayOutputStream(1024 * 1024 * 2);
                byte[] nowWriteBytes = new byte[buf.limit()];
                buf.get(nowWriteBytes);

                bufferedByteData.write(nowWriteBytes);
                bufferedData.put(bufferedDataBodyKey, bufferedByteData);
                bufferedData.put(bufferedDataOffset, offset);

                this.bufferedSaveData.put(fh, bufferedData);
                return 0;
            }
        }
    } catch (Exception e) {

        throw new FuseException(e);
    }
    return 0;
}

From source file:org.apache.olingo.fit.utils.JSONUtilities.java

@Override
public InputStream readEntities(final List<String> links, final String linkName, final String next,
        final boolean forceFeed) throws IOException {

    if (links.isEmpty()) {
        throw new NotFoundException();
    }/*from w  w  w .  ja va 2s.c om*/

    final ObjectNode node = mapper.createObjectNode();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if (forceFeed || links.size() > 1) {
        bos.write("[".getBytes());
    }

    for (String link : links) {
        try {
            final Map.Entry<String, String> uriMap = Commons.parseEntityURI(link);
            final Map.Entry<String, InputStream> entity = readEntity(uriMap.getKey(), uriMap.getValue(),
                    Accept.JSON_FULLMETA);

            if (bos.size() > 1) {
                bos.write(",".getBytes());
            }

            IOUtils.copy(entity.getValue(), bos);
        } catch (Exception e) {
            // log and ignore link
            LOG.warn("Error parsing uri {}", link, e);
        }
    }

    if (forceFeed || links.size() > 1) {
        bos.write("]".getBytes());
    }

    node.set(Constants.get(ConstantKey.JSON_VALUE_NAME),
            mapper.readTree(new ByteArrayInputStream(bos.toByteArray())));

    if (StringUtils.isNotBlank(next)) {
        node.set(Constants.get(ConstantKey.JSON_NEXTLINK_NAME), new TextNode(next));
    }

    return IOUtils.toInputStream(node.toString(), Constants.ENCODING);
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

@Override
public ListenableFuture<Response> request(final URI uri, final String method, final byte[] entityBytes,
        final Map<String, List<String>> headers) {
    return executorService.submit(new Callable<Response>() {
        @Override/* w ww .  ja v  a 2  s  .  c o  m*/
        public Response call() throws Exception {
            final HttpURLConnection connection = connect(uri, method, entityBytes, headers);
            final int status = connection.getResponseCode();
            final InputStream rawStream;

            if (status / 100 != 2) {
                rawStream = connection.getErrorStream();
            } else {
                rawStream = connection.getInputStream();
            }

            final boolean gzip = isGzipCompressed(connection);
            final InputStream stream = gzip ? new GZIPInputStream(rawStream) : rawStream;
            final ByteArrayOutputStream payload = new ByteArrayOutputStream();
            if (stream != null) {
                int n;
                byte[] buffer = new byte[4096];
                while ((n = stream.read(buffer, 0, buffer.length)) != -1) {
                    payload.write(buffer, 0, n);
                }
            }

            URI realUri = connection.getURL().toURI();
            if (log.isTraceEnabled()) {
                log.trace("rep: {} {} {} {} {} gzip:{}", method, realUri, status, payload.size(),
                        decode(payload), gzip);
            } else {
                log.debug("rep: {} {} {} {} gzip:{}", method, realUri, status, payload.size(), gzip);
            }

            return new Response(method, uri, status, payload.toByteArray(),
                    Collections.unmodifiableMap(Maps.newHashMap(connection.getHeaderFields())));
        }

        private boolean isGzipCompressed(final HttpURLConnection connection) {
            final List<String> encodings = connection.getHeaderFields().get("Content-Encoding");
            if (encodings == null) {
                return false;
            }
            for (String encoding : encodings) {
                if ("gzip".equals(encoding)) {
                    return true;
                }
            }
            return false;
        }
    });
}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

protected Representation finalizeZip(List<String> config, ZipOutputStream zip, ByteArrayOutputStream baos)
        throws Exception {
    String file = "";
    for (String s : config) {
        file += s + '\n';
    }//from  w w  w . ja  v  a 2s .c  o m

    if (caCert == null) {
        caCert = IOUtils.toByteArray(new FileInputStream(VPN.cfg.getProperty("ca.crt")));
    }

    ZipEntry configFile = new ZipEntry("neutrinet.ovpn");
    configFile.setCreationTime(FileTime.from(Instant.now()));
    zip.putNextEntry(configFile);
    zip.write(file.getBytes());
    zip.putNextEntry(new ZipEntry("ca.crt"));
    zip.write(caCert);

    zip.close();

    ByteArrayRepresentation rep = new ByteArrayRepresentation(baos.toByteArray());
    rep.setMediaType(MediaType.APPLICATION_ZIP);
    rep.setSize(baos.size());
    rep.setCharacterSet(CharacterSet.UTF_8);
    rep.setDisposition(new Disposition(Disposition.TYPE_ATTACHMENT));
    return rep;
}

From source file:org.zlogic.vogon.web.controller.DataController.java

/**
 * Returns all data//from  w w  w  .  jav  a  2  s .c  o  m
 *
 * @param userPrincipal the authenticated user
 * @return the HTTPEntity for the file download
 */
@RequestMapping(value = "/export/xml", method = { RequestMethod.GET, RequestMethod.POST })
public HttpEntity<byte[]> exportDataXML(@AuthenticationPrincipal VogonSecurityUser userPrincipal)
        throws RuntimeException {
    VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername());
    try {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        XmlExporter exporter = new XmlExporter(outStream);
        Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N
        exporter.exportData(user, accountRepository.findByOwner(user, accountSort),
                transactionRepository.findByOwner(user, transactionSort), null);

        String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        headers.setContentLength(outStream.size());
        headers.setContentDispositionFormData("attachment", "vogon-" + date + ".xml"); //NOI18N //NOI18N

        return new HttpEntity<>(outStream.toByteArray(), headers);
    } catch (VogonExportException ex) {
        throw new RuntimeException(ex);
    }
}

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

/**
 * Tests that the PurchaseOrderService would print purchase order quote requests list pdf.
 *
 * @throws Exception/*from w  ww  . j  a  v a2  s. c  om*/
 */

public void testPrintPurchaseOrderQuoteRequestsListPDF() 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);

        poService.printPurchaseOrderQuoteRequestsListPDF(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:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public data_ret _encode_multipart_formdata(Hashtable<String, String> values, String file_field, String filename,
        byte[] file_data) throws IOException {
    data_ret ret2 = new data_ret();
    //byte[] ret = new byte[1];
    ByteArrayOutputStream b = new ByteArrayOutputStream();

    String BOUNDARY = "----------ThIs_Is_tHe_bouNdaRY_$";
    String CRLF = "\r\n";

    Enumeration<String> i = values.keys();
    String x = null;/*from   ww  w .  j  av  a  2s.c  o  m*/
    String y = null;

    // values
    while (i.hasMoreElements()) {
        x = i.nextElement();
        y = values.get(x);

        if (b.size() > 0) {
            b.write(CRLF.getBytes());
        } else {
            //ret = "";
        }
        //ret = ret + "--" + BOUNDARY + CRLF;
        //ret = ret + "Content-Disposition: form-data; name=\"" + x + "\"" + CRLF;
        //ret = ret + CRLF;
        //ret = ret + y;
        b.write(("--" + BOUNDARY + CRLF).getBytes());
        b.write(("Content-Disposition: form-data; name=\"" + x + "\"" + CRLF).getBytes());
        b.write((CRLF + y).getBytes());
    }

    // file
    if (b.size() > 0) {
        //ret = ret + CRLF;
        b.write(CRLF.getBytes());
    } else {
        //ret = "";
    }
    b.write(("--" + BOUNDARY + CRLF + "Content-Disposition: form-data; name=\"" + file_field + "\"; filename=\""
            + filename + "\"" + CRLF + "Content-Type: " + "text/plain" + CRLF + CRLF).getBytes());
    b.write(file_data);

    // finish
    if (b.size() > 0) {
        // ret = ret + CRLF;
        b.write(CRLF.getBytes());
    } else {
        // ret = "";
    }
    b.write(("--" + BOUNDARY + "--" + CRLF + CRLF).getBytes());

    ret2.data = b;
    ret2.encoding = String.format("multipart/form-data; boundary=%s", BOUNDARY);
    return ret2;
}

From source file:org.abstracthorizon.proximity.maven.MavenProximityLogic.java

/**
 * This postprocessing simply merges the fetched list of metadatas.
 * /*from   w ww .  j a  v  a2  s .  c o  m*/
 * @param request the request
 * @param groupRequest the group request
 * @param listOfProxiedItems the list of proxied items
 * 
 * @return the merged metadata.
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public Item postprocessItemList(ProximityRequest request, ProximityRequest groupRequest,
        List listOfProxiedItems) throws IOException {

    if (listOfProxiedItems.size() == 0) {

        throw new IllegalArgumentException("The listOfProxiedItems list cannot be 0 length!");
    }

    Item item = (Item) listOfProxiedItems.get(0);
    ItemProperties itemProps = item.getProperties();

    if (listOfProxiedItems.size() > 1) {

        if (MavenArtifactRecognizer.isChecksum(request.getPath())) {

            File tmpFile = new File(System.getProperty("java.io.tmpdir"),
                    request.getPath().replace(ItemProperties.PATH_SEPARATOR.charAt(0), '_'));
            if (tmpFile.exists()) {
                logger.info("Item for path " + request.getPath() + " SPOOFED with merged metadata checksum.");
                item.setStream(new DeleteOnCloseFileInputStream(tmpFile));
                itemProps.setSize(tmpFile.length());
            } else {
                logger.debug("Item for path " + request.getPath() + " SPOOFED with first got from repo group.");
            }

        } else {
            logger.debug("Item for path " + request.getPath() + " found in total of "
                    + listOfProxiedItems.size() + " repositories, will merge them.");

            MetadataXpp3Reader metadataReader = new MetadataXpp3Reader();
            MetadataXpp3Writer metadataWriter = new MetadataXpp3Writer();
            InputStreamReader isr;

            Metadata mergedMetadata = null;

            for (int i = 0; i < listOfProxiedItems.size(); i++) {

                Item currentItem = (Item) listOfProxiedItems.get(i);
                try {
                    isr = new InputStreamReader(currentItem.getStream());
                    Metadata imd = metadataReader.read(isr);
                    if (mergedMetadata == null) {
                        mergedMetadata = imd;
                    } else {
                        mergedMetadata.merge(imd);
                    }
                    isr.close();
                } catch (XmlPullParserException ex) {
                    logger.warn("Could not merge M2 metadata: " + currentItem.getProperties().getDirectoryPath()
                            + " from repository " + currentItem.getProperties().getRepositoryId(), ex);
                } catch (IOException ex) {
                    logger.warn("Got IOException during merge of M2 metadata: "
                            + currentItem.getProperties().getDirectoryPath() + " from repository "
                            + currentItem.getProperties().getRepositoryId(), ex);
                }

            }

            try {
                // we know that maven-metadata.xml is relatively small
                // (few
                // KB)
                MessageDigest md5alg = MessageDigest.getInstance("md5");
                MessageDigest sha1alg = MessageDigest.getInstance("sha1");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DigestOutputStream md5os = new DigestOutputStream(bos, md5alg);
                DigestOutputStream sha1os = new DigestOutputStream(md5os, sha1alg);
                OutputStreamWriter osw = new OutputStreamWriter(sha1os);
                metadataWriter.write(osw, mergedMetadata);
                osw.flush();
                osw.close();

                storeDigest(request, md5alg);
                storeDigest(request, sha1alg);

                ByteArrayInputStream is = new ByteArrayInputStream(bos.toByteArray());
                item.setStream(is);
                itemProps.setSize(bos.size());
            } catch (NoSuchAlgorithmException ex) {
                throw new IllegalArgumentException("No MD5 or SHA1 algorithm?");
            }
        }

    }

    return item;
}