[Git][java-team/felix-utils][upstream] New upstream version 1.9.0

Emmanuel Bourg (@ebourg) gitlab at salsa.debian.org
Fri Nov 20 07:56:09 GMT 2026



Emmanuel Bourg pushed to branch upstream at Debian Java Maintainers / felix-utils


Commits:
2d256c79 by Emmanuel Bourg at 2026-11-19T11:55:01+01:00
New upstream version 1.9.0
- - - - -


5 changed files:

- doc/changelog.txt
- pom.xml
- + src/main/java/org/apache/felix/utils/json/JSONParser.java
- + src/main/java/org/apache/felix/utils/json/JSONWriter.java
- + src/test/java/org/apache/felix/utils/json/JSONParserTest.java


Changes:

=====================================
doc/changelog.txt
=====================================
@@ -1,3 +1,10 @@
+Changes from 1.8.6 to 1.9.0
+---------------------------
+** Improvement
+    * [FELIX-5534] - Add simple JSONWriter
+    * [FELIX-5508] - Add simple JSON Parser
+
+
 Changes from 1.8.4 to 1.8.6
 ---------------------------
 ** Improvement


=====================================
pom.xml
=====================================
@@ -27,13 +27,13 @@
     <modelVersion>4.0.0</modelVersion>
     <name>Apache Felix Utils</name>
     <description>Utility classes for OSGi.</description>
-    <version>1.8.6</version>
+    <version>1.9.0</version>
     <artifactId>org.apache.felix.utils</artifactId>
 
     <scm>
-        <connection>scm:svn:http://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.8.6</connection>
-        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.8.6</developerConnection>
-        <url>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.8.6</url>
+        <connection>scm:svn:http://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.9.0</connection>
+        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.9.0</developerConnection>
+        <url>scm:svn:https://svn.apache.org/repos/asf/felix/releases/org.apache.felix.utils-1.9.0</url>
     </scm>
 
     <dependencies>


