Java Code Examples for java.io.ByteArrayOutputStream#writeTo()

The following examples show how to use java.io.ByteArrayOutputStream#writeTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MarshallingView.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	Object toBeMarshalled = locateToBeMarshalled(model);
	if (toBeMarshalled == null) {
		throw new IllegalStateException("Unable to locate object to be marshalled in model: " + model);
	}

	Assert.state(this.marshaller != null, "No Marshaller set");
	ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
	this.marshaller.marshal(toBeMarshalled, new StreamResult(baos));

	setResponseContentType(request, response);
	response.setContentLength(baos.size());
	baos.writeTo(response.getOutputStream());
}
 
Example 2
Source File: MemoryConsumption.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/38989235/itext-html-to-pdf-memory-leak">
 * IText HTML to PDF memory leak
 * </a>
 * <p>
 * The OP's code plus a save-to-file.
 * </p>
 */
public void testDevelofersScenario(String outputName) throws IOException, DocumentException
{
    final String content = "<!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->\n<html>\n <head>\n    <title>Title</title>\n    \n   \n </head>\n"
            + "\n    \n<body>  \n  \n      \nEXAMPLE\n\n</body>\n</html>";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);        
    document.open();
    InputStream is = new ByteArrayInputStream(content.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);

    document.close();
    
    baos.writeTo(new FileOutputStream(new File(RESULT_FOLDER, outputName)));
}
 
Example 3
Source File: CodeController.java    From taoshop with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/generate")
	public void generate(HttpServletRequest request, HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);

//		Subject currentUser = SecurityUtils.getSubject();
//		Session session = currentUser.getSession();
		HttpSession session = request.getSession();
		session.setAttribute(SESSION_SECURITY_CODE, code);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
Example 4
Source File: CodeController.java    From taoshop with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/generate")
public void generate(HttpServletResponse response){
	ByteArrayOutputStream output = new ByteArrayOutputStream();
	String code = drawImg(output);
	
	Subject currentUser = SecurityUtils.getSubject();  
	Session session = currentUser.getSession();
	session.setAttribute(Constants.SESSION_SECURITY_CODE, code);

	try {
		ServletOutputStream out = response.getOutputStream();
		output.writeTo(out);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: MessageDumper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void dump(ByteArrayOutputStream bos, String name, String way) {
   try {
      if (path != null && !"".equals(path)) {
         File dir = new File(path);
         if (dir.exists() && dir.isDirectory()) {
            OutputStream fos = new FileOutputStream(this.generateFileName(name, way));
            bos.writeTo(fos);
            fos.close();
         }
      }
   } catch (FileNotFoundException var6) {
      LOG.error("dump error", var6);
   } catch (IOException var7) {
      LOG.error("dump error", var7);
   }

}
 
Example 6
Source File: MarshallingView.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	Object toBeMarshalled = locateToBeMarshalled(model);
	if (toBeMarshalled == null) {
		throw new IllegalStateException("Unable to locate object to be marshalled in model: " + model);
	}

	Assert.state(this.marshaller != null, "No Marshaller set");
	ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
	this.marshaller.marshal(toBeMarshalled, new StreamResult(baos));

	setResponseContentType(request, response);
	response.setContentLength(baos.size());
	baos.writeTo(response.getOutputStream());
}
 
Example 7
Source File: DownloadResource.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/download", method = RequestMethod.GET)
@Timed
public void downloadArtifact(@RequestParam(value = "url") String url, HttpServletResponse response) {
    log.debug("REST request to download artifact/document file");

    // 暂时不在HTTP响应头中传递文件名,因为文件名可能是中文
    // String fileName = url.substring(artifactUrl.lastIndexOf("/") + 1);
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "0");
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    // response.setHeader("x-filename", fileName);
    // response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    response.setHeader("Content-Disposition", "attachment");
    response.setStatus(HttpServletResponse.SC_OK);

    try {
        ByteArrayOutputStream byteArrayOutputStream = nexusArtifactClient.getArtifact(url);
        byteArrayOutputStream.writeTo(response.getOutputStream());
        response.flushBuffer();
        if (null != byteArrayOutputStream) {
            byteArrayOutputStream.close();
        }
    } catch (Exception e) {
    }
}
 
