package org.simantics.document.server; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.simantics.databoard.Bindings; import org.simantics.databoard.adapter.AdaptException; import org.simantics.databoard.adapter.Adapter; import org.simantics.databoard.adapter.AdapterConstructionException; import org.simantics.databoard.binding.ArrayBinding; import org.simantics.databoard.binding.Binding; import org.simantics.databoard.binding.MapBinding; import org.simantics.databoard.binding.OptionalBinding; import org.simantics.databoard.binding.RecordBinding; import org.simantics.databoard.binding.error.BindingException; import org.simantics.databoard.parser.repository.DataValueRepository; import org.simantics.databoard.type.Component; import org.simantics.databoard.type.RecordType; import org.simantics.databoard.util.Bean; import org.simantics.document.server.io.IJSONObject; import org.simantics.scl.runtime.tuple.Tuple; final public class JSONObject extends Bean implements IJSONObject { final public String id; final public TreeMap fields = new TreeMap(); private int hashCode = 0; public JSONObject(Binding binding, String id) { super(binding); assert (binding != null); assert (id != null); this.id = id.intern(); } public JSONObject(String id) { assert (id != null); this.id = id.intern(); } public JSONObject clone() { JSONObject result = new JSONObject(binding, id); for (Map.Entry e : fields.entrySet()) result.addJSONField(e.getKey(), e.getValue()); return result; } public void add(Map fields) { for (Map.Entry e : fields.entrySet()) addJSONField(e.getKey(), e.getValue()); } @Override public int hashCode() { if(hashCode == 0) { int result = id.hashCode(); Iterator> i = fields.entrySet().iterator(); while (i.hasNext()) { Entry entry = i.next(); String key = entry.getKey(); Object value = entry.getValue(); if(value != null) { if(value.getClass().isArray()) result += objectHashCode(key) ^ arrayHashCode(value); else result += objectHashCode(key) ^ objectHashCode(value); } else { result += objectHashCode(key); } } hashCode = result; } return hashCode; } /** * Returns the hash code of a non-{@code null} argument and 0 for * a {@code null} argument. * * @param o an object * @return the hash code of a non-{@code null} argument and 0 for * a {@code null} argument * @see Object#hashCode */ private static int objectHashCode(Object o) { return o != null ? o.hashCode() : 0; } private final boolean arrayEquals(Object av1, Object av2) { if (av2 == null) return false; Class c1 = av1.getClass().getComponentType(); Class c2 = av2.getClass().getComponentType(); if (c2 == null || !c1.equals(c2)) return false; boolean p1 = c1.isPrimitive(); boolean p2 = c2.isPrimitive(); if (p1 != p2) return false; if (!p1) return Arrays.equals((Object[]) av1, (Object[]) av2); if (boolean.class.equals(c1)) return Arrays.equals((boolean[]) av1, (boolean[]) av2); else if (byte.class.equals(c1)) return Arrays.equals((byte[]) av1, (byte[]) av2); else if (int.class.equals(c1)) return Arrays.equals((int[]) av1, (int[]) av2); else if (long.class.equals(c1)) return Arrays.equals((long[]) av1, (long[]) av2); else if (float.class.equals(c1)) return Arrays.equals((float[]) av1, (float[]) av2); else if (double.class.equals(c1)) return Arrays.equals((double[]) av1, (double[]) av2); throw new RuntimeException("??? Contact application querySupport."); } private final int arrayHashCode(Object av) { if (av == null) return 0; Class c1 = av.getClass().getComponentType(); boolean p1 = c1.isPrimitive(); if (!p1) return Arrays.hashCode((Object[]) av); if (boolean.class.equals(c1)) return Arrays.hashCode((boolean[]) av); else if (byte.class.equals(c1)) return Arrays.hashCode((byte[]) av); else if (int.class.equals(c1)) return Arrays.hashCode((int[]) av); else if (long.class.equals(c1)) return Arrays.hashCode((long[]) av); else if (float.class.equals(c1)) return Arrays.hashCode((float[]) av); else if (double.class.equals(c1)) return Arrays.hashCode((double[]) av); throw new RuntimeException("??? Contact application querySupport."); } @Override public boolean equals(Object object) { if (this == object) return true; else if (object == null) return false; else if (!(object instanceof JSONObject)) return false; JSONObject o = (JSONObject) object; if (!id.equals(o.id)) return false; Set keys = fields.keySet(); Set otherKeys = o.fields.keySet(); if (!keys.equals(otherKeys)) return false; for (String key : keys) { Object value = fields.get(key); Object otherValue = o.fields.get(key); if (otherValue != null) { if (otherValue.getClass().isArray()) { if (!arrayEquals(otherValue, value)) { return false; } } else { if (!otherValue.equals(value)) { return false; } } } else if (value != null) return false; } return true; } public void addJSONField(String key, Object content) { fields.put(key, content); } @SuppressWarnings("unchecked") public T getJSONField(String key) { return (T) fields.get(key); } @SuppressWarnings("unchecked") public T getJSONFieldDefault(String key, T defaultValue) { T value = (T) fields.get(key); if (value != null) return value; else return defaultValue; } @SuppressWarnings("unchecked") public T getBeanJSONFieldDefault(String key, Binding target, T defaultValue) { T value = (T) fields.get(key); try { if (value != null) { // if (value instanceof Bean) { Binding source = Bindings.getBinding(target.type()); Adapter adapter = Bindings.getAdapter(source, target); return (T) adapter.adapt(value); // } // return value; } } catch (AdapterConstructionException e) { } catch (AdaptException e) { } return defaultValue; } public String getParent() { return (String) fields.get("parent"); } public String getParentOrd() { return (String) fields.get("parentOrd"); } public String getType() { return (String) fields.get("type"); } public String toString() { StringBuilder b = new StringBuilder(); b.append("{"); boolean first = true; for (Map.Entry entry : fields.entrySet()) { if (first) first = false; else b.append(","); String key = entry.getKey(); String value = fieldJSON(entry.getValue()); if (value == null) { first = true; // prevents ", ," when no key and value are given continue; } b.append('"'); b.append(key); b.append('"'); b.append(':'); b.append(value); b.append("\n"); } b.append("}"); return b.toString(); } private void printValue(Object value, Binding binding_, StringBuilder sb) throws IOException { try { if (binding_ instanceof RecordBinding) { RecordBinding binding = (RecordBinding) binding_; sb.append("{"); RecordType type = binding.type(); for (int i = 0, j = 0; i < type.getComponentCount(); i++) { Component c = type.getComponent(i); Object field = binding.getComponent(value, i); Binding b = binding.getComponentBinding(i); if (b instanceof OptionalBinding) { OptionalBinding ob = (OptionalBinding) b; if (!ob.hasValueUnchecked(field)) continue; b = ob.getComponentBinding(); } if (j > 0) sb.append(","); sb.append("\n"); j++; sb.append("\""); sb.append(c.name); sb.append("\" : "); printValue(field, b, sb); } sb.append("}"); } else if (binding_ instanceof ArrayBinding) { ArrayBinding binding = (ArrayBinding) binding_; Binding b = binding.getComponentBinding(); sb.append("["); for (int i = 0; i < binding.size(value); i++) { if (i > 0) sb.append(","); printValue(binding.get(value, i), b, sb); } sb.append("]"); } else if (binding_ instanceof MapBinding) { sb.append("{"); MapBinding binding = (MapBinding) binding_; int j = 0; for (Object key : binding.getKeys(value)) { Object val = binding.get(value, key); if (key instanceof String && val instanceof String) { if (j > 0) sb.append(","); sb.append("\n"); j++; sb.append("\""); sb.append((String) key); sb.append("\" : \""); sb.append((String) val); sb.append("\""); } } sb.append("}"); } else { DataValueRepository rep = new DataValueRepository(); binding_.printValue(value, sb, rep, false); } } catch (BindingException e) { e.printStackTrace(); } } private String printList(List list) { StringBuilder b = new StringBuilder(); b.append("["); boolean first = true; for (Object o : list) { if (first) { first = false; } else { b.append(","); } b.append(fieldJSON(o)); } b.append("]"); return b.toString(); } private String fieldJSON(Object field) { if (field == null) return null; String valueString = null; if (field instanceof Bean) { // Try bean to JSON try { Bean bean = (Bean) field; StringBuilder sb = new StringBuilder(); printValue(bean, bean.getBinding(), sb); valueString = sb.toString(); } catch (IOException e) { e.printStackTrace(); } } else if (field instanceof List) { return printList((List) field); } else if (field instanceof Tuple) { Tuple t = (Tuple) field; if (t.length() == 2) { Object o1 = t.get(0); Object o2 = t.get(1); if (o1 instanceof String) { return fieldJSON(o1) + " : " + fieldJSON(o2); } else { return "{" + fieldJSON(o1) + " , " + fieldJSON(o2) + "}"; } } else { StringBuilder b = new StringBuilder(); b.append("{"); for (int i = 0; i < t.length(); i++) { if (i > 0) b.append(","); b.append(fieldJSON(t.get(i))); } b.append("}"); return b.toString(); } } else { if (field.getClass().isArray()) { Object[] array; if (field instanceof float[]) { array = new Float[((float[]) field).length]; for (int i = 0; i < array.length; i++) { array[i] = ((float[]) field)[i]; } } else if (field instanceof int[]) { array = new Integer[((int[]) field).length]; for (int i = 0; i < array.length; i++) { array[i] = ((int[]) field)[i]; } } else array = (Object[]) field; // Build a string of the value array. Format is: [ value, value, // value, ... ] StringBuilder arrayBuilder = new StringBuilder(); arrayBuilder.append("["); for (int i = 0; i < array.length; i++) { Object o = array[i]; if (i != 0) arrayBuilder.append(","); if (o instanceof String) arrayBuilder.append("\""); arrayBuilder.append(o.toString()); if (o instanceof String) arrayBuilder.append("\""); } arrayBuilder.append("]"); valueString = arrayBuilder.toString(); } else { if (field instanceof String) { // Use a string representation of the value valueString = quote((String) field); } else { // Use a string representation of the value valueString = "\"" + field.toString() + "\""; } } } return valueString; } /* * Copied from org.json * Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } public String getId() { return id; } @SuppressWarnings("unchecked") @Override public T getValue(String key) { return (T)fields.get(key); } @Override public Iterator keys() { return fields.keySet().iterator(); } @Override public IJSONObject clone(Map newObjects) { JSONObject result = new JSONObject(binding, id); for (Map.Entry e : fields.entrySet()) result.addJSONField(e.getKey(), e.getValue()); for (Map.Entry e : newObjects.entrySet()) result.addJSONField(e.getKey(), e.getValue()); return result; } }