This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 996c6d3d689df00a2f9f528c03e66b12ab0ed6e4 Author: jsorel <[email protected]> AuthorDate: Thu Nov 12 10:06:29 2026 +0100 feat(UBJSON): add UBJSON encoding --- .../main/module-info.java | 1 + .../main/org/apache/sis/storage/ubjson/UBJson.java | 51 +++ .../apache/sis/storage/ubjson/UBJsonFactory.java | 187 +++++++++ .../sis/storage/ubjson/UBJsonFactoryBuilder.java | 40 ++ .../apache/sis/storage/ubjson/UBJsonGenerator.java | 437 +++++++++++++++++++++ .../apache/sis/storage/ubjson/UBJsonMapper.java | 72 ++++ .../apache/sis/storage/ubjson/UBJsonParser.java | 139 +++++++ .../sis/storage/ubjson/UBJsonWriteContext.java | 157 ++++++++ .../org/apache/sis/storage/ubjson/UBJSONTest.java | 78 ++++ 9 files changed, 1162 insertions(+) diff --git a/incubator/src/org.apache.sis.storage.json/main/module-info.java b/incubator/src/org.apache.sis.storage.json/main/module-info.java index c0bc317b38..7f0f15692c 100644 --- a/incubator/src/org.apache.sis.storage.json/main/module-info.java +++ b/incubator/src/org.apache.sis.storage.json/main/module-info.java @@ -45,4 +45,5 @@ module org.apache.sis.storage.json { exports org.apache.sis.storage.coveragejson.binding; exports org.apache.sis.storage.geopose; exports org.apache.sis.storage.geopose.binding; + exports org.apache.sis.storage.ubjson; } diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJson.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJson.java new file mode 100644 index 0000000000..2f4942c267 --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJson.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +/** + * Constants from UBJSON specification. + * + * @author Johann Sorel (Geomatys) + * @see https://ubjson.org/ + */ +final class UBJson { + + public static final byte NULL = 'Z'; + public static final byte NO_OP = 'N'; + public static final byte TRUE = 'T'; + public static final byte FALSE = 'F'; + public static final byte INT8 = 'i'; + public static final byte UINT8 = 'U'; + public static final byte INT16 = 'I'; + public static final byte INT32 = 'l'; + public static final byte INT64 = 'L'; + public static final byte FLOAT32 = 'd'; + public static final byte FLOAT64 = 'D'; + public static final byte HIGH_PRECISION_NUMBER = 'H'; + public static final byte CHAR = 'C'; + public static final byte STRING = 'S'; + + public static final byte ARRAY_START = '['; + public static final byte ARRAY_END = ']'; + public static final byte OBJECT_START = '{'; + public static final byte OBJECT_END = '}'; + + public static final byte OPTIMIZED_TYPE = '$'; + public static final byte OPTIMIZED_SIZE = '#'; + + private UBJson(){} +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactory.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactory.java new file mode 100644 index 0000000000..809309d52b --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactory.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.FormatSchema; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.core.format.InputAccessor; +import com.fasterxml.jackson.core.format.MatchStrength; +import com.fasterxml.jackson.core.io.IOContext; +import com.fasterxml.jackson.core.json.PackageVersion; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.TreeTraversingParser; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import org.apache.sis.storage.DataStoreException; + +/** + * Jackson factory implementation for UBJSON. + * + * @author Johann Sorel (Geomatys) + */ +public final class UBJsonFactory extends JsonFactory { + + public final static String FORMAT_NAME_UBJSON = "ubjson"; + + public UBJsonFactory() { + super(); + } + + public UBJsonFactory(ObjectCodec codec) { + super(codec); + } + + protected UBJsonFactory(UBJsonFactory src, ObjectCodec oc) { + super(src, oc); + } + + protected UBJsonFactory(UBJsonFactoryBuilder b) { + super(b, false); + } + + @Override + public UBJsonFactoryBuilder rebuild() { + return new UBJsonFactoryBuilder(this); + } + + /** + * Main factory method to use for constructing {@link UBJsonFactory} instances with different configuration. + */ + public static UBJsonFactoryBuilder builder() { + return new UBJsonFactoryBuilder(); + } + + @Override + public UBJsonFactory copy() { + _checkInvalidCopy(UBJsonFactory.class); + return new UBJsonFactory(this, null); + } + + // ********************************************************** + // Versioned + // ********************************************************** + + @Override + public Version version() { + return PackageVersion.VERSION; + } + + // ********************************************************* + // Format detection functionality + // ********************************************************* + + @Override + public String getFormatName() { + return FORMAT_NAME_UBJSON; + } + + /** + * Sub-classes need to override this method + */ + @Override + public MatchStrength hasFormat(InputAccessor acc) throws IOException { + return MatchStrength.INCONCLUSIVE; + } + + // ********************************************************* + // Capability introspection + // ********************************************************* + + @Override + public boolean requiresPropertyOrdering() { + return false; + } + + @Override + public boolean canHandleBinaryNatively() { + return true; + } + + @Override + public boolean canUseCharArrays() { + return false; + } + + @Override + public boolean canUseSchema(FormatSchema schema) { + return false; + } + + // ********************************************************************* + // Overridden internal factory methods, parser + // ********************************************************************* + + @Override + public JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException { + return new TreeTraversingParser(parse(ctxt, in)); + } + + @Override + public JsonParser _createParser(Reader r, IOContext ctxt) throws IOException { + throw new UnsupportedOperationException("Can not create UBJson binary parser from text input"); + } + + @Override + public JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException { + return _createParser(new ByteArrayInputStream(data, offset, len), ctxt); + } + + @Override + protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable) throws IOException { + throw new UnsupportedOperationException("Can not create UBJson binary parser from text input"); + } + + // ********************************************************************* + // Overridden internal factory methods, generator + // ********************************************************************* + + @Override + protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException { + throw new UnsupportedOperationException("Can not create UBJson binary generator for text output"); + } + + @Override + protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { + try { + return new UBJsonGenerator(ctxt, _generatorFeatures, _objectCodec, out); + } catch (IllegalArgumentException | DataStoreException ex) { + throw new IOException(ex); + } + } + + // ********************************************************************* + // Low-level methods for reading/writing UBJSON + // ********************************************************************* + + private JsonNode parse(IOContext ctxt, InputStream in) throws IOException { + final UBJsonParser parser = new UBJsonParser(); + try { + return parser.parse(in); + } catch (IllegalArgumentException | DataStoreException ex) { + throw new IOException(ex); + } + } + +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactoryBuilder.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactoryBuilder.java new file mode 100644 index 0000000000..a0e3890dcd --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonFactoryBuilder.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.TSFBuilder; + +/** + * Jackson factory builder implementation for UBJSON. + * + * @author Johann Sorel (Geomatys) + */ +public final class UBJsonFactoryBuilder extends TSFBuilder<UBJsonFactory, UBJsonFactoryBuilder> { + + public UBJsonFactoryBuilder() { + super(); + } + + public UBJsonFactoryBuilder(UBJsonFactory base) { + super(base); + } + + @Override + public UBJsonFactory build() { + return new UBJsonFactory(this); + } +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonGenerator.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonGenerator.java new file mode 100644 index 0000000000..ce961762e3 --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonGenerator.java @@ -0,0 +1,437 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.*; +import com.fasterxml.jackson.core.base.GeneratorBase; +import com.fasterxml.jackson.core.io.IOContext; +import com.fasterxml.jackson.core.json.PackageVersion; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import org.apache.sis.io.stream.ChannelDataOutput; +import org.apache.sis.storage.DataStoreException; +import org.apache.sis.storage.StorageConnector; + +/** + * Jackson generator implementation for UBJSON. + * + * @author Johann Sorel (Geomatys) + */ +final class UBJsonGenerator extends GeneratorBase { + + /* + /********************************************************************** + /* Configuration + /********************************************************************** + */ + /** + * @since 2.16 + */ + protected final StreamWriteConstraints _streamWriteConstraints; + + /** + * Underlying {@link Writer} used for output. + */ + protected final ChannelDataOutput _out; + + /* + /********************************************************************** + /* Output state + /********************************************************************** + */ + /** + * Current context, in form we can use it (GeneratorBase has untyped reference; left as null) + */ + protected UBJsonWriteContext _streamWriteContext; + + protected final StringBuilder _basePath = new StringBuilder(50); + + /* + /********************************************************************** + /* Life-cycle + /********************************************************************** + */ + public UBJsonGenerator(IOContext ioCtxt, int stdFeatures, ObjectCodec codec, OutputStream out) throws IllegalArgumentException, DataStoreException { + super(stdFeatures, codec, ioCtxt); + _streamWriteConstraints = ioCtxt.streamWriteConstraints(); + _streamWriteContext = UBJsonWriteContext.createRootContext(); + _out = new StorageConnector(out).getStorageAs(ChannelDataOutput.class); + } + + @Override + public StreamWriteConstraints streamWriteConstraints() { + return _streamWriteConstraints; + } + + /* + /********************************************************************** + /* Versioned + /********************************************************************** + */ + @Override + public Version version() { + return PackageVersion.VERSION; + } + + /* + /********************************************************************** + /* Overridden methods: low-level I/O + /********************************************************************** + */ + @Override + public void close() throws IOException { + if (!isClosed()) { + if (_out != null) { + if (_ioContext.isResourceManaged() || isEnabled(StreamWriteFeature.AUTO_CLOSE_TARGET)) { + _out.flush(); + _out.channel.close(); + } else if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { + // If we can't close it, we should at least flush + _out.flush(); + } + } + // Internal buffer(s) generator has can now be released as well + _releaseBuffers(); + super.close(); + } + } + + @Override + public void flush() throws IOException { + if (_out != null) { + if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) { + _out.flush(); + } + } + } + + /* + /********************************************************************** + /* Implementations for methods from base class + /********************************************************************** + */ + @Override + protected void _releaseBuffers() { + } + + /* + /********************************************************************** + /* Overridden output state handling methods + /********************************************************************** + */ + @Override + public Object currentValue() { + return _streamWriteContext.getCurrentValue(); + } + + @Override + public void assignCurrentValue(Object v) { + _streamWriteContext.setCurrentValue(v); + } + + /* + /********************************************************************** + /* Overrides: capability introspection methods + /********************************************************************** + */ + @Override + public boolean canWriteObjectId() { + return false; + } + + @Override + public boolean canWriteTypeId() { + return false; + } + + /* + /********************************************************************** + /* Overridden methods; writing property names + /********************************************************************** + */ + @Override + public void writeFieldName(String name) throws IOException { + if (!_streamWriteContext.writeName(name)) { + _reportError("Cannot write a property name, expecting a value"); + } + _writeStringNoMarker(name); + } + + /* + /********************************************************************** + /* Public API: structural output + /********************************************************************** + */ + @Override + public void writeStartArray() throws IOException { + writeStartArray(null); + } + + @Override + public void writeStartArray(Object currValue) throws IOException { + // arrays are always inline, force writing the current key + // NOTE: if this ever changes, we need to add empty array handling in writeEndArray + _verifyValueWrite("start an array"); + _streamWriteContext = _streamWriteContext.createChildArrayContext(currValue, + _basePath.length()); + streamWriteConstraints().validateNestingDepth(_streamWriteContext.getNestingDepth()); + _out.writeByte(UBJson.ARRAY_START); + } + + @Override + public void writeEndArray() throws IOException { + if (!_streamWriteContext.inArray()) { + _reportError("Current context not an Array but " + _streamWriteContext.typeDesc()); + } + _out.writeByte(UBJson.ARRAY_END); + _streamWriteContext = _streamWriteContext.getParent(); + } + + @Override + public void writeStartObject() throws IOException { + writeStartObject(null); + } + + @Override + public void writeStartObject(Object forValue) throws IOException { + // objects aren't always materialized right now + _verifyValueWrite("start an object"); + _streamWriteContext = _streamWriteContext.createChildObjectContext(forValue, _basePath.length()); + streamWriteConstraints().validateNestingDepth(_streamWriteContext.getNestingDepth()); + _out.writeByte(UBJson.OBJECT_START); + } + + @Override + public void writeEndObject() throws IOException { + if (!_streamWriteContext.inObject()) { + _reportError("Current context not an Object but " + _streamWriteContext.typeDesc()); + } + _out.writeByte(UBJson.OBJECT_END); + _streamWriteContext = _streamWriteContext.getParent(); + } + + /* + /********************************************************************** + /* Output method implementations, textual + /********************************************************************** + */ + @Override + public void writeString(String text) throws IOException { + if (text == null) { + writeNull(); + } else { + final byte[] utf8Buffer = text.getBytes(StandardCharsets.UTF_8); + writeUTF8String(utf8Buffer, 0, utf8Buffer.length); + } + } + + @Override + public void writeString(char[] text, int offset, int len) throws IOException { + writeString(new String(text, offset, len)); + } + + @Override + public void writeRawUTF8String(byte[] text, int offset, int len) throws IOException { + _verifyValueWrite("write String value"); + _out.writeByte(UBJson.STRING); + _writeInt(len, false); + _out.write(text, offset, len); + + } + + @Override + public void writeUTF8String(byte[] text, int offset, int len) throws IOException { + writeRawUTF8String(text, offset, len); + } + + /* + /********************************************************************** + /* Output method implementations, unprocessed ("raw") + /********************************************************************** + */ + @Override + public void writeRaw(String text) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeRaw(String text, int offset, int len) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeRaw(char[] text, int offset, int len) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void writeRaw(char c) throws IOException { + throw new UnsupportedOperationException(); + } + + /* + /********************************************************************** + /* Output method implementations, base64-encoded binary + /********************************************************************** + */ + @Override + public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) + throws IOException { + if (data == null) { + writeNull(); + } else { + //create a compact ubjson byte array + _out.writeByte(UBJson.ARRAY_START); + _out.writeByte(UBJson.OPTIMIZED_TYPE); + _out.writeByte(UBJson.UINT8); + _out.writeByte(UBJson.OPTIMIZED_SIZE); + _writeInt(len, false); + _out.write(data, offset, len); + } + } + + /* + /********************************************************************** + /* Output method implementations, scalars + /********************************************************************** + */ + @Override + public void writeBoolean(boolean state) throws IOException { + _verifyValueWrite("write boolean value"); + _out.writeByte(state ? UBJson.TRUE : UBJson.FALSE); + } + + @Override + public void writeNumber(short v) throws IOException { + writeNumber((int) v); + _out.writeByte(UBJson.INT16); + _out.writeShort(v); + } + + @Override + public void writeNumber(int i) throws IOException { + _verifyValueWrite("write number"); + _out.writeByte(UBJson.INT32); + _out.writeInt(i); + } + + @Override + public void writeNumber(long l) throws IOException { + _verifyValueWrite("write number"); + _out.writeByte(UBJson.INT64); + _out.writeLong(l); + } + + @Override + public void writeNumber(BigInteger dec) throws IOException { + if (dec == null) { + writeNull(); + return; + } + _verifyValueWrite("write number"); + String str = dec.toString(); + _out.writeByte(UBJson.HIGH_PRECISION_NUMBER); + _writeStringNoMarker(str); + } + + @Override + public void writeNumber(double d) throws IOException { + _verifyValueWrite("write number"); + _out.writeByte(UBJson.FLOAT64); + _out.writeDouble(d); + } + + @Override + public void writeNumber(float f) throws IOException { + _verifyValueWrite("write number"); + _out.writeByte(UBJson.FLOAT32); + _out.writeFloat(f); + } + + @Override + public void writeNumber(BigDecimal dec) throws IOException { + if (dec == null) { + writeNull(); + return; + } + _verifyValueWrite("write number"); + String str = isEnabled(StreamWriteFeature.WRITE_BIGDECIMAL_AS_PLAIN) ? dec.toPlainString() : dec.toString(); + _out.writeByte(UBJson.HIGH_PRECISION_NUMBER); + _writeStringNoMarker(str); + } + + @Override + public void writeNumber(String encodedValue) throws IOException { + if (encodedValue == null) { + writeNull(); + return; + } + _verifyValueWrite("write number"); + throw new UnsupportedOperationException(); + } + + @Override + public void writeNull() throws IOException { + _verifyValueWrite("write null value"); + _out.writeByte(UBJson.NULL); + } + + /* + /********************************************************************** + /* Implementations for methods from base class + /********************************************************************** + */ + @Override + protected void _verifyValueWrite(String typeMsg) throws IOException { + // check that name/value cadence works + if (!_streamWriteContext.writeValue()) { + _reportError("Cannot " + typeMsg + ", expecting a property name"); + } + } + + //internals + private void _writeStringNoMarker(String txt) throws IOException { + final byte[] bytes = txt.getBytes(StandardCharsets.UTF_8); + final int length = bytes.length; + _writeInt(length, false); + _out.write(bytes); + } + + private void _writeInt(long value, boolean allowUnsigned8) throws IOException { + if (allowUnsigned8 && value >= 0 && value <= 255) { + _out.writeByte(UBJson.UINT8); + _out.writeByte((int) value); + } else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + _out.writeByte(UBJson.INT8); + _out.writeByte((int) value); + } else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) { + _out.writeByte(UBJson.INT16); + _out.writeShort((int) value); + } else if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) { + _out.writeByte(UBJson.INT32); + _out.writeInt((int) value); + } else if (value >= Long.MIN_VALUE && value <= Long.MAX_VALUE) { + _out.writeByte(UBJson.INT64); + _out.writeLong(value); + } + } + +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonMapper.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonMapper.java new file mode 100644 index 0000000000..d324c8e7c6 --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonMapper.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.Version; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.cfg.*; + +/** + * Jackson mapper implementation for UBJSON. + * + * @author Johann Sorel (Geomatys) + */ +public final class UBJsonMapper extends ObjectMapper { + + public static class Builder extends MapperBuilder<UBJsonMapper, Builder> { + + Builder(UBJsonMapper mapper) { + super(mapper); + } + } + + public UBJsonMapper() { + this(new UBJsonFactory()); + } + + public UBJsonMapper(UBJsonFactory f) { + super(f); + } + + public static Builder builder() { + return new Builder(new UBJsonMapper()); + } + + public static Builder builder(UBJsonFactory streamFactory) { + return new Builder(new UBJsonMapper(streamFactory)); + } + + @Override + public UBJsonMapper copy() { + _checkInvalidCopy(UBJsonMapper.class); + return new UBJsonMapper(tokenStreamFactory().copy()); + } + + // ********************************************************************* + // Basic accessor overrides + // ********************************************************************* + + @Override + public Version version() { + return PackageVersion.VERSION; + } + + @Override + public UBJsonFactory tokenStreamFactory() { + return (UBJsonFactory) _jsonFactory; + } +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonParser.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonParser.java new file mode 100644 index 0000000000..e82c344da9 --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonParser.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import org.apache.sis.io.stream.ChannelDataInput; +import org.apache.sis.storage.DataStoreException; +import org.apache.sis.storage.StorageConnector; + +/** + * UBJSON parser. + * + * @author Johann Sorel (Geomatys) + */ +final class UBJsonParser { + + private static final JsonNodeFactory NF = JsonNodeFactory.instance; + + public JsonNode parse(InputStream stream) throws IllegalArgumentException, DataStoreException, IOException { + final ChannelDataInput di = new StorageConnector(stream).getStorageAs(ChannelDataInput.class); + final byte marker = di.readByte(); + return switch (marker) { + case UBJson.OBJECT_START -> parseObject(di); + case UBJson.ARRAY_START -> parseArray(di); + default -> parseValue(marker, di); + }; + } + + private static ObjectNode parseObject(ChannelDataInput in) throws IOException { + final ObjectNode node = NF.objectNode(); + byte marker; + while ( (marker = in.readByte()) != UBJson.OBJECT_END) { + final String name = readStringNoMarker(marker, in); + final JsonNode value = parseValue(in.readByte(), in); + node.set(name, value); + } + return node; + } + + private static JsonNode parseArray(ChannelDataInput in) throws IOException { + byte marker = in.readByte(); + // check for optimized cases + // https://ubjson.org/type-reference/container-types/#optimized-format + if (marker == UBJson.OPTIMIZED_TYPE) { + marker = in.readByte(); + final byte type = marker; + marker = in.readByte(); + if (marker != UBJson.OPTIMIZED_SIZE) throw new IOException("Optimized size marker not found"); + marker = in.readByte(); + final int size = parseValue(marker, in).asInt(); + if (type == UBJson.UINT8 || type == UBJson.INT8) { + //use a compact form + return NF.binaryNode(in.readBytes(size)); + } else { + final ArrayNode node = NF.arrayNode(size); + for (int i = 0; i < size; i++) { + node.add(parseValue(type, in)); + } + return node; + } + + } else if (marker == UBJson.OPTIMIZED_SIZE) { + //array of fixed size but undefined type + marker = in.readByte(); + final int size = parseValue(marker, in).asInt(); + final ArrayNode node = NF.arrayNode(size); + for (int i = 0; i < size; i++) { + marker = in.readByte(); + node.add(parseValue(marker, in)); + } + return node; + } else { + //normal array or undefined size and type + final ArrayNode node = NF.arrayNode(); + do { + node.add(parseValue(marker, in)); + marker = in.readByte(); + } while (marker != UBJson.ARRAY_END); + return node; + } + } + + private static JsonNode parseValue(byte marker, ChannelDataInput in) throws IOException { + switch (marker) { + case UBJson.NO_OP : //should not happen + case UBJson.NULL : return NF.nullNode(); + case UBJson.TRUE : return NF.booleanNode(true); + case UBJson.FALSE : return NF.booleanNode(false); + case UBJson.UINT8 : return NF.numberNode(in.readUnsignedByte()); + case UBJson.INT8 : return NF.numberNode(in.readByte()); + case UBJson.INT16 : return NF.numberNode(in.readShort()); + case UBJson.INT32 : return NF.numberNode(in.readInt()); + case UBJson.INT64 : return NF.numberNode(in.readLong()); + case UBJson.FLOAT32 : return NF.numberNode(in.readFloat()); + case UBJson.FLOAT64 : return NF.numberNode(in.readDouble()); + case UBJson.CHAR : return NF.textNode(""+((char)in.readUnsignedByte())); + case UBJson.HIGH_PRECISION_NUMBER : return NF.numberNode(new BigDecimal(readStringNoMarker(in.readByte(), in))); + case UBJson.ARRAY_START : return parseArray(in); + case UBJson.OBJECT_START : return parseObject(in); + case UBJson.STRING : return NF.textNode(readStringNoMarker(in.readByte(), in)); + default: throw new IOException("Unexpected marker " + marker); + } + } + + private static String readStringNoMarker(int marker, ChannelDataInput in) throws IOException { + final long size; + switch (marker) { + case UBJson.INT8 : size = in.readByte(); break; + case UBJson.INT16 : size = in.readShort(); break; + case UBJson.INT32 : size = in.readInt(); break; + case UBJson.INT64 : size = in.readLong(); break; + default: throw new IOException("Unexpected size marker"); + } + final byte[] datas = in.readBytes(Math.toIntExact(size)); + return new String(datas, StandardCharsets.UTF_8); + } + +} diff --git a/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonWriteContext.java b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonWriteContext.java new file mode 100644 index 0000000000..c06bae5e9a --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/main/org/apache/sis/storage/ubjson/UBJsonWriteContext.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.JsonStreamContext; + +final class UBJsonWriteContext extends JsonStreamContext { + + /** + * Parent context for this context; null for root context. + */ + protected final UBJsonWriteContext _parent; + + // ********************************************************************* + // Simple instance reuse slots; speed up things a bit + // ********************************************************************* + protected UBJsonWriteContext _child = null; + + // ********************************************************************* + // Location/state information (minus source reference) + // ********************************************************************* + + /** + * Value that is being serialized and caused this context to be created; typically a POJO or container type. + */ + protected Object _currentValue; + + /** + * Marker used to indicate that we just received a name, and now expect a value + */ + protected boolean _gotName; + + /** + * Name of the field of which value is to be parsed; only used for OBJECT contexts + */ + protected String _currentName; + + protected int _basePathLength; + + boolean _inline; + + // ********************************************************************* + // Life-cycle + // ********************************************************************* + + UBJsonWriteContext(int type, UBJsonWriteContext parent, + Object currValue, int basePathLength) { + super(); + _type = type; + _parent = parent; + _nestingDepth = parent == null ? 0 : parent._nestingDepth + 1; + _basePathLength = basePathLength; + _index = -1; + _currentValue = currValue; + _inline = (type == TYPE_ARRAY) || (parent != null && parent._inline); + } + + private void reset(int type, Object currValue, int basePathLength) { + _type = type; + _basePathLength = basePathLength; + _currentValue = null; + _index = -1; + _currentValue = currValue; + // 09-Apr-2021, tatu: [dataformats-text#260]: must reset this flag as well + _inline = (type == TYPE_ARRAY) || (_parent != null && _parent._inline); + } + + static UBJsonWriteContext createRootContext() { + return new UBJsonWriteContext(TYPE_ROOT, null, null, 0); + } + + public UBJsonWriteContext createChildArrayContext(Object currValue, int basePathLength) { + UBJsonWriteContext ctxt = _child; + if (ctxt == null) { + _child = ctxt = new UBJsonWriteContext(TYPE_ARRAY, this, currValue, basePathLength); + return ctxt; + } + ctxt.reset(TYPE_ARRAY, currValue, basePathLength); + return ctxt; + } + + public UBJsonWriteContext createChildObjectContext(Object currValue, int basePathLength) { + UBJsonWriteContext ctxt = _child; + if (ctxt == null) { + _child = ctxt = new UBJsonWriteContext(TYPE_OBJECT, this, currValue, basePathLength); + return ctxt; + } + ctxt.reset(TYPE_OBJECT, currValue, basePathLength); + return ctxt; + } + + // ********************************************************************* + // State changes + // ********************************************************************* + + public boolean writeName(String name) { + if (_gotName) { + return false; + } + _gotName = true; + _currentName = name; + return true; + } + + public boolean writeValue() { + // Most likely, object: + if (_type == TYPE_OBJECT) { + if (!_gotName) { + return false; + } + _gotName = false; + } + // Array fine, and must allow root context for Object values too so... + ++_index; + return true; + } + + + // ********************************************************************* + // Simple accessors, mutators + // ********************************************************************* + + @Override + public final UBJsonWriteContext getParent() { + return _parent; + } + + @Override + public String getCurrentName() { + return _currentName; + } + + @Override + public Object getCurrentValue() { + return _currentValue; + } + + @Override + public void setCurrentValue(Object v) { + _currentValue = v; + } + +} diff --git a/incubator/src/org.apache.sis.storage.json/test/org/apache/sis/storage/ubjson/UBJSONTest.java b/incubator/src/org.apache.sis.storage.json/test/org/apache/sis/storage/ubjson/UBJSONTest.java new file mode 100644 index 0000000000..7c54e974ea --- /dev/null +++ b/incubator/src/org.apache.sis.storage.json/test/org/apache/sis/storage/ubjson/UBJSONTest.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on anz "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.storage.ubjson; + +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +// Test dependencies +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +/** + * + * @author Johann Sorel (Geomatys) + */ +public class UBJSONTest { + + @Test + public void testWriteRead() throws JsonProcessingException, IOException { + + final Map<String,Object> submap = new LinkedHashMap<>(); + submap.put("attN", 789); + + final Map<String,Object> map = new LinkedHashMap<>(); + map.put("att0", null); + map.put("att1", true); + map.put("att2", 123456); + map.put("att3", "some test"); + map.put("att4", List.of(1,2,3)); + map.put("att5", submap); + + byte[] bytes = new UBJsonMapper().writeValueAsBytes(map); + assertArrayEquals(new byte[]{ + UBJson.OBJECT_START, + UBJson.INT8, 4, 97, 116, 116, 48, //att0 + UBJson.NULL, //null + UBJson.INT8, 4, 97, 116, 116, 49, //att1 + UBJson.TRUE, //true + UBJson.INT8, 4, 97, 116, 116, 50, //att2 + UBJson.INT32, 0, 1, -30, 64, //123456 + UBJson.INT8, 4, 97, 116, 116, 51, //att3 + UBJson.STRING, UBJson.INT8, 9, 115, 111, 109, 101, 32, 116, 101, 115, 116, //some text + UBJson.INT8, 4, 97, 116, 116, 52, //att4 + UBJson.ARRAY_START, + UBJson.INT32, 0, 0, 0, 1, //1 + UBJson.INT32, 0, 0, 0, 2, //2 + UBJson.INT32, 0, 0, 0, 3, //3 + UBJson.ARRAY_END, + UBJson.INT8, 4, 97, 116, 116, 53, //att5 + UBJson.OBJECT_START, + UBJson.INT8, 4, 97, 116, 116, 78, //attN + UBJson.INT32, 0, 0, 3, 21, //789 + UBJson.OBJECT_END, + UBJson.OBJECT_END}, bytes); + + Map result = new UBJsonMapper().readValue(bytes, Map.class); + assertEquals(map, result); + + } + +}
