|
| 1 | +package com.fasterxml.jackson.dataformat.protobuf.schema; |
| 2 | + |
| 3 | + |
| 4 | +import com.fasterxml.jackson.dataformat.protobuf.ProtobufMapper; |
| 5 | + |
| 6 | +import java.io.ByteArrayInputStream; |
| 7 | +import java.io.File; |
| 8 | +import java.io.FileInputStream; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.InputStream; |
| 11 | +import java.net.URL; |
| 12 | + |
| 13 | +/** |
| 14 | + * Class used for loading protobuf descriptors (from .desc files |
| 15 | + * or equivalent sources), to construct FileDescriptorSet. |
| 16 | + */ |
| 17 | +public class DescriptorLoader |
| 18 | +{ |
| 19 | + private final String DESCRIPTOR_PROTO = "/descriptor.proto"; |
| 20 | + private ProtobufMapper descriptorMapper; |
| 21 | + private ProtobufSchema descriptorFileSchema; |
| 22 | + |
| 23 | + /** |
| 24 | + * Standard loader instance that is usually used for loading descriptor file. |
| 25 | + */ |
| 26 | + public final static DescriptorLoader std = new DescriptorLoader(); |
| 27 | + |
| 28 | + public DescriptorLoader() {} |
| 29 | + |
| 30 | + |
| 31 | + /** |
| 32 | + * Public API |
| 33 | + */ |
| 34 | + |
| 35 | + public FileDescriptorSet load(URL url) throws IOException |
| 36 | + { |
| 37 | + return _loadFileDescriptorSet(url.openStream()); |
| 38 | + } |
| 39 | + |
| 40 | + public FileDescriptorSet load(File f) throws IOException |
| 41 | + { |
| 42 | + return _loadFileDescriptorSet(new FileInputStream(f)); |
| 43 | + } |
| 44 | + |
| 45 | + public FileDescriptorSet load(InputStream in) throws IOException |
| 46 | + { |
| 47 | + return _loadFileDescriptorSet(in); |
| 48 | + } |
| 49 | + |
| 50 | + public FileDescriptorSet fromBytes(byte[] descriptorBytes) throws IOException |
| 51 | + { |
| 52 | + return _loadFileDescriptorSet(new ByteArrayInputStream(descriptorBytes)); |
| 53 | + } |
| 54 | + |
| 55 | + protected FileDescriptorSet _loadFileDescriptorSet(InputStream in) throws IOException |
| 56 | + { |
| 57 | + try { |
| 58 | + if (descriptorMapper == null) { |
| 59 | + createDescriptorMapper(); |
| 60 | + } |
| 61 | + return descriptorMapper.readerFor(FileDescriptorSet.class) |
| 62 | + .with(descriptorFileSchema) |
| 63 | + .readValue(in); |
| 64 | + } |
| 65 | + finally { |
| 66 | + try { |
| 67 | + in.close(); |
| 68 | + } |
| 69 | + catch (IOException e) { |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + private void createDescriptorMapper() throws IOException |
| 75 | + { |
| 76 | + // read Descriptor Proto |
| 77 | + descriptorMapper = new ProtobufMapper(); |
| 78 | + InputStream in = getClass().getResourceAsStream(DESCRIPTOR_PROTO); |
| 79 | + descriptorFileSchema = ProtobufSchemaLoader.std.load(in, "FileDescriptorSet"); |
| 80 | + in.close(); |
| 81 | + } |
| 82 | +} |
0 commit comments