| 1 |
package com.fasterxml.jackson.module.jaxb.ser; |
| 2 |
|
| 3 |
import java.io.ByteArrayOutputStream; |
| 4 |
import java.io.IOException; |
| 5 |
import java.io.InputStream; |
| 6 |
import java.lang.reflect.Type; |
| 7 |
|
| 8 |
import javax.activation.DataHandler; |
| 9 |
|
| 10 |
import com.fasterxml.jackson.core.*; |
| 11 |
import com.fasterxml.jackson.databind.JavaType; |
| 12 |
import com.fasterxml.jackson.databind.JsonMappingException; |
| 13 |
import com.fasterxml.jackson.databind.JsonNode; |
| 14 |
import com.fasterxml.jackson.databind.SerializerProvider; |
| 15 |
import com.fasterxml.jackson.databind.ser.std.StdSerializer; |
| 16 |
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor; |
| 17 |
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatTypes; |
| 18 |
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; |
| 19 |
import com.fasterxml.jackson.databind.node.ObjectNode; |
| 20 |
|
| 21 |
public class DataHandlerJsonSerializer extends StdSerializer<DataHandler> |
| 22 |
{ |
| 23 |
private static final long serialVersionUID = 1L; |
| 24 |
|
| 25 |
public DataHandlerJsonSerializer() { super(DataHandler.class); } |
| 26 |
|
| 27 |
@Override |
| 28 |
public void serialize(DataHandler value, JsonGenerator jgen, SerializerProvider provider) |
| 29 |
throws IOException, JsonProcessingException |
| 30 |
{ |
| 31 |
final ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 32 |
/* for copy-through, a small buffer should suffice: ideally |
| 33 |
* we might want to reuse a generic byte buffer, but for now |
| 34 |
* there's no serializer context to hold them. |
| 35 |
* |
| 36 |
* Also: it'd be nice not to have buffer all data, but use a |
| 37 |
* streaming output. But currently JsonGenerator won't allow |
| 38 |
* that. |
| 39 |
*/ |
| 40 |
byte[] buffer = new byte[1024 * 4]; |
| 41 |
InputStream in = value.getInputStream(); |
| 42 |
int len = in.read(buffer); |
| 43 |
while (len > 0) { |
| 44 |
out.write(buffer, 0, len); |
| 45 |
len = in.read(buffer); |
| 46 |
} |
| 47 |
in.close(); |
| 48 |
jgen.writeBinary(out.toByteArray()); |
| 49 |
} |
| 50 |
|
| 51 |
@Override |
| 52 |
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) |
| 53 |
throws JsonMappingException |
| 54 |
{ |
| 55 |
if (visitor != null) { |
| 56 |
JsonArrayFormatVisitor v2 = visitor.expectArrayFormat(typeHint); |
| 57 |
if (v2 != null) { |
| 58 |
v2.itemsFormat(JsonFormatTypes.STRING); |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
@Override |
| 64 |
public JsonNode getSchema(SerializerProvider provider, Type typeHint) |
| 65 |
{ |
| 66 |
ObjectNode o = createSchemaNode("array", true); |
| 67 |
ObjectNode itemSchema = createSchemaNode("string"); //binary values written as strings? |
| 68 |
o.set("items", itemSchema); |
| 69 |
return o; |
| 70 |
} |
| 71 |
} |