001/* 002 * ModeShape (http://www.modeshape.org) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.modeshape.jdbc.rest; 017 018import java.util.ArrayList; 019import java.util.Collections; 020import java.util.List; 021import org.codehaus.jettison.json.JSONArray; 022import org.codehaus.jettison.json.JSONException; 023import org.codehaus.jettison.json.JSONObject; 024 025/** 026 * Helper class used by the client to parse {@link org.codehaus.jettison.json.JSONObject} 027 * 028 * @author Horia Chiorean (hchiorea@redhat.com) 029 */ 030public final class JSONHelper { 031 032 private JSONHelper() { 033 } 034 035 protected static List<String> valuesFrom( JSONObject json, 036 String name ) { 037 if (!json.has(name)) { 038 // Just an empty collection ... 039 return Collections.emptyList(); 040 } 041 Object prop = null; 042 try { 043 prop = json.get(name); 044 if (prop instanceof JSONArray) { 045 // There are multiple values ... 046 JSONArray array = (JSONArray)prop; 047 int length = array.length(); 048 if (length == 0) { 049 return Collections.emptyList(); 050 } 051 List<String> result = new ArrayList<>(length); 052 for (int i = 0; i < length; i++) { 053 String value = array.getString(i); 054 result.add(value); 055 } 056 return result; 057 } 058 } catch (JSONException e) { 059 throw new RuntimeException(e); 060 } 061 // Just a single value ... 062 return Collections.singletonList(prop.toString()); 063 } 064 065 protected static boolean valueFrom( JSONObject object, 066 String name, 067 boolean defaultValue ) { 068 if (!object.has(name)) { 069 return defaultValue; 070 } 071 try { 072 return object.getBoolean(name); 073 } catch (JSONException e) { 074 throw new RuntimeException(e); 075 } 076 } 077 078 protected static String valueFrom( JSONObject object, 079 String name ) { 080 return valueFrom(object, name, null); 081 } 082 083 protected static String valueFrom( JSONObject object, 084 String name, 085 String defaultValue ) { 086 if (!object.has(name)) { 087 return defaultValue; 088 } 089 try { 090 return object.getString(name); 091 } catch (JSONException e) { 092 throw new RuntimeException(e); 093 } 094 } 095}