Example 8
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
    t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
    if (shouldUseCompression(t)) {
        t.getResponseHeaders().set("Content-Encoding", "gzip");
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
        final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
        response.writeTo(os);
        os.finish();
    } else {
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
Example 9
Source File: CdmrfWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private long sendData(Array data, OutputStream out, boolean deflate) throws IOException {

    // length of data uncompressed
    long uncompressedLength = data.getSizeBytes();
    long size = 0;

    if (deflate) {
      // write to an internal buffer, so we can find out the size
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      DeflaterOutputStream dout = new DeflaterOutputStream(bout);
      IospHelper.copyToOutputStream(data, dout);

      // write internal buffer to output stream
      dout.close();
      int deflatedSize = bout.size();
      size += NcStream.writeVInt(out, deflatedSize);
      bout.writeTo(out);
      size += deflatedSize;

    } else {
      size += NcStream.writeVInt(out, (int) uncompressedLength);
      size += IospHelper.copyToOutputStream(data, out);
    }

    return size;
  }
 
Example 10
Source File: CdmrGridController.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private long sendData(Array data, OutputStream out, boolean deflate) throws IOException, InvalidRangeException {

    // length of data uncompressed
    long uncompressedLength = data.getSizeBytes();
    long size = 0;


    if (deflate) {
      // write to an internal buffer, so we can find out the size
      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      DeflaterOutputStream dout = new DeflaterOutputStream(bout);
      IospHelper.copyToOutputStream(data, dout);

      // write internal buffer to output stream
      dout.close();
      int deflatedSize = bout.size();
      size += NcStream.writeVInt(out, deflatedSize);
      bout.writeTo(out);
      size += deflatedSize;
      float ratio = ((float) uncompressedLength) / deflatedSize;
      if (showRes)
        System.out.printf("  org/compress= %d/%d = %f%n", uncompressedLength, deflatedSize, ratio);

    } else {
      size += NcStream.writeVInt(out, (int) uncompressedLength);
      size += IospHelper.copyToOutputStream(data, out);
    }

    return size;
  }
 
Example 11
Source File: AbstractView.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Write the given temporary OutputStream to the HTTP response.
 * @param response current HTTP response
 * @param baos the temporary OutputStream to write
 * @throws IOException if writing/flushing failed
 */
protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos) throws IOException {
	// Write content type and also length (determined via byte array).
	response.setContentType(getContentType());
	response.setContentLength(baos.size());

	// Flush byte array to servlet output stream.
	ServletOutputStream out = response.getOutputStream();
	baos.writeTo(out);
	out.flush();
}
 
Example 12
Source File: MessageDumper.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Dump.
 * 
 * @param bos the bos
 * @param name the name
 */
public void dump(ByteArrayOutputStream bos, String name, String way) {
	try {
		if (path != null && !"".equals(path)) {
			File dir = new File(path);
			if(dir.exists() && dir.isDirectory()) {
				OutputStream fos = new FileOutputStream(generateFileName(name, way));
				bos.writeTo(fos); 
				fos.close();			
			}
		}
	} catch (IOException e) {
		LOG.error("dump error",e);
	} 
}
 
Example 13
Source File: AbstractView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Write the given temporary OutputStream to the HTTP response.
 * @param response current HTTP response
 * @param baos the temporary OutputStream to write
 * @throws IOException if writing/flushing failed
 */
protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos) throws IOException {
	// Write content type and also length (determined via byte array).
	response.setContentType(getContentType());
	response.setContentLength(baos.size());

	// Flush byte array to servlet output stream.
	ServletOutputStream out = response.getOutputStream();
	baos.writeTo(out);
	out.flush();
}
 
Example 14
Source File: EventIdFirstSchemaRecordWriter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized void writeHeader(final long firstEventId, final DataOutputStream out) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    eventSchema.writeTo(baos);

    out.writeInt(baos.size());
    baos.writeTo(out);

    baos.reset();
    headerSchema.writeTo(baos);
    out.writeInt(baos.size());
    baos.writeTo(out);

    this.firstEventId = firstEventId;
    this.systemTimeOffset = System.currentTimeMillis();

    final Map<String, Object> headerValues = new HashMap<>();
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.FIRST_EVENT_ID, firstEventId);
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.TIMESTAMP_OFFSET, systemTimeOffset);
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.COMPONENT_IDS, idLookup.getComponentIdentifiers());
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.COMPONENT_TYPES, idLookup.getComponentTypes());
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.QUEUE_IDS, idLookup.getQueueIdentifiers());
    headerValues.put(EventIdFirstHeaderSchema.FieldNames.EVENT_TYPES, eventTypeNames);
    final FieldMapRecord headerInfo = new FieldMapRecord(headerSchema, headerValues);

    schemaRecordWriter.writeRecord(headerInfo, out);
}
 
Example 15
Source File: ByteArraySchemaRecordWriter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void writeHeader(final long firstEventId, final DataOutputStream out) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    eventSchema.writeTo(baos);

    out.writeInt(baos.size());
    baos.writeTo(out);
}
 
Example 16
Source File: TestSchemaRecordReaderWriter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a SchemaRecordWriter that uses a modified schema
 *
 * @param fieldModifier the callback for modifying the schema
 * @return a SchemaRecordWriter that uses the modified schema
 * @throws IOException if unable to create the writer
 */