=====================================
src/main/java/org/apache/felix/utils/json/JSONParser.java
=====================================
@@ -0,0 +1,297 @@
+/*
+ * 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.felix.utils.json;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A very small JSON parser.
+ *
+ * The JSON input is parsed into an object structure in the following way:
+ * <ul>
+ * <li>Object names are represented as a {@link String}.
+ * <li>String values are represented as a {@link String}.
+ * <li>Numeric values without a decimal separator are represented as a {@link Long}.
+ * <li>Numeric values with a decimal separator are represented as a {@link Double}.
+ * <li>Boolean values are represented as a {@link Boolean}.
+ * <li>Nested JSON objects are parsed into a {@link java.util.Map Map<String, Object>}.
+ * <li>JSON lists are parsed into a {@link java.util.List} which may contain any of the above values.
+ * </ul>
+ */
+public class JSONParser {
+    private static final Pattern KEY_VALUE_PATTERN = Pattern.compile("^\\s*[\"](.+?)[\"]\\s*[:]\\s*(.+)$");
+
+    private enum Scope { QUOTE, CURLY, BRACKET;
+        static Scope getScope(char c) {
+            switch (c) {
+            case '"':
+                return QUOTE;
+            case '[':
+            case ']':
+                return BRACKET;
+            case '{':
+            case '}':
+                return CURLY;
+            default:
+                return null;
+            }
+        }
+    }
+
+    static class Pair<K, V> {
+        final K key;
+        final V value;
+
+        Pair(K k, V v) {
+            key = k;
+            value = v;
+        }
+    }
+
+    private final Map<String, Object> parsed;
+
+    public JSONParser(CharSequence json) {
+        String str = json.toString();
+        str = str.trim().replace('\n', ' ');
+        parsed = parseObject(str);
+    }
+
+    public JSONParser(InputStream is) throws IOException {
+        this(readStreamAsString(is));
+    }
+
+    public Map<String, Object> getParsed() {
+        return parsed;
+    }
+
+    private static Pair<String, Object> parseKeyValue(String jsonKeyValue) {
+        Matcher matcher = KEY_VALUE_PATTERN.matcher(jsonKeyValue);
+        if (!matcher.matches() || matcher.groupCount() < 2) {
+            throw new IllegalArgumentException("Malformatted JSON key-value pair: " + jsonKeyValue);
+        }
+
+        return new Pair<String, Object>(matcher.group(1), parseValue(matcher.group(2)));
+    }
+
+    private static Object parseValue(String jsonValue) {
+        jsonValue = jsonValue.trim();
+
+        switch (jsonValue.charAt(0)) {
+        case '\"':
+            if (!jsonValue.endsWith("\""))
+                throw new IllegalArgumentException("Malformatted JSON string: " + jsonValue);
+
+            return jsonValue.substring(1, jsonValue.length() - 1);
+        case '[':
+            List<Object> entries = new ArrayList<Object>();
+            for (String v : parseListValuesRaw(jsonValue)) {
+                entries.add(parseValue(v));
+            }
+            return entries;
+        case '{':
+            return parseObject(jsonValue);
+        case 't':
+        case 'T':
+        case 'f':
+        case 'F':
+            return Boolean.parseBoolean(jsonValue);
+        case 'n':
+        case 'N':
+            return null;
+        default:
+            if (jsonValue.contains(".")) {
+                return Double.parseDouble(jsonValue);
+            }
+            return Long.parseLong(jsonValue);
+        }
+    }
+
+    private static Map<String, Object> parseObject(String jsonObject) {
+        if (!(jsonObject.startsWith("{") && jsonObject.endsWith("}")))
+            throw new IllegalArgumentException("Malformatted JSON object: " + jsonObject);
+
+        Map<String, Object> values = new HashMap<String, Object>();
+
+        jsonObject = jsonObject.substring(1, jsonObject.length() - 1).trim();
+        if (jsonObject.length() == 0)
+            return values;
+
+        for (String element : parseKeyValueListRaw(jsonObject)) {
+            Pair<String, Object> pair = parseKeyValue(element);
+            values.put(pair.key, pair.value);
+        }
+
+        return values;
+    }
+
+    private static List<String> parseKeyValueListRaw(String jsonKeyValueList) {
+        if (jsonKeyValueList.trim().length() == 0)
+            return Collections.emptyList();
+        jsonKeyValueList = jsonKeyValueList + ","; // append comma to simplify parsing
+        List<String> elements = new ArrayList<String>();
+
+        int i=0;
+        int start=0;
+        Stack<Scope> scopeStack = new Stack<Scope>();
+        while (i < jsonKeyValueList.length()) {
+            char curChar = jsonKeyValueList.charAt(i);
+            switch (curChar) {
+            case '"':
+                if (i > 0 && jsonKeyValueList.charAt(i-1) == '\\') {
+                    // it's escaped, ignore for now
+                } else {
+                    if (!scopeStack.empty() && scopeStack.peek() == Scope.QUOTE) {
+                        scopeStack.pop();
+                    } else {
+                        scopeStack.push(Scope.QUOTE);
+                    }
+                }
+                break;
+            case '[':
+            case '{':
+                if ((scopeStack.empty() ? null : scopeStack.peek()) == Scope.QUOTE) {
+                    // inside quotes, ignore
+                } else {
+                    scopeStack.push(Scope.getScope(curChar));
+                }
+                break;
+            case ']':
+            case '}':
+                Scope curScope = scopeStack.empty() ? null : scopeStack.peek();
+                if (curScope == Scope.QUOTE) {
+                    // inside quotes, ignore
+                } else {
+                    Scope newScope = Scope.getScope(curChar);
+                    if (curScope == newScope) {
+                        scopeStack.pop();
+                    } else {
+                        throw new IllegalArgumentException("Unbalanced closing " +
+                            curChar + " in: " + jsonKeyValueList);
+                    }
+                }
+                break;
+            case ',':
+                if (scopeStack.empty()) {
+                    elements.add(jsonKeyValueList.substring(start, i));
+                    start = i+1;
+                }
+                break;
+            }
+
+            i++;
+        }
+        return elements;
+    }
+
+    private static List<String> parseListValuesRaw(String jsonList) {
+        if (!(jsonList.startsWith("[") && jsonList.endsWith("]")))
+            throw new IllegalArgumentException("Malformatted JSON list: " + jsonList);
+
+        jsonList = jsonList.substring(1, jsonList.length() - 1);
+        return parseKeyValueListRaw(jsonList);
+    }
+
+    /**
+     * Read an entire input stream into a byte array.
+     * @param is The input stream to read.
+     * @return The byte array with the contents of the input stream.
+     * @throws IOException if the underlying read operation on the input stream
+     * throws an error.
+     */
+    private static byte [] readStream(InputStream is) throws IOException {
+        try {
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            byte[] bytes = new byte[65536];
+
+            int length = 0;
+            int offset = 0;
+
+            while ((length = is.read(bytes, offset, bytes.length - offset)) != -1) {
+                offset += length;
+
+                if (offset == bytes.length) {
+                    baos.write(bytes, 0, bytes.length);
+                    offset = 0;
+                }
+            }
+            if (offset != 0) {
+                baos.write(bytes, 0, offset);
+            }
+            return baos.toByteArray();
+        } finally {
+            is.close();
+        }
+    }
+
+    private static String readStreamAsString(InputStream is) throws IOException {
+        byte [] bytes = readStream(is);
+        if (bytes.length < 5)
+            // need at least 5 bytes to establish the encoding
+            throw new IllegalArgumentException("Malformatted JSON");
+
+        int offset = 0;
+        if ((bytes[0] == -1 && bytes[1] == -2)
+            || (bytes[0] == -2 && bytes[1] == -1)) {
+            // Skip UTF16/UTF32 Byte Order Mark (BOM)
+            offset = 2;
+        }
+
+        /* Infer the encoding as described in section 3 of http://www.ietf.org/rfc/rfc4627.txt
+         * which reads:
+         *   Encoding
+         *
+         *   JSON text SHALL be encoded in Unicode.  The default encoding is
+         *   UTF-8.
+         *
+         *   Since the first two characters of a JSON text will always be ASCII
+         *   characters [RFC0020], it is possible to determine whether an octet
+         *   stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
+         *   at the pattern of nulls in the first four octets.
+         *
+         *         00 00 00 xx  UTF-32BE
+         *         00 xx 00 xx  UTF-16BE
+         *         xx 00 00 00  UTF-32LE
+         *         xx 00 xx 00  UTF-16LE
+         *         xx xx xx xx  UTF-8
+         */
+        String encoding;
+        if (bytes[offset + 2] == 0) {
+            if (bytes[offset + 1] != 0) {
+                encoding = "UTF-16";
+            } else {
+                encoding = "UTF-32";
+            }
+        } else if (bytes[offset + 1] == 0) {
+            encoding = "UTF-16";
+        } else {
+            encoding = "UTF-8";
+        }
+        return new String(bytes, encoding);
+    }
+
+
+}
\ No newline at end of file


