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:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java

/**
 * Tests that if network connection dropped during a product retrieval that is in progress and
 * actively being cached, that the (partially) cached file is deleted and not
 * placed in the cache map./*from w  w w . j a  va 2s .com*/
 *
 * @throws Exception
 */
@Test
@Ignore
public void testNetworkConnectionDroppedDuringProductDownload() throws Exception {

    mis = new MockInputStream(productInputFilename);
    Metacard metacard = getMockMetacard(EXPECTED_METACARD_ID, EXPECTED_METACARD_SOURCE_ID);
    resourceResponse = getMockResourceResponse();

    ResourceRetriever retriever = getMockResourceRetrieverWithRetryCapability(
            RetryType.NETWORK_CONNECTION_DROPPED);

    int chunkSize = 50;
    startDownload(true, chunkSize, false, metacard, retriever);

    ByteArrayOutputStream clientBytesRead = clientRead(chunkSize, productInputStream);

    // Verify client did not receive entire product download
    assertTrue(clientBytesRead.size() < expectedFileSize);

    // Verify product was not cached, i.e., its pending caching entry was removed
    String cacheKey = new CacheKey(metacard, resourceResponse.getRequest()).generateKey();
    verify(resourceCache, timeout(3000)).removePendingCacheEntry(cacheKey);

    cleanup();
}

From source file:com.liferay.mobile.android.http.file.FileDownloadTest.java

@Test
public void download() throws Exception {
    BasicAuthentication basic = (BasicAuthentication) session.getAuthentication();

    DigestAuthentication digest = new DigestAuthentication(basic.getUsername(), basic.getPassword());

    session.setAuthentication(digest);/*from ww w  .ja v  a2s.c o  m*/

    String url = session.getServer() + "/webdav/guest/document_library/"
            + _file.getString(DLAppServiceTest.TITLE);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    FileProgressCallback callback = new FileProgressCallback() {

        @Override
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    Response response = HttpUtil.download(session, url, callback);
    assertNotNull(response);
    assertEquals(Status.OK, response.getStatusCode());
    assertEquals(5, baos.size());
}

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

public static void validateURLFPFlagSerializationOneSubDomain() {
    TreeMultimap<Integer, URLFP> sourceMap = TreeMultimap.create();
    TreeMultimap<Integer, URLFP> destMap = TreeMultimap.create();
    ;// w w w  . j ava  2s.co  m

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

    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "0", 1, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "1", 2, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "2", 3, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "3", 4, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "4", 5, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "5", 6, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "6", 7, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "7", 8, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "8", 9, 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:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic./*from  w  w  w .  j ava 2s . co  m*/
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Path path = new Path(req.getRequestURI());
    String pluginId = path.lastSegment();
    if (pluginId.endsWith(".jar")) {
        pluginId = pluginId.substring(0, pluginId.length() - 4);
    }//from   w w w.  j a va 2 s.c  o m
    final Bundle b = Platform.getBundle(pluginId);
    if (b == null) {
        final String protocol = req.getProtocol();
        final String msg = "Plugin does not exist: " + pluginId;
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
        return;
    }
    final File file = FileLocator.getBundleFile(b);
    resp.setContentType("application/octet-stream");

    if (file.isFile()) {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setContentLength((int) file.length());
        final FileInputStream istream = new FileInputStream(file);
        try {
            IOUtils.copy(istream, resp.getOutputStream());
        } finally {
            istream.close();
        }
        resp.flushBuffer();
    } else {
        final String contentDisposition = "attachment; filename=\"" + file.getName() + ".jar\"";
        resp.setHeader("Content-Disposition", contentDisposition);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Manifest man = new Manifest(new FileInputStream(new File(file, "META-INF/MANIFEST.MF")));
        final JarOutputStream out = new JarOutputStream(outputStream, man);
        final File binDir = new File(file, "bin");

        if (binDir.exists()) {
            addFiles(out, Path.ROOT, binDir.listFiles());
            for (final File f : file.listFiles()) {
                if (!f.getName().equals("bin")) {
                    addFiles(out, Path.ROOT, f);
                }
            }
        } else {
            addFiles(out, Path.ROOT, file.listFiles());
        }
        out.close();
        outputStream.close();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        resp.setContentLength(outputStream.size());
        try {
            IOUtils.copy(inputStream, resp.getOutputStream());
        } finally {
            inputStream.close();
        }
        resp.flushBuffer();
    }

}

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

public static void validateURLFPFlagSerializationOneSubDomain() {
    TreeMultimap<Long, URLFPV2> sourceMap = TreeMultimap.create();
    TreeMultimap<Long, URLFPV2> destMap = TreeMultimap.create();
    ;//from   w w w  . j  a va 2s  .  c o m

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

    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "0", 1, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "1", 2, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "2", 3, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "3", 4, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "4", 5, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "5", 6, 0);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "6", 7, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "7", 8, 255);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "8", 9, 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()) {
            URLFPV2 fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

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

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

From source file:org.openhab.binding.ihc.ws.IhcClient.java

private Document LoadProjectFileFromController() throws IhcExecption {

    try {/*from   w w  w  .  j a v a 2s .c o m*/

        WSProjectInfo projectInfo = getProjectInfo();
        int numberOfSegments = controllerService.getProjectNumberOfSegments();
        int segmentationSize = controllerService.getProjectSegmentationSize();

        logger.debug("Number of segments: {}", numberOfSegments);
        logger.debug("Segmentation size: {}", segmentationSize);

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        for (int i = 0; i < numberOfSegments; i++) {
            logger.debug("Downloading segment {}", i);

            WSFile data = controllerService.getProjectSegment(i, projectInfo.getProjectMajorRevision(),
                    projectInfo.getProjectMinorRevision());
            byteStream.write(data.getData());
        }

        logger.debug("File size before base64 encoding: {} bytes", byteStream.size());

        byte[] decodedBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(byteStream.toString());

        logger.debug("File size after base64 encoding: {} bytes", decodedBytes.length);

        GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(decodedBytes));

        InputStreamReader in = new InputStreamReader(gzis, "ISO-8859-1");
        InputSource reader = new InputSource(in);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(reader);

    } catch (Exception e) {
        throw new IhcExecption(e);
    }

}

