ByteArrayOutputStream baos = new ByteArrayOutputStream(); MessageBodyWriter bodyWriter = workers.getMessageBodyWriter(bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE); bodyWriter.writeTo(bean, bean.getClass(), bean.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), baos); JsonNode serverState = mapper.readValue(baos.toByteArray(), JsonNode.class); JsonNode patchAsNode = mapper.readValue(readerInterceptorContext.getInputStream(), JsonNode.class); JsonPatch patch = JsonPatch.fromJson(patchAsNode); ByteArrayOutputStream resultAsByteArray = new ByteArrayOutputStream(); mapper.writeValue(resultAsByteArray, result); readerInterceptorContext.setInputStream(new ByteArrayInputStream(resultAsByteArray.toByteArray()));
/** * Safely invokes {@link javax.ws.rs.ext.MessageBodyWriter#isWriteable isWriteable} method on the supplied provider. * * Any exceptions will be logged at finer level. * * @param provider message body writer on which the {@code isWriteable} should be invoked. * @param type the class of instance that is to be written. * @param genericType the type of instance to be written, obtained either * by reflection of a resource method return type or via inspection * of the returned instance. {@link javax.ws.rs.core.GenericEntity} * provides a way to specify this information at runtime. * @param annotations an array of the annotations attached to the message entity instance. * @param mediaType the media type of the HTTP entity. * @return {@code true} if the type is supported, otherwise {@code false}. */ public static boolean isWriteable( final MessageBodyWriter<?> provider, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { try { return provider.isWriteable(type, genericType, annotations, mediaType); } catch (final Exception ex) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, LocalizationMessages.ERROR_MBW_ISWRITABLE(provider.getClass().getName()), ex); } } return false; }
if (!getHttpHeaders().containsKey(HttpHeaders.VARY)) { final String varyHeader = (String)request.getProperties().get(ContainerRequest.VARY_HEADER); if (varyHeader != null) { getHttpHeaders().add(HttpHeaders.VARY, varyHeader); request.getAcceptableMediaTypes()); if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) contentType = MediaType.APPLICATION_OCTET_STREAM_TYPE; getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, contentType); final long size = writer.getSize(entity, entity.getClass(), entityType, annotations, contentType); writer.writeTo(entity, entity.getClass(), entityType, annotations, contentType, getHttpHeaders(), out);
@SuppressWarnings({"unchecked", "rawtypes"}) protected byte[] marshalContent(Object content, MediaType marshalTo) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Class type = content.getClass(); Type genericType = null; Object obj = content; if (content instanceof GenericEntity) { GenericEntity ge = (GenericEntity) content; obj = ge.getEntity(); type = ge.getRawType(); genericType = ge.getType(); } if (genericType == null) genericType = type; MessageBodyWriter writer = providers.getMessageBodyWriter(type, genericType, null, marshalTo); if (writer == null) throw new IllegalStateException(Messages.MESSAGES.unableToFindMessageBodyWriter()); try { writer.writeTo(obj, type, genericType, null, marshalTo, new MultivaluedHashMap<String, Object>(), baos); } catch (Exception e) { throw new RuntimeException(e); } return baos.toByteArray(); }
final Application application = applicationDescription.getApplication(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); if(v.getMediaType().equals(MediaTypes.WADL)) { try { final Marshaller marshaller = wadlContext.getJAXBContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(application, os); cachedWadl = os.toByteArray(); os.close(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not marshal wadl Application.", e); final MessageBodyWriter<Application> messageBodyWriter = providers.getMessageBodyWriter(Application.class, null, new Annotation[0], v.getMediaType()); messageBodyWriter.writeTo(application, Application.class, null, new Annotation[0], v.getMediaType(), null /* headers */, os); cachedWadl = os.toByteArray(); os.close();
for (Map.Entry<String, List<Object>> entry : response.getMetadata().entrySet()) getMetadata().add(entry.getKey(), configuration.toHeaderString(obj)); if (mediaType == null) { mediaType = MediaType.WILDCARD_TYPE; getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD); throw new ProcessingException(Messages.MESSAGES.failedToBufferAbortedResponseNoWriter(mediaType, entityClass.getName())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { writer.writeTo(getEntity(), getEntityClass(), getGenericType(), getAnnotations(), mediaType, getHeaders(), baos); bufferedEntity = baos.toByteArray(); setInputStream(new ByteArrayInputStream(bufferedEntity));
ByteArrayOutputStream bout = new ByteArrayOutputStream(); MediaType mediaType = event.getMediaType(); boolean mediaTypeSet = event instanceof OutboundSseEventImpl ? ((OutboundSseEventImpl) event).isMediaTypeSet() : true; if (mediaType == null || !mediaTypeSet) Object o = response.getOutputHeaders().getFirst("Content-Type"); if (o != null) String s = mt.getParameters().get(SseConstants.SSE_ELEMENT_MEDIA_TYPE); if (s != null) mediaType = MediaType.valueOf(s); MediaType mt = MediaType.valueOf((String) o); String s = mt.getParameters().get(SseConstants.SSE_ELEMENT_MEDIA_TYPE); if (s != null) writer.writeTo(event, event.getClass(), null, new Annotation[]{}, mediaType, null, bout); response.getOutputStream().write(bout.toByteArray()); response.flushBuffer();
|| mediaType == null || !mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) { return new MultivaluedHashMap<String, String>(); ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, out); } catch (WebApplicationException wae) { ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ByteArrayOutputStream bout = new ByteArrayOutputStream(); writer.writeTo(event, event.getClass(), null, new Annotation[] {}, event.getMediaType(), null, bout); response.getOutputStream().write(bout.toByteArray()); response.flushBuffer();
&& MediaType.APPLICATION_JSON_PATCH_JSON_TYPE.isCompatible(requestContext.getMediaType())) ByteArrayOutputStream tmpOutputStream = new ByteArrayOutputStream(); MessageBodyWriter msgBodyWriter = ResteasyProviderFactory.getInstance().getMessageBodyWriter( object.getClass(), object.getClass(), methodInvoker.getMethodAnnotations(), MediaType.APPLICATION_JSON_TYPE); msgBodyWriter.writeTo(object, object.getClass(), object.getClass(), methodInvoker.getMethodAnnotations(), MediaType.APPLICATION_JSON_TYPE, new MultivaluedTreeMap<String, Object>(), tmpOutputStream); ObjectMapper mapper = new ObjectMapper(); JsonNode targetJson = mapper.readValue(tmpOutputStream.toByteArray(), JsonNode.class); JsonPatch patch = JsonPatch.fromJson(mapper.readValue(request.getInputStream(), JsonNode.class)); JsonNode result = patch.apply(targetJson); ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream(); mapper.writeValue(targetOutputStream, result); request.setInputStream(new ByteArrayInputStream(targetOutputStream.toByteArray()));
@SuppressWarnings("unchecked") public static String writeToString(Providers providers, Object object, Class<?> type, Type genericType, MultivaluedMap<String, Object> httpHeaders, MediaType mediaType) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(type, genericType, null, mediaType); if (writer == null) { return null; } writer.writeTo(object, type, genericType, new Annotation[0], mediaType, httpHeaders, os); String contentString = os.toString(getCharset(mediaType)); return contentString; }
if (outboundEvent.getComment() != null) { for (final String comment : outboundEvent.getComment().split("\n")) { entityStream.write(COMMENT_LEAD); entityStream.write(comment.getBytes(charset)); entityStream.write(EOL); final MessageBodyWriter messageBodyWriter = workersProvider.get().getMessageBodyWriter(outboundEvent.getType(), outboundEvent.getGenericType(), annotations, eventMediaType); messageBodyWriter.writeTo( outboundEvent.getData(), outboundEvent.getType(),
final long size = headers.containsKey(HttpHeaders.CONTENT_ENCODING) ? -1 : bw.getSize(entity, entityClass, entityType, EMPTY_ANNOTATIONS, mediaType); listener.onRequestEntitySize(size); bw.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, mediaType, headers, out); out.flush(); } catch (IOException ex) { try { out.close(); } catch (Exception e) { } throw ex; } catch (RuntimeException ex) { try { out.close(); } catch (Exception e) { } throw ex;
/** * * @param out * @throws java.io.IOException */ public void writeRequestEntity(OutputStream out) throws IOException { out = cr.getAdapter().adapt(cr, out); try { bw.writeTo(entity, entity.getClass(), entityType, EMPTY_ANNOTATIONS, mediaType, cr.getMetadata(), out); out.flush(); } finally { out.close(); } } }
@SuppressWarnings(value = "unchecked") protected void writePart(OutputStream entityStream, byte[] boundaryBytes, OutputPart part, MultivaluedMap<String, Object> headers) throws IOException { entityStream.write(boundaryBytes); entityStream.write("\r\n".getBytes()); headers.putAll(part.getHeaders()); headers.putSingle(HttpHeaderNames.CONTENT_TYPE, part.getMediaType()); Object entity = part.getEntity(); Class<?> entityType = part.getType(); Type entityGenericType = part.getGenericType(); MessageBodyWriter writer = workers.getMessageBodyWriter(entityType, entityGenericType, null, part.getMediaType()); LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); OutputStream partStream = new DelegatingOutputStream(entityStream) { @Override public void close() throws IOException { // no close // super.close(); } }; writer.writeTo(entity, entityType, entityGenericType, null, part.getMediaType(), headers, new HeaderFlushedOutputStream(headers, partStream)); entityStream.write("\r\n".getBytes()); } }
@Override public String toString(Book value) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { mbw.writeTo(value, Book.class, Book.class, new Annotation[]{}, MediaType.APPLICATION_XML_TYPE, new MetadataMap<String, Object>(), bos); } catch (IOException ex) { throw new BadRequestException(ex); } return bos.toString(); } }
if (this.writerProvider == null) { this.writerProvider = injectedProviders.getMessageBodyWriter((Class<Object>)theType, theType, annotations, entityStream.write("[".getBytes()); //$NON-NLS-1$ int i = 0; for (Object o : t) { this.writerProvider.writeTo(o, theType, theType, entityStream); if ((++i) != t.length) entityStream.write(",".getBytes()); //$NON-NLS-1$ entityStream.write("]".getBytes()); //$NON-NLS-1$
private void debugWrite(Object root, MediaType format) { MessageBodyWriter messageBodyWriter = workers.getMessageBodyWriter(root.getClass(), root.getClass(), new Annotation[]{}, format); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // use the MBW to serialize myBean into baos messageBodyWriter.writeTo(root, root.getClass(), root.getClass(), new Annotation[]{}, format, new MultivaluedHashMap<String, Object>(), baos); } catch (Throwable e) { logger.error(String.format("could not serialize %s to format %s", root, format), e); throw propagate(e); } logger.info("{}", baos); }
@Override public void writeTo(MultipartUploadRepresentation o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Class<BucketObjectUpdateRepresentation> writerType = BucketObjectUpdateRepresentation.class; Type writerGenericType = writerType; Annotation[] writerAnnotations = new Annotation[0]; MessageBodyWriter<BucketObjectUpdateRepresentation> writer = providers.getMessageBodyWriter(writerType, writerGenericType, writerAnnotations, MediaType.WILDCARD_TYPE); String boundary = UUID.randomUUID().toString(); httpHeaders.putSingle(BlazeStorageHeaders.QUIET, Boolean.toString(o.isQuiet())); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; boundary=" + boundary); byte[] boundaryBytes = ("--" + boundary).getBytes(); for (Map.Entry<String, BucketObjectUpdateRepresentation> entry : o.getUploads().entrySet()) { BucketObjectUpdateRepresentation value = entry.getValue(); MediaType writerMediaType = MediaType.valueOf(value.getContentType()); MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>(); headers.add(BlazeStorageHeaders.MULTIPART_KEY, entry.getKey()); entityStream.write(boundaryBytes); entityStream.write("\r\n".getBytes()); writer.writeTo(entry.getValue(), writerType, writerGenericType, writerAnnotations, writerMediaType, headers, new HeaderFlushedOutputStream(headers, entityStream)); entityStream.write("\r\n".getBytes()); } entityStream.write(boundaryBytes); entityStream.write("--".getBytes()); }
@Override @SuppressWarnings({"unchecked"}) public void writeBody(GenericContainerResponse response, MessageBodyWriter entityWriter) throws IOException { if (servletResponse.isCommitted()) { return; } Object entity = response.getEntity(); if (entity != null) { OutputStream out = servletResponse.getOutputStream(); entityWriter.writeTo(entity, entity.getClass(), response.getEntityType(), null, response.getContentType(), response.getHttpHeaders(), out); out.flush(); } }