=====================================
src/main/java/org/apache/felix/utils/json/JSONWriter.java
=====================================
@@ -0,0 +1,254 @@
+/*
+ * 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.felix.utils.json;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Array;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Simple JSON writer to be used on top of a {@link Writer}.
+ */
+public class JSONWriter
+{
+
+    private final Writer pw;
+
+    private boolean comma;
+
+    public JSONWriter(final Writer pw)
+    {
+        this.comma = false;
+        this.pw = pw;
+    }
+
+    public JSONWriter object() throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        this.pw.write("{");
+        this.comma = false;
+        return this;
+    }
+
+    public JSONWriter endObject() throws IOException
+    {
+        this.pw.write('}');
+        this.comma = true;
+        return this;
+    }
+
+    public JSONWriter array() throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        this.pw.write("[");
+        this.comma = false;
+        return this;
+    }
+
+    public JSONWriter endArray() throws IOException
+    {
+        this.pw.write(']');
+        this.comma = true;
+        return this;
+    }
+
+    public JSONWriter key(String key) throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        quote(key);
+        this.pw.write(':');
+        this.comma = false;
+        return this;
+    }
+
+    public JSONWriter value(final boolean b) throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        this.pw.write(b ? "true" : "false");
+        this.comma = true;
+        return this;
+    }
+
+    public JSONWriter value(final double d) throws IOException
+    {
+        return this.value(new Double(d));
+    }
+
+    public JSONWriter value(final int i) throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        this.pw.write(String.valueOf(i));
+        this.comma = true;
+        return this;
+    }
+
+    public JSONWriter value(final long l) throws IOException
+    {
+        if (this.comma)  this.pw.write(',');
+        this.pw.write(String.valueOf(l));
+        this.comma = true;
+        return this;
+    }
+
+    public JSONWriter value(final Object value) throws IOException
+    {
+        if (this.comma)
+        {
+            this.pw.write(',');
+        }
+        if (value == null || value.equals(null))
+        {
+            this.pw.write("null");
+        }
+        else if (value instanceof Boolean )
+        {
+            this.pw.write(value.toString());
+        }
+        else if (value instanceof Number)
+        {
+            String str = value.toString();
+            if ( str.indexOf('.') == -1 || str.indexOf('e') > 0 || str.indexOf('E') > 0 )
+            {
+                this.pw.write(str);
+            } else {
+                while (str.endsWith("0"))
+                {
+                    str = str.substring(0, str.length() - 1);
+                }
+                if (str.endsWith("."))
+                {
+                    str = str.substring(0, str.length() - 1);
+                }
+                this.pw.write(str);
+            }
+        }
+        else if ( value instanceof Map)
+        {
+            this.comma = false;
+            this.object();
+
+            final Map map = (Map)value;
+            final Iterator iter = map.entrySet().iterator();
+            while ( iter.hasNext() )
+            {
+                Map.Entry entry = (Entry) iter.next();
+                this.key((String)entry.getKey());
+                this.value(entry.getValue());
+            }
+            this.endObject();
+        }
+        else if ( value.getClass().isArray() )
+        {
+            this.comma = false;
+            this.array();
+            for(int i=0;i<Array.getLength(value);i++)
+            {
+                final Object val = Array.get(value, i);
+                value(val);
+            }
+            this.endArray();
+        }
+        else if ( value instanceof Collection )
+        {
+            this.comma = false;
+            this.array();
+            final Collection col = (Collection)value;
+            final Iterator i = col.iterator();
+            while ( i.hasNext())
+            {
+                value(i.next());
+            }
+            this.endArray();
+        }
+        else
+        {
+            quote(value.toString());
+        }
+        this.comma = true;
+        return this;
+    }
+
+    /**
+     * Quote the provided value and escape some characters.
+     * @param value The value to quote
+     * @throws IOException
+     */
+    private void quote(final String value) throws IOException
+    {
+        pw.write('"');
+        final int len = value.length();
+        for(int i=0;i<len;i++)
+        {
+            final char c = value.charAt(i);
+            switch(c){
+            case '"':
+                pw.write("\\\"");
+                break;
+            case '\\':
+                pw.write("\\\\");
+                break;
+            case '\b':
+                pw.write("\\b");
+                break;
+            case '\f':
+                pw.write("\\f");
+                break;
+            case '\n':
+                pw.write("\\n");
+                break;
+            case '\r':
+                pw.write("\\r");
+                break;
+            case '\t':
+                pw.write("\\t");
+                break;
+            case '/':
+                pw.write("\\/");
+                break;
+            default:
+                if ((c>='\u0000' && c<='\u001F') || (c>='\u007F' && c<='\u009F') || (c>='\u2000' && c<='\u20FF'))
+                {
+                    final String hex=Integer.toHexString(c);
+                    pw.write("\\u");
+                    for(int k=0;k<4-hex.length();k++){
+                        pw.write('0');
+                    }
+                    pw.write(hex.toUpperCase());
+                }
+                else{
+                    pw.write(c);
+                }
+            }
+        }
+        pw.write('"');
+    }
+
+    /**
+     * @see Writer#flush()
+     * @throws IOException
+     */
+    public void flush() throws IOException
+    {
+        this.pw.flush();
+    }
+}