private ByteArraySchemaRecordWriter createSchemaWriter(final Consumer<List<RecordField>> fieldModifier, final Map<RecordField, Object> fieldsToAdd) throws IOException {
    final TocWriter tocWriter = new StandardTocWriter(tocFile, false, false);

    // Create a schema that has the fields modified
    final RecordSchema schemaV1 = ProvenanceEventSchema.PROVENANCE_EVENT_SCHEMA_V1;
    final List<RecordField> fields = new ArrayList<>(schemaV1.getFields());
    fieldModifier.accept(fields);

    final RecordSchema recordSchema = new RecordSchema(fields);
    final RecordSchema contentClaimSchema = new RecordSchema(recordSchema.getField(EventFieldNames.CONTENT_CLAIM).getSubFields());

    final ByteArraySchemaRecordWriter writer = new ByteArraySchemaRecordWriter(journalFile, idGenerator, tocWriter, false, 0) {
        @Override
        public void writeHeader(long firstEventId, DataOutputStream out) throws IOException {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            recordSchema.writeTo(baos);

            out.writeInt(baos.size());
            baos.writeTo(out);
        }

        @Override
        protected Record createRecord(final ProvenanceEventRecord event, final long eventId) {
            final Map<RecordField, Object> values = new HashMap<>();

            final EventRecord eventRecord = new EventRecord(event, eventId, recordSchema, contentClaimSchema);
            for (final RecordField field : recordSchema.getFields()) {
                final Object value = eventRecord.getFieldValue(field);
                values.put(field, value);
            }

            values.putAll(fieldsToAdd);
            return new FieldMapRecord(values, recordSchema);
        }
    };

    return writer;
}
 
Example 17
Source File: ViewDebug.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static void captureViewLayer(View view, DataOutputStream clientStream, boolean visible)
        throws IOException {

    final boolean localVisible = view.getVisibility() == View.VISIBLE && visible;

    if ((view.mPrivateFlags & View.PFLAG_SKIP_DRAW) != View.PFLAG_SKIP_DRAW) {
        final int id = view.getId();
        String name = view.getClass().getSimpleName();
        if (id != View.NO_ID) {
            name = resolveId(view.getContext(), id).toString();
        }

        clientStream.write(1);
        clientStream.writeUTF(name);
        clientStream.writeByte(localVisible ? 1 : 0);

        int[] position = new int[2];
        // XXX: Should happen on the UI thread
        view.getLocationInWindow(position);

        clientStream.writeInt(position[0]);
        clientStream.writeInt(position[1]);
        clientStream.flush();

        Bitmap b = performViewCapture(view, true);
        if (b != null) {
            ByteArrayOutputStream arrayOut = new ByteArrayOutputStream(b.getWidth() *
                    b.getHeight() * 2);
            b.compress(Bitmap.CompressFormat.PNG, 100, arrayOut);
            clientStream.writeInt(arrayOut.size());
            arrayOut.writeTo(clientStream);
        }
        clientStream.flush();
    }

    if (view instanceof ViewGroup) {
        ViewGroup group = (ViewGroup) view;
        int count = group.getChildCount();

        for (int i = 0; i < count; i++) {
            captureViewLayer(group.getChildAt(i), clientStream, localVisible);
        }
    }

    if (view.mOverlay != null) {
        ViewGroup overlayContainer = view.getOverlay().mOverlayViewGroup;
        captureViewLayer(overlayContainer, clientStream, localVisible);
    }
}
 
Example 18
Source File: DistributedMapCacheClientService.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private <T> void serialize(final T value, final Serializer<T> serializer, final DataOutputStream dos) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    serializer.serialize(value, baos);
    dos.writeInt(baos.size());
    baos.writeTo(dos);
}
 
Example 19
Source File: SimpleHttpInvokerRequestExecutor.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Set the given serialized remote invocation as request body.
 * <p>The default implementation simply write the serialized invocation to the
 * HttpURLConnection's OutputStream. This can be overridden, for example, to write
 * a specific encoding and potentially set appropriate HTTP request headers.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param con the HttpURLConnection to write the request body to
 * @param baos the ByteArrayOutputStream that contains the serialized
 * RemoteInvocation object
 * @throws IOException if thrown by I/O methods
 * @see java.net.HttpURLConnection#getOutputStream()
 * @see java.net.HttpURLConnection#setRequestProperty
 */
protected void writeRequestBody(
		HttpInvokerClientConfiguration config, HttpURLConnection con, ByteArrayOutputStream baos)
		throws IOException {

	baos.writeTo(con.getOutputStream());
}
 
Example 20
Source File: SimpleHttpInvokerRequestExecutor.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Set the given serialized remote invocation as request body.
 * <p>The default implementation simply write the serialized invocation to the
 * HttpURLConnection's OutputStream. This can be overridden, for example, to write
 * a specific encoding and potentially set appropriate HTTP request headers.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param con the HttpURLConnection to write the request body to
 * @param baos the ByteArrayOutputStream that contains the serialized
 * RemoteInvocation object
 * @throws IOException if thrown by I/O methods
 * @see java.net.HttpURLConnection#getOutputStream()
 * @see java.net.HttpURLConnection#setRequestProperty
 */
protected void writeRequestBody(
		HttpInvokerClientConfiguration config, HttpURLConnection con, ByteArrayOutputStream baos)
		throws IOException {

	baos.writeTo(con.getOutputStream());
}