From source file:com.aol.webservice_base.util.http.HttpHelper.java

/**
 * Output data./*from  w w  w.j a  v  a  2 s .c o  m*/
 *
 * @param in the in
 * @return the byte[]
 * @throws HttpException the http exception
 */
private byte[] outputData(java.io.InputStream in) throws HttpException {
    final String METHOD = "HttpHelper.outputData()";
    if (logger.isDebugEnabled()) {
        logger.debug(METHOD + ": Enter");
    }
    try {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int len;
        while ((len = in.read(buf, 0, buf.length)) > 0) {
            data.write(buf, 0, len);
            if (logger.isDebugEnabled()) {
                logger.debug("read size = " + len);
                // logger.debug("Data size = "+data.size());
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(METHOD + ": Leave with total data size = [" + data.size() + "]");
        }
        return data.toByteArray();

    } catch (IOException e) {
        logger.error(METHOD, e);
        throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } catch (Throwable t) {
        logger.error(METHOD, t);
        throw new HttpException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t);
    }
}

From source file:org.dataconservancy.ui.api.PersonController.java

/**
 * Handles the posting of a new person, this will add a new person to the
 * system with registration status of pending.
 *
 * @throws org.dataconservancy.model.builder.InvalidXmlException
 * @throws java.io.IOException/*from w  w  w. ja v  a 2  s.  c  o  m*/
 */
@RequestMapping(method = { RequestMethod.POST })
public void handlePersonPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, BizPolicyException, InvalidXmlException, IOException {
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }
    //use businessobjectBuilder to deserialize content into a bop -> set of person
    Set<Person> postedPersonSet = builder.buildBusinessObjectPackage(new ByteArrayInputStream(content))
            .getPersons();
    //currently, only handle request to create 1 person
    //A request is considered BAD if it contains 0 person, or more than 1 person
    if (postedPersonSet.size() != 1) {
        try {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getWriter()
                    .print("Only one new person can be requested to be created via this API at a time.");
            resp.getWriter().flush();
            resp.getWriter().close();
        } catch (Exception ee) {
            log.debug("Handling exception", ee);
        }
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Person person = postedPersonSet.iterator().next();
        try {
            Person createPerson = userService.create(person);
            //Serialize the created Person to return
            Bop businessObjectPackage = new Bop();
            businessObjectPackage.addPerson(createPerson);

            resp.setStatus(HttpStatus.SC_OK);

            resp.setHeader(LOCATION, createPerson.getId());
            resp.setHeader(LAST_MODIFIED, DateTime.now().toString());
            builder.buildBusinessObjectPackage(businessObjectPackage, baos);
            resp.setHeader(ETAG, ETagCalculator.calculate(Integer.toString(businessObjectPackage.hashCode())));
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/xml");
            resp.setContentLength(baos.size());
            baos.writeTo(resp.getOutputStream());
        } catch (PersonUpdateException re) {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getOutputStream().println(re.getMessage());
            resp.getWriter().flush();
            resp.getWriter().close();
        }
    }
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = RequestMethod.POST)
public void exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
        HttpServletRequest request) throws ServletException, IOException, InterruptedException,
        SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

    long start1 = System.currentTimeMillis();

    MimeType mime = getMime(type);
    filename = getFilename(filename);//from  w w w . j a va  2  s.  c  om
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    String input;

    boolean convertSvg = false;

    if (options != null) {
        // create a svg file out of the options
        input = options;
        callback = sanitize(callback);
    } else {
        // assume SVG conversion
        if (svg == null) {
            throw new ServletException("The manadatory svg POST parameter is undefined.");
        } else {
            svg = sanitize(svg);
            if (svg == null) {
                throw new ServletException("The manadatory svg POST parameter is undefined.");
            }
            convertSvg = true;
            input = svg;
        }
    }

    ByteArrayOutputStream stream = null;
    if (convertSvg && mime.equals(MimeType.SVG)) {
        // send this to the client, without converting.
        stream = new ByteArrayOutputStream();
        stream.write(input.getBytes());
    } else {
        //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);
        stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);
    }

    if (stream == null) {
        throw new ServletException("Error while converting");
    }

    logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentLength(stream.size());
    response.setStatus(HttpStatus.OK.value());
    response.setHeader("Content-disposition",
            "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\"");

    IOUtils.write(stream.toByteArray(), response.getOutputStream());
    response.flushBuffer();
}