=====================================
src/test/java/org/apache/felix/utils/json/JSONParserTest.java
=====================================
@@ -0,0 +1,77 @@
+/*
+ * 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.felix.utils.json;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class JSONParserTest {
+    @Test
+    public void testJsonSimple() {
+        String json = "{\"hi\": \"ho\", \"ha\": true}";
+        JSONParser jp = new JSONParser(json);
+        Map<String, Object> m = jp.getParsed();
+        assertEquals(2, m.size());
+        assertEquals("ho", m.get("hi"));
+        assertTrue((Boolean) m.get("ha"));
+    }
+
+    @Test
+    @SuppressWarnings("unchecked")
+    public void testJsonComplex() {
+        String json = "{\"a\": [1,2,3,4,5], \"b\": {\"x\": 12, \"y\": 42, \"z\": {\"test test\": \"hello hello\"}}, \"ddd\": 12.34}";
+        JSONParser jp = new JSONParser(json);
+        Map<String, Object> m = jp.getParsed();
+        assertEquals(3, m.size());
+        assertEquals(Arrays.asList(1L, 2L, 3L, 4L, 5L), m.get("a"));
+        Map<String, Object> mb = (Map<String, Object>) m.get("b");
+        assertEquals(3, mb.size());
+        assertEquals(12L, mb.get("x"));
+        assertEquals(42L, mb.get("y"));
+        Map<String, Object> mz = (Map<String, Object>) mb.get("z");
+        assertEquals(1, mz.size());
+        assertEquals("hello hello", mz.get("test test"));
+        assertEquals(12.34d, ((Double) m.get("ddd")).doubleValue(), 0.0001d);
+    }
+
+    @Test
+    public void testJsonArray() {
+        String json = "{\"abc\": [\"x\", \"y\", \"z\"]}";
+        JSONParser jp = new JSONParser(json);
+        Map<String, Object> m = jp.getParsed();
+        assertEquals(1, m.size());
+        assertEquals(Arrays.asList("x", "y", "z"), m.get("abc"));
+    }
+
+    @Test
+    public void testEmptyJsonArray() {
+        String json = "{\"abc\": {\"def\": []}}";
+        JSONParser jp = new JSONParser(json);
+        Map<String, Object> m = jp.getParsed();
+        assertEquals(1, m.size());
+        Map<String, Object> result = new HashMap<String, Object>();
+        result.put("def", Collections.emptyList());
+        assertEquals(result, m.get("abc"));
+    }
+}



View it on GitLab: https://salsa.debian.org/java-team/felix-utils/-/commit/2d256c79cba0d7e7f952e939a9739d516d6ae28b

-- 
View it on GitLab: https://salsa.debian.org/java-team/felix-utils/-/commit/2d256c79cba0d7e7f952e939a9739d516d6ae28b
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261120/ec6eef2d/attachment.htm>


More information about the pkg-java-commits mailing list