List of usage examples for com.google.gson JsonParseException JsonParseException
public JsonParseException(Throwable cause)
From source file:org.sweble.wom3.serialization.Wom3NodeJsonTypeAdapter.java
License:Open Source License
private static Node fromJson(Wom3Document doc, JsonElement json, ScopeStack scopeStack) { // Get node object if (!json.isJsonObject()) throw new JsonParseException("Expected JsonObject"); JsonObject o = json.getAsJsonObject(); Set<Entry<String, JsonElement>> entries = o.entrySet(); // Get node type JsonElement type = o.get(PROPERTY_TYPE); if (type == null) throw new JsonParseException("Missing member '" + PROPERTY_TYPE + "'"); if (!type.isJsonPrimitive()) throw new JsonParseException("Expected member '" + PROPERTY_TYPE + "' to be a string"); Element elem = null;// w w w. j a v a2 s .c o m ValueTypes valueType = null; Scope scope = null; String defaultNsUri = null; String typeQName = type.getAsString(); if (typeQName.startsWith(SPECIAL_TYPE_PREFIX)) { if (typeQName.equals("#text")) { valueType = ValueTypes.XML_TEXT; } else if (typeQName.equals(TYPE_ENTITY_REF)) { valueType = ValueTypes.ENTITY_REF; } else if (typeQName.equals("#cdata-section")) { valueType = ValueTypes.CDATA; } else if (typeQName.equals("#comment")) { valueType = ValueTypes.COMMENT; } else { throw new JsonParseException("Unknown special type '" + typeQName + "'"); } } else { scope = registerNsDecls(entries, scopeStack, scope); defaultNsUri = scopeStack.getXmlns(); if (defaultNsUri != null && defaultNsUri.isEmpty()) defaultNsUri = null; elem = createElement(doc, scopeStack, defaultNsUri, typeQName); } int countType = 0; int countChildren = 0; String nodeValue = null; for (Entry<String, JsonElement> e : entries) { String entryName = e.getKey(); JsonElement entryValue = e.getValue(); if (entryName.startsWith(ATTRIBUTE_PREFIX)) { if (elem == null) throw new JsonParseException("Node type '" + typeQName + "' cannot have attributes"); parseAttribute(scopeStack, elem, entryName, entryValue); } else if (entryName.startsWith(PROPERTY_PREFIX)) { if (entryName.equals(PROPERTY_TYPE)) { ++countType; if (countType > 1) throw new JsonParseException("Member '" + PROPERTY_TYPE + "' occurred repeatedly"); // Ignore, we handled that field already } else if (entryName.equals(PROPERTY_VALUE)) { if (nodeValue != null) throw new JsonParseException("Member '" + PROPERTY_VALUE + "' occurred repeatedly"); if (valueType == null) throw new JsonParseException("Type '" + typeQName + "' cannot have a value"); nodeValue = entryValue.getAsString(); } else if (entryName.equals(PROPERTY_CHILDREN)) { ++countChildren; if (countChildren > 1) throw new JsonParseException("Member '" + PROPERTY_CHILDREN + "' occurred repeatedly"); if (valueType != null) throw new JsonParseException("Type '" + typeQName + "' cannot have children"); if (!entryValue.isJsonArray()) throw new JsonParseException("Expected member '" + entryName + "' to be an array."); JsonArray children = entryValue.getAsJsonArray(); for (JsonElement child : children) elem.appendChild(fromJson(doc, child, scopeStack)); } } else throw new JsonParseException("Unexpected field: '" + entryName + "'"); } if (scope != null) scopeStack.pop(); return (valueType != null) ? valueType.create(doc, nodeValue) : elem; }
From source file:org.syphr.lametrictime.api.common.impl.typeadapters.imported.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*from w w w.j a v a 2 s . co m*/ final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = RuntimeTypeAdapterFactory.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } RuntimeTypeAdapterFactory.write(clone, out); } }.nullSafe(); }
From source file:org.terasology.i18n.gson.I18nMapTypeAdapter.java
License:Apache License
@Override public I18nMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonPrimitive()) { return new I18nMap(json.getAsString()); } else if (json.isJsonObject()) { JsonObject obj = json.getAsJsonObject(); Map<Locale, String> values = Maps.newHashMapWithExpectedSize(obj.entrySet().size()); for (Map.Entry<String, JsonElement> item : obj.entrySet()) { if (item.getValue().isJsonPrimitive()) { values.put(Locale.forLanguageTag(item.getKey()), item.getValue().getAsString()); } else { throw new JsonParseException( "Expected locale string pair, found " + item.getKey() + "'" + item.getValue() + "'"); }//from w ww . jav a2 s . co m } return new I18nMap(values); } else { throw new JsonParseException("Invalid I18nMap: '" + json + "'"); } }
From source file:org.terasology.persistence.typeHandling.gson.PolymorphicTypeAdapterFactory.java
License:Apache License
@Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (!baseClass.isAssignableFrom(type.getRawType())) { return null; }//from w w w . j a v a 2s .com return new TypeAdapter<R>() { @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, R value) throws IOException { Class<?> valueClass = value.getClass(); String valueTypeName = valueClass.getName(); TypeToken<?> valueType = TypeToken.get(valueClass); TypeAdapter<R> delegate = (TypeAdapter<R>) gson .getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType); if (delegate == null) { throw new JsonParseException("Could not serialize " + valueClass.getName()); } JsonElement jsonElement = delegate.toJsonTree(value); if (valueClass != baseClass) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject clone = new JsonObject(); clone.add(TYPE_FIELD_NAME, new JsonPrimitive(valueTypeName)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } else { Streams.write(jsonElement, out); } } @SuppressWarnings("unchecked") @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); Class<?> valueClass; if (jsonElement.isJsonObject()) { JsonElement typeNameJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD_NAME); if (typeNameJsonElement != null) { String typeName = typeNameJsonElement.getAsString(); try { valueClass = Class.forName(typeName); } catch (ClassNotFoundException e) { throw new JsonParseException("Could not find class " + typeName); } } else { valueClass = baseClass; } } else { valueClass = baseClass; } if (!baseClass.isAssignableFrom(valueClass)) { throw new JsonParseException( valueClass.getName() + " does not derive from " + baseClass.getName()); } TypeToken<?> valueType = TypeToken.get(valueClass); TypeAdapter<R> delegate = (TypeAdapter<R>) gson .getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType); if (delegate == null) { throw new JsonParseException("Could not deserialize " + valueClass.getName()); } return delegate.fromJsonTree(jsonElement); } }; }
From source file:org.terasology.utilities.gson.ColorTypeAdapter.java
License:Apache License
@Override public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) { String value = json.getAsString(); return new Color((int) Long.parseLong(value, 16)); }/*from ww w . ja va 2 s. co m*/ throw new JsonParseException("Did not find hexadecimal string for Color value"); }
From source file:org.tuleap.mylyn.task.core.internal.parser.DateIso8601Adapter.java
License:Open Source License
/** * {@inheritDoc}/*from w ww. j a v a 2 s. c o m*/ * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, * com.google.gson.JsonDeserializationContext) */ @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonPrimitive()) { try { return parseIso8601Date(json.getAsString()); } catch (ParseException e) { throw new JsonParseException(e); } } throw new JsonParseException(TuleapCoreMessages.getString(TuleapCoreKeys.invalidDate, json.toString())); }
From source file:org.ut.biolab.medsavant.SimplifiedCondition.java
License:Open Source License
public Condition getCondition(String sessionId, VariantManagerAdapter vm) throws JsonParseException { try {/* w ww .ja v a2 s . c o m*/ if (this.args.length < 1) { throw new JsonParseException("No arguments given for SimplifiedCondition with type " + this.type + " and method " + this.method); } TableSchema tableSchema = vm.getCustomTableSchema(sessionId, this.projectId, this.refId); DbColumn col = tableSchema.getDBColumn(this.args[0]); if (this.type.equals("BinaryCondition")) { if (this.method.equals("lessThan")) { return BinaryCondition.lessThan(col, this.args[1], Boolean.parseBoolean(this.args[2])); } else if (this.method.equals("greaterThan")) { return BinaryCondition.greaterThan(col, this.args[1], Boolean.parseBoolean(this.args[2])); } else if (this.method.equals("equalTo")) { return BinaryCondition.equalTo(col, this.args[1]); } else if (this.method.equals("notEqualTo")) { return BinaryCondition.notEqualTo(col, this.args[1]); } else if (this.method.equals("like")) { return BinaryCondition.like(col, this.args[1]); } else if (this.method.equals("notLike")) { return BinaryCondition.notLike(col, this.args[1]); } else if (this.method.equals("iLike")) { return BinaryCondition.iLike(col, this.args[1]); } else if (this.method.equals("notiLike")) { return BinaryCondition.notiLike(col, this.args[1]); } throw new JsonParseException( "Unrecognized method " + this.method + " for simplified condition " + this.type); } else if (this.type.equals("UnaryCondition")) { if (this.method.equals("isNull")) { return UnaryCondition.isNull(col); } else if (this.method.equals("isNotNull")) { return UnaryCondition.isNotNull(col); } else if (this.method.equals("exists")) { return UnaryCondition.exists(col); } else if (this.method.equals("unique")) { return UnaryCondition.unique(col); } throw new JsonParseException( "Unrecognized method " + this.method + " for simplified condition " + this.type); } throw new JsonParseException("Unrecognized simplified condition type " + this.type); } catch (ArrayIndexOutOfBoundsException ai) { throw new JsonParseException("Invalid arguments specified for SimplifiedCondition of type" + this.type + ", method " + this.method + ", and args=" + this.args); } catch (SQLException ex) { throw new JsonParseException("Couldn't fetch variant table schema: " + ex); } catch (RemoteException re) { throw new JsonParseException("Couldn't fetch variant table schema: " + re); } catch (SessionExpiredException se) { throw new JsonParseException("Couldn't fetch variant table schema: " + se); } }
From source file:org.wso2.carbon.identity.entitlement.endpoint.util.JSONRequestParser.java
License:Open Source License
/** * Static method that will convert a XACML JSON Request to a <code>{@link RequestCtx}</code> instance * * @param jsonRequest <code>String</code> with JSON request * @return <code>{@link RequestCtx}</code> instance that can be used to evaluate on Balana * @throws JsonParseException <code>{@link JsonParseException}</code> * @throws RequestParseException <code>{@link RequestParseException}</code> * @throws UnknownIdentifierException <code>{@link UnknownIdentifierException}</code> *///from w w w. j a v a2 s . c o m public static RequestCtx parse(String jsonRequest) throws JsonParseException, RequestParseException, UnknownIdentifierException { JsonObject requestObject = null; Set<Attributes> categories = new HashSet<>(); boolean returnPolicyIdList = false; boolean combinedDecision = false; MultiRequests multiRequests = null; RequestDefaults requestDefaults = null; try { requestObject = gson.fromJson(jsonRequest, JsonObject.class); requestObject = requestObject.get("Request").getAsJsonObject(); } catch (Exception e) { throw new JsonParseException("Error in JSON Request String"); } Set<Map.Entry<String, JsonElement>> jsonAttributes = requestObject.entrySet(); for (Map.Entry<String, JsonElement> jsonAttribute : jsonAttributes) { if (jsonAttribute.getValue().isJsonPrimitive()) { switch (jsonAttribute.getKey()) { case XACMLConstants.RETURN_POLICY_LIST: if (jsonAttribute.getValue().getAsBoolean() == true) { returnPolicyIdList = true; } break; case XACMLConstants.COMBINE_DECISION: if (jsonAttribute.getValue().getAsBoolean() == true) { combinedDecision = true; } break; case EntitlementEndpointConstants.XPATH_VERSION: String xPathVersion = jsonAttribute.getValue().getAsString(); requestDefaults = new RequestDefaults(xPathVersion); break; } } else if (!jsonAttribute.getValue().isJsonNull()) { JsonObject jsonCategory = null; if (jsonAttribute.getValue().isJsonObject()) { jsonCategory = jsonAttribute.getValue().getAsJsonObject(); jsonAttributeSeperator(jsonAttribute, jsonCategory, categories); } else if (jsonAttribute.getValue().isJsonArray()) { for (JsonElement jsonElement : jsonAttribute.getValue().getAsJsonArray()) { jsonCategory = jsonElement.getAsJsonObject(); jsonAttributeSeperator(jsonAttribute, jsonCategory, categories); } } else if (EntitlementEndpointConstants.MULTI_REQUESTS.equals(jsonAttribute.getKey())) { Set<Map.Entry<String, JsonElement>> jsonRequestReferences = jsonCategory.entrySet(); Set<RequestReference> requestReferences = new HashSet<>(); if (jsonRequestReferences.isEmpty()) { throw new RequestParseException( "MultiRequest should contain at least one Reference Request"); } for (Map.Entry<String, JsonElement> jsonRequstReference : jsonRequestReferences) { requestReferences.add( jsonObjectToRequestReference(jsonRequstReference.getValue().getAsJsonObject())); } multiRequests = new MultiRequests(requestReferences); } } } return new RequestCtx(null, categories, returnPolicyIdList, combinedDecision, multiRequests, requestDefaults); }
From source file:org.wso2.carbon.siddhi.editor.core.util.designview.deserializers.types.AggregateByTimePeriodDeSerializer.java
License:Open Source License
@Override public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonObject.get(TYPE); String attributesSelectionType = jsonPrimitive.getAsString(); if (attributesSelectionType.equalsIgnoreCase(AggregationByTimeType.RANGE.toString())) { return jsonDeserializationContext.deserialize(jsonObject, AggregateByTimeRange.class); } else if (attributesSelectionType.equalsIgnoreCase(AggregationByTimeType.INTERVAL.toString())) { return jsonDeserializationContext.deserialize(jsonObject, AggregateByTimeInterval.class); }/* w w w .j a va2 s. co m*/ throw new JsonParseException( "Unable to de-serialize the AggregateByTimePeriod JSON since its type is unknown"); }
From source file:org.wso2.carbon.siddhi.editor.core.util.designview.deserializers.types.AttributesSelectionConfigDeSerializer.java
License:Open Source License
@Override public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonObject.get(TYPE); String attributesSelectionType = jsonPrimitive.getAsString(); if (attributesSelectionType.equalsIgnoreCase(AttributeSelection.TYPE_USER_DEFINED)) { return jsonDeserializationContext.deserialize(jsonObject, UserDefinedSelectionConfig.class); } else if (attributesSelectionType.equalsIgnoreCase(AttributeSelection.TYPE_ALL)) { return jsonDeserializationContext.deserialize(jsonObject, AllSelectionConfig.class); }//www . ja v a 2s . com throw new JsonParseException( "Unable to de-serialize the AttributesSelectionConfig JSON since its type is unknown"); }