]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/JSONObjectUtils.java
TreeGridWidget improvements
[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     @SuppressWarnings("unchecked")
318     public static Collection<ITreeTableCell> getTreeTableCells(IJSONObject object) {
319         try {
320             Object tableCells = object.getValue("tableCells");
321             if (tableCells instanceof String) {
322                 String tableCellsS = (String) tableCells;
323                 if (tableCellsS.length() == 0)
324                     return Collections.emptyList();
325             }
326             if (tableCells != null) {
327                 return (List<ITreeTableCell>) tableCells;
328             } else {
329                 return Collections.emptyList();
330             }
331         } catch (ClassCastException e) {
332             e.printStackTrace();
333         }
334         return Collections.emptyList();
335     }
336
337     public static Collection<FileInfo> getFiles(IJSONObject object) {
338         try {
339             @SuppressWarnings("unchecked")
340             List<IJSONObject> fileArray = (List<IJSONObject>) object.getValue("files");
341             ArrayList<FileInfo> fileList = new ArrayList<FileInfo>();
342             for(IJSONObject f : fileArray) {
343                 String name = getValueOrDefault(f, "name", "");
344                 String content = getValueOrDefault(f, "content", "");
345                 Long resourceId = getValueOrDefault(f, "resourceId", 0L);
346                 Long creationTimeMillis = getValueOrDefault(f, "creationTimeMillis", 0L);
347                 boolean canModify = getValueOrDefault(f, "canModify", false);
348                 if(name != null && content != null) {
349                     fileList.add(new FileInfo(name, content, resourceId, creationTimeMillis, canModify));
350                 }
351             }
352             return fileList;
353         } catch (ClassCastException e) {
354             e.printStackTrace();
355         }
356         
357         return Collections.emptyList();
358     }
359
360     public static List<IListItem> getListItems(IJSONObject object) {
361         Object items =  object.getValue("listItems");
362         if (items instanceof List<?>)
363             return (List<IListItem>) items;
364         else
365             return Collections.<IListItem>emptyList();
366     }
367     
368     @SuppressWarnings("unchecked")
369     public static Collection<ITreeTableCell> getTreeTableCell(IJSONObject object) {
370         try {
371             Object treeTableCells = object.getValue("tableCells");
372             if (treeTableCells instanceof String) {
373                 String tableCellsS = (String) treeTableCells;
374                 if (tableCellsS.length() == 0)
375                     return Collections.emptyList();
376             }
377             if (treeTableCells != null) {
378                 return (List<ITreeTableCell>) treeTableCells;
379             } else {
380                 return Collections.emptyList();
381             }
382         } catch (ClassCastException e) {
383             e.printStackTrace();
384         }
385         return Collections.emptyList();
386     }
387
388     public static final boolean equalObjects(Object oldValue, Object newValue) {
389         if (newValue != null) {
390                 if (newValue.getClass().isArray()) {
391                         return arrayEquals(newValue, oldValue);
392                 } else {
393                         return newValue.equals(oldValue);
394                 }
395         } else
396                 return oldValue == null;
397     }
398
399     
400         /**
401          * @param av1 an array (guaranteed)
402          * @param av2 any object
403          * @return <code>true</code> if the two arrays are equal
404          */
405         private static final boolean arrayEquals(Object av1, Object av2) {
406                 if (av2 == null)
407                         return false;
408                 Class<?> c1 = av1.getClass().getComponentType();
409                 Class<?> c2 = av2.getClass().getComponentType();
410                 if (c2 == null || !c1.equals(c2))
411                         return false;
412                 boolean p1 = c1.isPrimitive();
413                 boolean p2 = c2.isPrimitive();
414                 if (p1 != p2)
415                         return false;
416                 if (!p1)
417                         return Arrays.equals((Object[]) av1, (Object[]) av2);
418                 if (boolean.class.equals(c1))
419                         return Arrays.equals((boolean[]) av1, (boolean[]) av2);
420                 else if (byte.class.equals(c1))
421                         return Arrays.equals((byte[]) av1, (byte[]) av2);
422                 else if (int.class.equals(c1))
423                         return Arrays.equals((int[]) av1, (int[]) av2);
424                 else if (long.class.equals(c1))
425                         return Arrays.equals((long[]) av1, (long[]) av2);
426                 else if (float.class.equals(c1))
427                         return Arrays.equals((float[]) av1, (float[]) av2);
428                 else if (double.class.equals(c1))
429                         return Arrays.equals((double[]) av1, (double[]) av2);
430                 throw new RuntimeException("Unsupported objects for equality testing ." + av1 + " vs. " + av2);
431                 
432         }
433     
434     
435 }