List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.bibsonomy.rest.RestServlet.java
/** * @param request//from w ww .j a v a2 s. c o m * the servletrequest * @param response * the servletresponse * @param method * httpMethod to use, see {@link HttpMethod} * @throws IOException */ private void handle(final HttpServletRequest request, final HttpServletResponse response, final HttpMethod method) throws IOException { log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP " + request.getHeader("x-forwarded-for")); final long start = System.currentTimeMillis(); try { // validate the requesting user's authorization final LogicInterface logic = validateAuthorization(request); // parse the request object to retrieve a list with all items of the // http request final MultiPartRequestParser parser = new MultiPartRequestParser(request); // choose rendering format (defaults to xml) final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest( request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType()); // create Context final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING); final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer, reader, parser.getList(), logic, request.getParameterMap(), additionalInfos); // validate request context.canAccess(); // set some response headers final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT); log.debug("[USER-AGENT] " + userAgent); response.setContentType(context.getContentType(userAgent)); response.setCharacterEncoding(RESPONSE_ENCODING); // send answer if (method.equals(HttpMethod.POST)) { // if a POST request completes successfully this means that a // resource has been created response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_OK); } // just define an ByteArrayOutputStream to store all outgoing data final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream(); context.perform(cachingStream); /* * XXX: note: cachingStream.size() != * cachingStream.toString().length() !! the correct value is the * first one! */ response.setContentLength(cachingStream.size()); // some more logging log.debug("Size of output sent:" + cachingStream.size()); final long elapsed = System.currentTimeMillis() - start; log.debug("Processing time: " + elapsed + " ms"); cachingStream.writeTo(response.getOutputStream()); } catch (final AuthenticationException e) { log.warn(e.getMessage()); response.setHeader("WWW-Authenticate", "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\""); sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage()); } catch (final InternServerException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (final NoSuchResourceException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (final BadRequestOrResponseException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (final AccessDeniedException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (final ResourceMovedException e) { log.error(e.getMessage()); /* * sending new location TODO: add date using */ response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash())); sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage()); } catch (final DatabaseException e) { final StringBuilder returnMessage = new StringBuilder(""); for (final String hash : e.getErrorMessages().keySet()) { for (final ErrorMessage em : e.getErrorMessages(hash)) { log.error(em.toString()); returnMessage.append(em.toString() + "\n "); } } sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString()); } catch (final Exception e) { log.error(e, e); // well, lets fetch each and every error... sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndUpdateRepresentation() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-18"); this.postEntity(ie1); Representation r = new Representation.Builder(ie1.getRepresentations().get(0)).title("title update") .build();/* w w w.jav a2 s .c o m*/ HttpPut put = new HttpPut(SCAPE_URL + "/representation/entity-18/" + r.getIdentifier().getValue()); ByteArrayOutputStream sink = new ByteArrayOutputStream(); this.marshaller.serialize(r, sink); put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(), ContentType.TEXT_XML)); HttpResponse resp = this.client.execute(put); assertEquals(200, resp.getStatusLine().getStatusCode()); put.releaseConnection(); /* fetch the representation and check that the title has been updated */ HttpGet get = new HttpGet(SCAPE_URL + "/representation/entity-18/" + r.getIdentifier().getValue()); resp = this.client.execute(get); assertEquals(200, resp.getStatusLine().getStatusCode()); Representation fetched = this.marshaller.deserialize(Representation.class, resp.getEntity().getContent()); assertEquals(r.getIdentifier().getValue(), fetched.getIdentifier().getValue()); assertEquals("title update", fetched.getTitle()); get.releaseConnection(); }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndUpdateRepresentationAndFetchOldVersion() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-24"); this.postEntity(ie1); Representation r = new Representation.Builder(ie1.getRepresentations().get(0)).title("title update") .build();//from w ww .j a va 2 s . com HttpPut put = new HttpPut(SCAPE_URL + "/representation/entity-24/" + r.getIdentifier().getValue()); ByteArrayOutputStream sink = new ByteArrayOutputStream(); this.marshaller.serialize(r, sink); put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(), ContentType.TEXT_XML)); HttpResponse resp = this.client.execute(put); assertEquals(200, resp.getStatusLine().getStatusCode()); put.releaseConnection(); /* fetch the representation and check that the title has been updated */ HttpGet get = new HttpGet(SCAPE_URL + "/representation/entity-24/" + r.getIdentifier().getValue() + "/1"); resp = this.client.execute(get); assertEquals(200, resp.getStatusLine().getStatusCode()); Representation fetched = this.marshaller.deserialize(Representation.class, resp.getEntity().getContent()); assertEquals(r.getIdentifier().getValue(), fetched.getIdentifier().getValue()); assertEquals("Text representation", fetched.getTitle()); get.releaseConnection(); }
From source file:org.apache.axis.attachments.AttachmentPart.java
/** * Returns the number of bytes in this <CODE> * AttachmentPart</CODE> object./*from w w w.ja v a 2 s . com*/ * @return the size of this <CODE>AttachmentPart</CODE> object * in bytes or -1 if the size cannot be determined * @throws SOAPException if the content of this * attachment is corrupted of if there was an exception * while trying to determine the size. */ public int getSize() throws SOAPException { if (datahandler == null) { return 0; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { datahandler.writeTo(bout); } catch (java.io.IOException ex) { log.error(Messages.getMessage("javaIOException00"), ex); throw new SOAPException(Messages.getMessage("javaIOException01", ex.getMessage()), ex); } return bout.size(); }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndUpdateFileAndFetchOldVersion() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-25"); this.postEntity(ie1); File f = new File.Builder(ie1.getRepresentations().get(0).getFiles().get(0)) .uri(URI.create(TestUtil.class.getClassLoader().getResource("scape_logo.png").toString())) .filename("wikipedia.png").mimetype("image/png").build(); Representation r = new Representation.Builder(ie1.getRepresentations().get(0)).title("title update") .files(Arrays.asList(f)).build(); HttpPut put = new HttpPut(SCAPE_URL + "/representation/entity-25/" + r.getIdentifier().getValue()); ByteArrayOutputStream sink = new ByteArrayOutputStream(); this.marshaller.serialize(r, sink); put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(), ContentType.TEXT_XML));//from www .ja v a2s .c o m HttpResponse resp = this.client.execute(put); assertEquals(200, resp.getStatusLine().getStatusCode()); put.releaseConnection(); /* fetch the file */ HttpGet get = new HttpGet(SCAPE_URL + "/file/entity-25/" + r.getIdentifier().getValue() + "/" + f.getIdentifier().getValue() + "/1"); resp = this.client.execute(get); assertEquals(200, resp.getStatusLine().getStatusCode()); get.releaseConnection(); }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndUpdateEntityMetadata() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-19"); this.postEntity(ie1); org.purl.dc.elements._1.ObjectFactory dcFac = new org.purl.dc.elements._1.ObjectFactory(); ElementContainer cnt = dcFac.createElementContainer(); SimpleLiteral lit_title = new SimpleLiteral(); lit_title.getContent().add("DC metadata updated"); cnt.getAny().add(dcFac.createTitle(lit_title)); HttpPut put = new HttpPut(SCAPE_URL + "/metadata/entity-19/DESCRIPTIVE"); ByteArrayOutputStream sink = new ByteArrayOutputStream(); this.marshaller.serialize(cnt, sink); put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(), ContentType.TEXT_XML));//from www . j a va2 s .c om HttpResponse resp = this.client.execute(put); assertEquals(200, resp.getStatusLine().getStatusCode()); put.releaseConnection(); /* fetch the entity and check that the title has been updated */ HttpGet get = new HttpGet(SCAPE_URL + "/metadata/entity-19/DESCRIPTIVE"); resp = this.client.execute(get); assertEquals(200, resp.getStatusLine().getStatusCode()); ElementContainer fetched = (ElementContainer) this.marshaller.deserialize(resp.getEntity().getContent()); assertEquals("DC metadata updated", fetched.getAny().get(0).getValue().getContent().get(0)); get.releaseConnection(); }
From source file:eu.scape_project.fcrepo.integration.IntellectualEntitiesIT.java
@Test public void testIngestAndUpdateRepresentationMetadata() throws Exception { IntellectualEntity ie1 = TestUtil.createTestEntity("entity-20"); this.postEntity(ie1); org.purl.dc.elements._1.ObjectFactory dcFac = new org.purl.dc.elements._1.ObjectFactory(); ElementContainer cnt = dcFac.createElementContainer(); SimpleLiteral lit_title = new SimpleLiteral(); lit_title.getContent().add("SOURCE metadata updated"); cnt.getAny().add(dcFac.createTitle(lit_title)); HttpPut put = new HttpPut(SCAPE_URL + "/metadata/entity-20/representation-1/SOURCE"); ByteArrayOutputStream sink = new ByteArrayOutputStream(); this.marshaller.serialize(cnt, sink); put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(), ContentType.TEXT_XML));//ww w .ja v a 2 s. co m HttpResponse resp = this.client.execute(put); assertEquals(200, resp.getStatusLine().getStatusCode()); put.releaseConnection(); /* fetch the entity and check that the title has been updated */ HttpGet get = new HttpGet(SCAPE_URL + "/metadata/entity-20/representation-1/SOURCE"); resp = this.client.execute(get); assertEquals(200, resp.getStatusLine().getStatusCode()); ElementContainer fetched = (ElementContainer) this.marshaller.deserialize(resp.getEntity().getContent()); assertEquals("SOURCE metadata updated", fetched.getAny().get(0).getValue().getContent().get(0)); get.releaseConnection(); }
From source file:opendap.xml.Transformer.java
public InputStream transform(String inputDocumentUrl) throws SaxonApiException { StreamSource s = new StreamSource(inputDocumentUrl); ByteArrayOutputStream os = new ByteArrayOutputStream(); serializer.setOutputStream(os);//from w ww . ja va 2s . c o m transform.setSource(s); transform.setDestination(serializer); transform.transform(); ByteArrayInputStream bis = new ByteArrayInputStream(os.toByteArray()); log.debug("Transformed document is " + os.size() + " bytes."); return bis; }
From source file:org.hyperic.hq.agent.db.DiskList.java
/** * Add the string to the list of data being stored in the DiskList. * * @param data Data to add to the end of the list *///from w ww.j a v a2 s. c om public void addToList(String data) throws IOException { if (this.closed) { throw new IOException("Datafile already closed"); } ByteArrayOutputStream bOs = new ByteArrayOutputStream(this.recordSize); DataOutputStream dOs = new DataOutputStream(bOs); dOs.writeUTF(data); if (bOs.size() > this.recordSize) { throw new IOException( "Data length(" + bOs.size() + ") exceeds " + "maximum record length(" + this.recordSize + ")"); } final long start = now(); bOs.write(this.padBytes, 0, this.recordSize - bOs.size()); byte[] bytes = bOs.toByteArray(); synchronized (this.dataFile) { Long firstFreeL; long firstFree; this.modNum = this.rand.nextInt(); try { firstFreeL = (Long) this.freeList.first(); firstFree = firstFreeL.longValue(); this.freeList.remove(firstFreeL); } catch (NoSuchElementException exc) { // Else we're adding to the end firstFree = this.indexFile.length() / IDX_REC_LEN; } // Write the record to the data file this.dataFile.seek(firstFree * this.recordSize); this.dataFile.write(bytes); bOs.reset(); dOs.writeBoolean(true); // Is Used dOs.writeLong(this.lastRec); // Previous record idx dOs.writeLong(-1); // Next record idx // Write the index for the record we just made this.indexFile.seek(firstFree * IDX_REC_LEN); bytes = bOs.toByteArray(); this.indexFile.write(bytes, 0, bytes.length); // Update the previous 'last' record to point to us if (this.lastRec != -1) { this.indexFile.seek((this.lastRec * IDX_REC_LEN) + 1 + 8); this.indexFile.writeLong(firstFree); } this.lastRec = firstFree; if (this.firstRec == -1) { this.firstRec = firstFree; } } if (this.dataFile.length() > this.maxLength) { this.log.error("Maximum file size for data file: " + this.fileName + " reached (" + this.maxLength + " bytes), truncating."); deleteAllRecords(); } long duration = now() - start; statsCollector.addStat(duration, DISK_LIST_ADD_TO_LIST_TIME); }
From source file:org.apache.camel.component.dropbox.core.DropboxAPIFacade.java
private void downloadSingleFile(String path, Map<String, ByteArrayOutputStream> resultEntries) throws DropboxException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DbxEntry.File downloadedFile; try {/* w ww . jav a 2s. c o m*/ downloadedFile = DropboxAPIFacade.client.getFile(path, null, baos); } catch (DbxException e) { throw new DropboxException(path + " does not exist or can't obtain metadata"); } catch (IOException e) { throw new DropboxException(path + " can't obtain a stream"); } if (downloadedFile != null) { resultEntries.put(path, baos); LOG.info("downloaded path:" + path + " - baos size:" + baos.size()); } }