| 1 |
/* |
| 2 |
Copyright 2016 Google Inc. All rights reserved. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
import java.lang.reflect.Method; |
| 18 |
import java.lang.reflect.InvocationTargetException; |
| 19 |
import java.util.HashSet; |
| 20 |
import java.util.Set; |
| 21 |
|
| 22 |
public class JsonnetValue { |
| 23 |
public static String manifest(Object value) { |
| 24 |
StringBuffer buf = new StringBuffer(); |
| 25 |
if (value == null) { |
| 26 |
buf.append("null"); |
| 27 |
|
| 28 |
} else if (value instanceof String) { |
| 29 |
// FIXME: does not escape the string |
| 30 |
buf.append("\"" + value + "\""); |
| 31 |
|
| 32 |
} else if (value instanceof Double) { |
| 33 |
buf.append(value.toString()); |
| 34 |
|
| 35 |
} else if (value instanceof Boolean) { |
| 36 |
buf.append(value.toString()); |
| 37 |
|
| 38 |
} else if (value instanceof Object[]) { |
| 39 |
Object[] arr = (Object[]) value; |
| 40 |
buf.append("["); |
| 41 |
String prefix = " "; |
| 42 |
for (Object element : arr) { |
| 43 |
buf.append(prefix); |
| 44 |
prefix = ", "; |
| 45 |
buf.append(manifest(element)); |
| 46 |
} |
| 47 |
buf.append(" ]"); |
| 48 |
|
| 49 |
} else if (value instanceof JsonnetObject) { |
| 50 |
JsonnetObject obj = (JsonnetObject) value; |
| 51 |
buf.append("{"); |
| 52 |
String prefix = " "; |
| 53 |
for (String field : obj.nonHiddenFields()) { |
| 54 |
buf.append(prefix); |
| 55 |
prefix = ", "; |
| 56 |
buf.append("\"" + field + "\": "); |
| 57 |
try { |
| 58 |
Method method = obj.getClass().getMethod(field); |
| 59 |
Object fieldValue = method.invoke(obj); |
| 60 |
buf.append(manifest(fieldValue)); |
| 61 |
} catch (IllegalArgumentException e) { |
| 62 |
System.out.println(e); |
| 63 |
} catch (IllegalAccessException e) { |
| 64 |
System.out.println(e); |
| 65 |
} catch (InvocationTargetException e) { |
| 66 |
System.out.println(e); |
| 67 |
} catch (SecurityException e) { |
| 68 |
System.out.println(e); |
| 69 |
} catch (NoSuchMethodException e) { |
| 70 |
System.out.println(e); |
| 71 |
} |
| 72 |
} |
| 73 |
buf.append(" }"); |
| 74 |
} else { |
| 75 |
throw new RuntimeException("Got weird type: " + value.getClass()); |
| 76 |
} |
| 77 |
return buf.toString(); |
| 78 |
} |
| 79 |
} |
| 80 |
|