]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/JSONObjectUtils.java
558ee320459e519823852eac43d654763e90906f
[simantics/platform.git] / bundles / org.simantics.document.server.io / src / org / simantics / document / server / io / JSONObjectUtils.java
1 /*******************************************************************************
2  * Copyright (c) 2013, 2014 Association for Decentralized 
3  * Information Management in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the THTH Simantics 
6  * Division Member Component License which accompanies this 
7  * distribution, and is available at
8  * http://www.simantics.org/legal/sdmcl-v10.html
9  *
10  * Contributors:
11  *     Semantum Oy - initial API and implementation
12  *******************************************************************************/
13 package org.simantics.document.server.io;
14
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.List;
20
21 public class JSONObjectUtils {
22     
23     public static String getText(IJSONObject object) {
24         return getValueOrDefault(object, "text", "");
25     }
26     
27     public static String getLink(IJSONObject object) {
28         return getValueOrDefault(object, "link", "");
29     }
30     
31     public static String getTarget(IJSONObject object) {
32         return getValueOrDefault(object, "target", "");
33     }
34     
35     public static String getHyperLinkTarget(IJSONObject object){
36         return getValueOrDefault(object, "hyperlinkTarget", "");
37     }
38     
39     public static String getWidth(IJSONObject object) {
40         return getValueOrDefault(object, "width", "");
41     }
42     
43     public static String getHeight(IJSONObject object) {
44         return getValueOrDefault(object, "height", "");
45     }
46
47     public static String getParent(IJSONObject object) {
48         return object.getValue("parent");
49     }
50     
51     public static boolean enabled(IJSONObject object) {
52         return getValueOrDefault(object, "enabled", true);
53     }
54     
55     public static boolean visible(IJSONObject object) {
56         return getValueOrDefault(object, "visible", true);
57     }
58     
59     public static boolean readOnly(IJSONObject object) {
60         return getValueOrDefault(object, "readOnly", false);
61     }
62     
63     public static boolean selected(IJSONObject object) {
64         return getValueOrDefault(object, "selected", false);
65     }
66
67     public static boolean followEditMode(IJSONObject object) {
68         return getValueOrDefault(object, "followEditMode", true);
69     }
70
71     public static String getType(IJSONObject object) {
72         String result = (String)object.getValue("type");
73         if(result == null) throw new IllegalStateException("No type for object " + object);
74         return result;
75     }
76
77     public static String getId(IJSONObject object) {
78         String result = (String)object.getValue("id");
79         if(result == null) throw new IllegalStateException("No type for object " + object);
80         return result;
81     }
82     
83     public static <T> T getValueOrDefault(IJSONObject object, String key, T defaultValue) {
84         try {
85                 T value = (T)object.getValue(key);
86                 if(value != null) return value;
87         } catch (ClassCastException e) {
88             e.printStackTrace();
89         }
90         return defaultValue;        
91     }
92     
93     public static String[] getStringArrayValueOrDefault(IJSONObject object, String key, String[] defaultValue) {
94         try {
95             Object o = object.getValue(key);
96             if (o instanceof List) {
97                 @SuppressWarnings("unchecked")
98                 List<String> s = (List<String>) o;
99                 return s.toArray(new String[s.size()]);
100             } else if (o instanceof String[]) {
101                 return (String[]) o;
102             }
103         } catch (ClassCastException e) {
104             e.printStackTrace();
105         }
106         return defaultValue;
107     }
108
109     public static float[] getFloatArrayValueOrDefault(IJSONObject object, String key, float[] defaultValue) {
110         try {
111                 Object o = object.getValue(key);
112             if (o instanceof List) {
113                 @SuppressWarnings("unchecked")
114                 List<Float> list = (List<Float>) o;
115                 float[] result = new float[list.size()];
116                 int pos = 0;
117                 for (float value : list) {
118                         result[pos++] = value;
119                 }
120                 return result;
121             } else if (o instanceof float[]) {
122                 return (float[]) o;
123             }
124         } catch (ClassCastException e) {
125             e.printStackTrace();
126         }
127         return defaultValue;
128     }
129
130     public static int[] getIntArrayValueOrDefault(IJSONObject object, String key, int[] defaultValue) {
131         try {
132             Object o = object.getValue(key);
133             if (o instanceof List) {
134                 @SuppressWarnings("unchecked")
135                 List<Integer> list = (List<Integer>) o;
136                 int[] result = new int[list.size()];
137                 int pos = 0;
138                 for (int i : list) {
139                         result[pos++] = i;
140                 }
141                 return result;
142             } else if (o instanceof int[]) {
143                 return (int[]) o;
144             }
145         } catch (ClassCastException e) {
146             e.printStackTrace();
147         }
148         return defaultValue;
149     }
150
151     public static double[] getDoubleArrayValueOrDefault(IJSONObject object, String key, double[] defaultValue) {
152         try {
153                 Object o = object.getValue(key);
154             if (o instanceof List) {
155                 @SuppressWarnings("unchecked")
156                 List<Double> list = (List<Double>) o;
157                 double[] result = new double[list.size()];
158                 int pos = 0;
159                 for (double value : list) {
160                         result[pos++] = value;
161                 }
162                 return result;
163             } else if (o instanceof double[]) {
164                 return (double[]) o;
165             }
166         } catch (ClassCastException e) {
167             e.printStackTrace();
168         }
169         return defaultValue;
170     }
171     
172 //    public static String[] getObjectArrayValue(IJSONObject object, String key) {
173 //        try {
174 //            String value = (String)object.getValue(key);
175 //            if(value != null && value.startsWith("[") && value.endsWith("]")) {
176 //              
177 //              if(value.length() == 2) return new String[0];
178 //              
179 //                value = value.substring(1, value.length() - 1);
180 //                String[] split = value.split(",");
181 //                
182 //                for(int i = 0; i < split.length; i++) {
183 //                      if(split[i].startsWith("\"") && split[i].endsWith("\""))
184 //                                      split[i] = split[i].substring(1, split[i].length() - 1);
185 //                }
186 //                
187 //                return split;
188 //            }
189 //        } catch (ClassCastException e) {
190 //            e.printStackTrace();
191 //            return null;
192 //        }
193 //        
194 //        return null;
195 //    }
196
197     public static Collection<ICommand> getCommands(IJSONObject object) {
198         try {
199                 Collection<ICommand> result = object.getValue("commands");
200                 if(result != null) return result;
201         } catch (ClassCastException e) {
202             e.printStackTrace();
203         }
204         return Collections.emptyList();
205     }
206     
207     @SuppressWarnings("unchecked")
208     public static Collection<IChartItem> getChartItems(IJSONObject object) {
209         try {
210             Object values = object.getValue("values");
211             if (values == null)
212                 return Collections.emptyList();
213             if (values instanceof String) {
214                 String valuess = (String) values;
215                 if (valuess.length() == 0)
216                     return Collections.emptyList();
217             }
218             return (List<IChartItem>) values;
219         } catch (ClassCastException e) {
220             e.printStackTrace();
221         }
222         
223         return Collections.emptyList();
224     }
225     
226 //    public static TaskSeriesCollection getGanttTasks(IJSONObject object) {
227 //        TaskSeriesCollection collection = new TaskSeriesCollection();
228 //        try {
229 //            
230 //            //JSONArray seriesArray = object.getJSONArray("ganttSeries");
231 //            @SuppressWarnings("unchecked")
232 //            List<IJSONObject> seriesArray = (List<IJSONObject>) object.getValue("ganttSeries");
233 //            for(IJSONObject seriesObject : seriesArray) {
234 //                //IJSONObject seriesObject = seriesArray.getJSONObject(i);
235 //                
236 //                TaskSeries series = new TaskSeries(getStringValueOrNull(seriesObject, "name"));
237 //                
238 //                //JSONArray tasksArray = seriesObject.getJSONArray("tasks");
239 //                @SuppressWarnings("unchecked")
240 //                List<IJSONObject> tasksArray = (List<IJSONObject>) object.getValue("tasks");
241 //                
242 //                for(IJSONObject taskObject : tasksArray) {
243 //                    //IJSONObject taskObject = tasksArray.getJSONObject(j);
244 //                    String name = getStringValueOrNull(taskObject, "name");
245 //                    Double start = getDoubleValueOrNull(taskObject, "start");
246 //                    Double end = getDoubleValueOrNull(taskObject, "end");
247 //                    
248 ////                    System.out.println("Task: " + name + ", start: " + start + ", end: " + end);
249 //                    
250 //                    if(start >= 0 && end >= 0 && start < end) {
251 //                        Task task = new Task(name,  new Date(start.intValue()), new Date(end.intValue()));
252 //                        
253 //                        try {
254 //                            //JSONArray subtasksArray = taskObject.getJSONArray("subtasks");
255 //                            @SuppressWarnings("unchecked")
256 //                            List<IJSONObject> subtasksArray = (List<IJSONObject>) object.getValue("subtasks");
257 ////                            System.out.println("\tFound " + subtasksArray.length() + " subtasks");
258 //                            for(IJSONObject subtaskObject : subtasksArray) {
259 //                                //IJSONObject subtaskObject = subtasksArray.getJSONObject(s);
260 //                                String subtaskname = getStringValueOrNull(subtaskObject, "name");
261 //                                Double subtaskstart = getDoubleValueOrNull(subtaskObject, "start");
262 //                                Double subtaskend = getDoubleValueOrNull(subtaskObject, "end");
263 //                                if(subtaskstart >= 0 && subtaskend >= 0 && subtaskstart < subtaskend) {
264 //                                    Task subtask = new Task(subtaskname + " subtask " + (subtasksArray.indexOf(subtaskObject)),  new Date(subtaskstart.intValue()), new Date(subtaskend.intValue()));
265 //                                    task.addSubtask(subtask);
266 ////                                    System.out.println("\tSubTask: " + subtaskname + ", start: " + subtaskstart + ", end: " + subtaskend);
267 //                                }
268 //                            }
269 //                        } catch (ClassCastException e) {
270 //                            // Some tasks may not have subtasks
271 //                            e.printStackTrace();
272 //                        }
273 //                        
274 //                        series.add(task);
275 //                    }
276 //                }
277 //                
278 //                collection.add(series);
279 //            }
280 //        } catch (ClassCastException e) {
281 //            e.printStackTrace();
282 //        }
283 //        return collection;
284 //    }
285     
286     @SuppressWarnings("unchecked")
287     public static Collection<IDataDefinition> getDataDefinitions(IJSONObject object) {
288         try {
289                 Collection<IDataDefinition> result = (List<IDataDefinition>) object.getValue("dataDefinitions");
290                 if(result != null) return result;
291         } catch (ClassCastException e) {
292             e.printStackTrace();
293         }
294         return Collections.emptyList();
295     }
296     
297     @SuppressWarnings("unchecked")
298     public static Collection<ITableCell> getTableCell(IJSONObject object) {
299         try {
300             Object tableCells = object.getValue("tableCells");
301             if (tableCells instanceof String) {
302                 String tableCellsS = (String) tableCells;
303                 if (tableCellsS.length() == 0)
304                     return Collections.emptyList();
305             }
306             if (tableCells != null) {
307                 return (List<ITableCell>) tableCells;
308             } else {
309                 return Collections.emptyList();
310             }
311         } catch (ClassCastException e) {
312             e.printStackTrace();
313         }
314         return Collections.emptyList();
315     }
316     
317     public static Collection<FileInfo> getFiles(IJSONObject object) {
318         try {
319             @SuppressWarnings("unchecked")
320             List<IJSONObject> fileArray = (List<IJSONObject>) object.getValue("files");
321             ArrayList<FileInfo> fileList = new ArrayList<FileInfo>();
322             for(IJSONObject f : fileArray) {
323                 String name = getValueOrDefault(f, "name", "");
324                 String content = getValueOrDefault(f, "content", "");
325                 Long resourceId = getValueOrDefault(f, "resourceId", 0L);
326                 Long creationTimeMillis = getValueOrDefault(f, "creationTimeMillis", 0L);
327                 boolean canModify = getValueOrDefault(f, "canModify", false);
328                 if(name != null && content != null) {
329                     fileList.add(new FileInfo(name, content, resourceId, creationTimeMillis, canModify));
330                 }
331             }
332             return fileList;
333         } catch (ClassCastException e) {
334             e.printStackTrace();
335         }
336         
337         return Collections.emptyList();
338     }
339
340     public static List<IListItem> getListItems(IJSONObject object) {
341         Object items =  object.getValue("listItems");
342         if (items instanceof List<?>)
343             return (List<IListItem>) items;
344         else
345             return Collections.<IListItem>emptyList();
346     }
347     
348     @SuppressWarnings("unchecked")
349     public static Collection<ITreeTableCell> getTreeTableCell(IJSONObject object) {
350         try {
351             Object treeTableCells = object.getValue("tableCells");
352             if (treeTableCells instanceof String) {
353                 String tableCellsS = (String) treeTableCells;
354                 if (tableCellsS.length() == 0)
355                     return Collections.emptyList();
356             }
357             if (treeTableCells != null) {
358                 return (List<ITreeTableCell>) treeTableCells;
359             } else {
360                 return Collections.emptyList();
361             }
362         } catch (ClassCastException e) {
363             e.printStackTrace();
364         }
365         return Collections.emptyList();
366     }
367
368     public static final boolean equalObjects(Object oldValue, Object newValue) {
369         if (newValue != null) {
370                 if (newValue.getClass().isArray()) {
371                         return arrayEquals(newValue, oldValue);
372                 } else {
373                         return newValue.equals(oldValue);
374                 }
375         } else
376                 return oldValue == null;
377     }
378
379     
380         /**
381          * @param av1 an array (guaranteed)
382          * @param av2 any object
383          * @return <code>true</code> if the two arrays are equal
384          */
385         private static final boolean arrayEquals(Object av1, Object av2) {
386                 if (av2 == null)
387                         return false;
388                 Class<?> c1 = av1.getClass().getComponentType();
389                 Class<?> c2 = av2.getClass().getComponentType();
390                 if (c2 == null || !c1.equals(c2))
391                         return false;
392                 boolean p1 = c1.isPrimitive();
393                 boolean p2 = c2.isPrimitive();
394                 if (p1 != p2)
395                         return false;
396                 if (!p1)
397                         return Arrays.equals((Object[]) av1, (Object[]) av2);
398                 if (boolean.class.equals(c1))
399                         return Arrays.equals((boolean[]) av1, (boolean[]) av2);
400                 else if (byte.class.equals(c1))
401                         return Arrays.equals((byte[]) av1, (byte[]) av2);
402                 else if (int.class.equals(c1))
403                         return Arrays.equals((int[]) av1, (int[]) av2);
404                 else if (long.class.equals(c1))
405                         return Arrays.equals((long[]) av1, (long[]) av2);
406                 else if (float.class.equals(c1))
407                         return Arrays.equals((float[]) av1, (float[]) av2);
408                 else if (double.class.equals(c1))
409                         return Arrays.equals((double[]) av1, (double[]) av2);
410                 throw new RuntimeException("Unsupported objects for equality testing ." + av1 + " vs. " + av2);
411                 
412         }
413     
414     
415 }