Example usage for com.google.gwt.json.client JSONValue isObject

List of usage examples for com.google.gwt.json.client JSONValue isObject

Introduction

In this page you can find the example usage for com.google.gwt.json.client JSONValue isObject.

Prototype

public JSONObject isObject() 

Source Link

Document

Returns non-null if this JSONValue is really a JSONObject.

Usage

From source file:org.gwt.json.serialization.client.utils.JsonTreeMapSerializer.java

License:Apache License

@Override
public TreeMap deSerialize(JSONValue jsonObj, GenericType[] genericTypes) throws JSONException {
    if (jsonObj == null || jsonObj.isObject() == null)
        return null;
    TreeMap obj = new TreeMap();
    GenericType keyType = genericTypes[0];
    GenericType valueType = genericTypes[1];
    JSONObject mapObject = jsonObj.isObject();
    for (String key : mapObject.keySet()) {
        //well, key is always String, in this case...
        obj.put(key, serializer.getSerializerForType(valueType.getName()).deSerialize(mapObject.get(key),
                valueType.getTypes()));/*w ww  .j av a2s .c o  m*/
    }
    return obj;
}

From source file:org.jahia.ajax.gwt.client.widget.form.FormDeployPortletDefinition.java

License:Open Source License

protected void createUI() {
    setAction(getPortletDeploymentParam("formActionUrl"));
    setEncoding(Encoding.MULTIPART);
    setMethod(Method.POST);//ww  w.j  av  a 2  s  .co m
    setBodyBorder(false);
    setFrame(false);
    setAutoHeight(true);
    setHeaderVisible(false);
    setButtonAlign(Style.HorizontalAlignment.CENTER);
    setStyleAttribute("padding", "4");
    setLabelWidth(200);
    setFieldWidth(300);

    final com.extjs.gxt.ui.client.widget.form.FileUploadField portletDefinitionField = new com.extjs.gxt.ui.client.widget.form.FileUploadField();
    portletDefinitionField.setAllowBlank(false);
    portletDefinitionField.setName("portletDefinition");
    portletDefinitionField.setWidth(290);
    portletDefinitionField.setFieldLabel(
            Messages.get("org.jahia.engines.PortletsManager.wizard.upload.label", "Portlets WAR file"));
    add(portletDefinitionField);

    final HiddenField<Boolean> preparePortlet = new HiddenField<Boolean>();
    preparePortlet.setName("doPrepare");
    preparePortlet.setValue(false);
    add(preparePortlet);

    final HiddenField<Boolean> deployPortlet = new HiddenField<Boolean>();
    deployPortlet.setName("doDeploy");
    deployPortlet.setValue(false);
    add(deployPortlet);

    final HiddenField<String> jcrReturnContentType = new HiddenField<String>();
    jcrReturnContentType.setName("jcrReturnContentType");
    jcrReturnContentType.setValue("json");
    add(jcrReturnContentType);

    Button prepareButton = new Button(Messages.get("label.portletPrepareWar", "Prepare"));
    prepareButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
        @Override
        public void componentSelected(ButtonEvent ce) {
            preparePortlet.setValue(true);
            doCloseParent = true;
            submitAfterValidation(portletDefinitionField);
        }
    });
    addButton(prepareButton);

    final boolean autoDeploySupported = autoDeploySupported();
    Button deployButton = new Button(Messages.get("label.deployNewPortlet", "Deploy"));
    deployButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
        @Override
        public void componentSelected(ButtonEvent ce) {
            if (autoDeploySupported) {
                deployPortlet.setValue(true);
                doCloseParent = true;
                submitAfterValidation(portletDefinitionField);
            } else {
                doCloseParent = false;
                Window.open(getAppserverDeployerUrl(), "_blank", "");
            }
        }
    });
    addButton(deployButton);

    if (autoDeploySupported) {
        Button prepareAndDeployButton = new Button(
                Messages.get("label.prepareAndDeployWar", "Prepare and deploy"));
        prepareAndDeployButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
            @Override
            public void componentSelected(ButtonEvent ce) {
                deployPortlet.setValue(true);
                preparePortlet.setValue(true);
                doCloseParent = true;
                submitAfterValidation(portletDefinitionField);

            }
        });
        addButton(prepareAndDeployButton);

    }

    Button helpButton = new Button("?");
    helpButton.setWidth(30);
    helpButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
        public void componentSelected(ButtonEvent buttonEvent) {
            deployPortlet.setValue(false);
            preparePortlet.setValue(false);
            doCloseParent = false;
            submit();
        }
    });
    addButton(helpButton);

    final FormPanel form = this;

    addListener(Events.BeforeSubmit, new Listener<FormEvent>() {
        public void handleEvent(FormEvent formEvent) {
            form.mask(Messages.get("label.loading", "Loading..."));
        }
    });
    addListener(Events.Submit, new Listener<FormEvent>() {
        public void handleEvent(FormEvent formEvent) {
            if (doCloseParent) {
                closeParent();
            }
            HTML responseHTML = new HTML(formEvent.getResultHtml());
            String response = responseHTML.getText();

            if (!response.trim().isEmpty()) {
                JSONValue rspValue = JSONParser.parseStrict(response);
                if (rspValue != null && rspValue.isObject() != null
                        && rspValue.isObject().containsKey("dspMsg")) {
                    String dspMsg = rspValue.isObject().get("dspMsg").isString().stringValue();
                    MessageBox.info(Messages.get("label.deployNewPortlet", "Deploy new portlets"), dspMsg,
                            new Listener<MessageBoxEvent>() {
                                public void handleEvent(MessageBoxEvent be) {
                                    refreshParent();
                                }
                            });
                }
            }
            form.unmask();
        }
    });

    layout();
}

From source file:org.jboss.bpm.console.client.process.JSONTree.java

License:Open Source License

private void parseObject(TreeItem root, String key, JSONValue topLevel) {
    JSONObject rootJSO = topLevel.isObject();
    if (null == rootJSO)
        throw new IllegalArgumentException("Not a JSON object: " + topLevel);

    for (String innerKey : rootJSO.keySet()) {
        JSONValue jsonValue = rootJSO.get(innerKey);
        if (jsonValue.isObject() != null) {
            parseObject(root, innerKey, jsonValue);
        } else if (jsonValue.isArray() != null) {
            parseArray(root, innerKey, jsonValue);
        } else {/*from   ww w  .j  a  va 2 s.  c o  m*/
            parseValue(root, innerKey, jsonValue);
        }
    }
}

From source file:org.jboss.dmr.client.dispatch.impl.UploadResponse.java

License:Open Source License

private String extractFailure(final JSONObject response) {
    String failure = "n/a";
    JSONValue failureValue = response.get(FAILURE_DESCRIPTION);
    if (failureValue.isString() != null) {
        failure = failureValue.isString().stringValue();
    } else if (failureValue.isObject() != null) {
        JSONObject failureObject = failureValue.isObject();
        for (String key : failureObject.keySet()) {
            if (key.contains("failure") && failureObject.get(key).isString() != null) {
                failure = failureObject.get(key).isString().stringValue();
                break;
            }//from w w w.  j  av  a  2s.co m
        }
    }
    return failure;
}

From source file:org.jboss.errai.common.client.json.JSONDecoderCli.java

License:Apache License

private static Object _decode(JSONValue v, DecodingContext ctx) {
    if (v.isString() != null) {
        return v.isString().stringValue();
    } else if (v.isNumber() != null) {
        return v.isNumber().doubleValue();
    } else if (v.isBoolean() != null) {
        return v.isBoolean().booleanValue();
    } else if (v.isNull() != null) {
        return null;
    } else if (v instanceof JSONObject) {
        return decodeObject(v.isObject(), ctx);
    } else if (v instanceof JSONArray) {
        return decodeList(v.isArray(), ctx);
    } else {/*from w  w w  .j a  va  2s.  c o m*/
        throw new RuntimeException("unknown encoding");
    }
}

From source file:org.jboss.errai.common.client.types.JSONTypeHelper.java

License:Apache License

public static Object convert(JSONValue value, Class to, DecodingContext ctx) {
    JSONValue v;//  w ww  .j a  v a 2s  . c o m
    if ((v = value.isString()) != null) {
        return TypeHandlerFactory.convert(String.class, to, ((JSONString) v).stringValue(), ctx);
    } else if ((v = value.isNumber()) != null) {
        return TypeHandlerFactory.convert(Number.class, to, ((JSONNumber) v).doubleValue(), ctx);
    } else if ((v = value.isBoolean()) != null) {
        return TypeHandlerFactory.convert(Boolean.class, to, ((JSONBoolean) v).booleanValue(), ctx);
    } else if ((v = value.isArray()) != null) {
        List list = new ArrayList();
        JSONArray arr = (JSONArray) v;

        Class cType = to.getComponentType();

        while (cType != null && cType.getComponentType() != null)
            cType = cType.getComponentType();

        if (cType == null)
            cType = to;

        Object o;
        for (int i = 0; i < arr.size(); i++) {
            if ((o = convert(arr.get(i), cType, ctx)) instanceof UnsatisfiedForwardLookup) {
                ctx.addUnsatisfiedDependency(list, (UnsatisfiedForwardLookup) o);
            } else {
                list.add(convert(arr.get(i), cType, ctx));
            }
        }

        Object t = TypeHandlerFactory.convert(Collection.class, to, list, ctx);

        ctx.swapDepReference(list, t);

        return t;
    } else if ((v = value.isObject()) != null) {
        JSONObject eMap = (JSONObject) v;

        Map<Object, Object> m = new UHashMap<Object, Object>();
        Object o;
        Object val;

        for (String key : eMap.keySet()) {
            o = key;
            if (key.startsWith(SerializationParts.EMBEDDED_JSON)) {
                o = JSONDecoderCli.decode(key.substring(SerializationParts.EMBEDDED_JSON.length()), ctx);
            } else if (SerializationParts.ENCODED_TYPE.equals(key)) {
                String className = eMap.get(key).isString().stringValue();
                String objId = null;
                if ((v = eMap.get(SerializationParts.OBJECT_ID)) != null) {
                    objId = v.isString().stringValue();
                }

                boolean ref = false;
                if (objId != null) {
                    if (objId.charAt(0) == '$') {
                        ref = true;
                        objId = objId.substring(1);
                    }

                    if (ctx.hasObject(objId)) {
                        return ctx.getObject(objId);
                    } else if (ref) {
                        return new UnsatisfiedForwardLookup(objId);
                    }
                }

                if (TypeDemarshallers.hasDemarshaller(className)) {
                    o = TypeDemarshallers.getDemarshaller(className).demarshall(eMap, ctx);
                    if (objId != null)
                        ctx.putObject(objId, o);
                    return o;
                } else {
                    throw new RuntimeException("no available demarshaller: " + className);
                }
            }

            val = JSONDecoderCli.decode(eMap.get(key), ctx);
            boolean commit = true;

            if (o instanceof UnsatisfiedForwardLookup) {
                ctx.addUnsatisfiedDependency(m, (UnsatisfiedForwardLookup) o);
                if (!(val instanceof UnsatisfiedForwardLookup)) {
                    ((UnsatisfiedForwardLookup) o).setVal(val);
                }
                commit = false;
            }
            if (val instanceof UnsatisfiedForwardLookup) {
                ((UnsatisfiedForwardLookup) val).setKey(o);
                ctx.addUnsatisfiedDependency(m, (UnsatisfiedForwardLookup) val);
                commit = false;
            }

            if (commit) {
                m.put(o, JSONDecoderCli.decode(eMap.get(key), ctx));
            }

        }

        return TypeHandlerFactory.convert(Map.class, to, m, ctx);
    }

    return null;
}

From source file:org.jboss.errai.enterprise.client.jaxrs.JacksonTransformer.java

License:Apache License

/**
 * The transformation from Errai JSON to Jackson's JSON contains the following steps:
 * <ul>/*ww w.jav  a2 s  . c o  m*/
 * <li>For all JSON objects, recursively remove the Errai specific OBJECT_ID and ENCODED_TYPE
 * values</li>
 * <li>Keep a reference to the removed OBJECT_IDs, so back-references can be resolved</li>
 * <li>If an array is encountered, process all its elements, then remove the Errai specific
 * QUALIFIED_VALUE key, by associating its actual value with the object's key directly: "list":
 * {"^Value": ["e1","e2"]} becomes "list": ["e1","e2"]</li>
 * <li>If an enum is encountered, remove the Errai specific ENUM_STRING_VALUE key, by associating
 * its actual value with the object's key directly: "gender": {"^EnumStringValue": "MALE"} becomes
 * "gender": "MALE"</li>
 * <li>If a number is encountered, remove the Errai specific NUMERIC_VALUE key, by associating its
 * actual value with the object's key directly: "id": {"^NumValue": "1"} becomes "id": "1"</li>
 * <li>If a date is encountered, remove the Errai specific QUALIFIED_VALUE key, by associating its
 * actual value with the object's key directly and turning it into a JSON number</li>
 * <li>If EMBEDDED_JSON is encountered, turn in into standard json</li>
 * </ul>
 * 
 * @param val
 *          the JSON value to transform
 * @param key
 *          the key of the JSON value to transform
 * @param parent
 *          the parent object of the current value
 * @param objectCache
 *          a cache for removed objects, that is used to resolve backreferences
 * @return the modified JSON value
 */
private static JSONValue toJackson(JSONValue val, String key, JSONObject parent,
        Map<String, JSONValue> objectCache) {
    JSONObject obj;
    if ((obj = val.isObject()) != null) {
        JSONValue objectIdVal = obj.get(OBJECT_ID);
        if (objectIdVal != null) {
            String objectId = objectIdVal.isString().stringValue();
            if (!objectId.equals("-1")) {
                JSONValue backRef = objectCache.get(objectId);
                if (backRef != null) {
                    if (parent != null) {
                        parent.put(key, backRef);
                    } else {
                        return backRef.isObject();
                    }
                } else {
                    objectCache.put(objectId, obj);
                }
            }
        }

        JSONValue encType = obj.get(ENCODED_TYPE);
        obj.put(OBJECT_ID, null);
        obj.put(ENCODED_TYPE, null);

        for (String k : obj.keySet()) {
            JSONArray arr;
            if ((arr = obj.get(k).isArray()) != null) {
                for (int i = 0; i < arr.size(); i++) {
                    if (arr.get(i).isObject() != null && arr.get(i).isObject().get(NUMERIC_VALUE) != null) {
                        arr.set(i, arr.get(i).isObject().get(NUMERIC_VALUE));
                    } else if (arr.get(i).isObject() != null) {
                        arr.set(i, toJackson(arr.get(i), null, null, objectCache));
                    }
                }

                if (k.equals(QUALIFIED_VALUE)) {
                    if (parent != null) {
                        parent.put(key, arr);
                    } else {
                        return arr;
                    }
                }
            } else if (k.equals(ENUM_STRING_VALUE) || k.equals(NUMERIC_VALUE)) {
                if (parent != null) {
                    parent.put(key, obj.get(k));
                }
            } else if (k.equals(QUALIFIED_VALUE)) {
                if (parent != null) {
                    if (encType.isString().stringValue().equals("java.util.Date")) {
                        String dateValue = obj.get(k).isString().stringValue();
                        parent.put(key, new JSONNumber(Double.parseDouble(dateValue)));
                    } else {
                        parent.put(key, obj.get(k));
                    }
                }
            } else if (k.startsWith(SerializationParts.EMBEDDED_JSON)) {
                final JSONValue newKey = JSONParser
                        .parseStrict((k.substring(SerializationParts.EMBEDDED_JSON.length())));
                JSONValue value = obj.get(k);
                JSONObject tmpObject = new JSONObject();
                toJackson(newKey, QUALIFIED_VALUE, tmpObject, objectCache);

                String embeddedKey = null;
                JSONValue qualVal = tmpObject.get(QUALIFIED_VALUE);
                if (qualVal.isString() != null) {
                    embeddedKey = qualVal.isString().stringValue();
                } else {
                    embeddedKey = qualVal.toString();
                }
                obj.put(embeddedKey, value);
            }

            toJackson(obj.get(k), k, obj, objectCache);
        }
    }

    return cleanUpEmbeddedJson(obj);
}

From source file:org.jboss.errai.enterprise.client.jaxrs.JacksonTransformer.java

License:Apache License

/**
 * The transformation from Jackson's JSON to Errai JSON contains the following steps:
 * <ul>//w w w  .  ja v  a  2 s .  c  o  m
 * <li>Recursively add an incremented OBJECT_ID to every JSON object</li>
 * <li>If a number is encountered, wrap it in a new JSON object with an OBJECT_ID and
 * NUMERIC_VALUE property</li>
 * <li>If an array is encountered, wrap it in a new JSON object with an OBJECT_ID and
 * QUALIFIED_VALUE property</li>
 * </ul>
 * 
 * @param val
 *          the JSON value to transform
 * @param key
 *          the key of the JSON value to transform
 * @param parent
 *          the parent object of the current value
 * @param objectId
 *          last used object id
 * @return modified JSON value
 */
private static JSONValue fromJackson(JSONValue val, String key, JSONObject parent, int[] objectId) {
    JSONObject obj;
    JSONNumber num;
    JSONArray arr;

    if ((obj = val.isObject()) != null) {
        obj.put(OBJECT_ID, new JSONString(new Integer(++objectId[0]).toString()));

        for (String k : obj.keySet()) {
            fromJackson(obj.get(k), k, obj, objectId);
        }
    } else if ((num = val.isNumber()) != null) {
        JSONObject numObject = new JSONObject();
        numObject.put(OBJECT_ID, new JSONString(new Integer(++objectId[0]).toString()));
        numObject.put(NUMERIC_VALUE, num);
        if (parent != null) {
            parent.put(key, numObject);
        } else {
            val = numObject;
        }
    } else if ((arr = val.isArray()) != null) {
        JSONObject arrayObject = new JSONObject();
        arrayObject.put(OBJECT_ID, new JSONString(new Integer(++objectId[0]).toString()));
        arrayObject.put(QUALIFIED_VALUE, arr);
        if (parent != null) {
            parent.put(key, arrayObject);
        } else {
            val = arrayObject;
        }

        for (int i = 0; i < arr.size(); i++) {
            arr.set(i, fromJackson(arr.get(i), QUALIFIED_VALUE, null, objectId));
        }
    }

    return val;
}

From source file:org.jboss.errai.jpa.client.local.ErraiIdentifiableType.java

License:Apache License

/**
 * Converts the given JSONValue, which represents an instance of this entity
 * type, into the actual instance of this entity type that exists in the given
 * EntityManager's persistence context. References to other entities are
 * recursively retrieved from the EntityManager.
 *
 * @param em/*from www  .  j  a v  a2s  . com*/
 *          The EntityManager that owns this entity type and houses the
 *          persistence context.
 * @param jsonValue
 *          A value that represents an instance of this entity type.
 * @return A managed entity that is in the given EntityManager's persistence
 *         context.
 */
@Override
public X fromJson(EntityManager em, JSONValue jsonValue) {
    final ErraiEntityManager eem = (ErraiEntityManager) em;

    Key<X, ?> key = keyFromJson(jsonValue);

    X entity = eem.getPartiallyConstructedEntity(key);
    if (entity != null) {
        return entity;
    }

    entity = newInstance();
    try {
        eem.putPartiallyConstructedEntity(key, entity);
        for (Attribute<? super X, ?> a : getAttributes()) {
            ErraiAttribute<? super X, ?> attr = (ErraiAttribute<? super X, ?>) a;
            JSONValue attrJsonValue = jsonValue.isObject().get(attr.getName());

            // this attribute did not exist when the entity was originally persisted; skip it.
            if (attrJsonValue == null)
                continue;

            switch (attr.getPersistentAttributeType()) {
            case ELEMENT_COLLECTION:
            case EMBEDDED:
            case BASIC:
                parseInlineJson(entity, attr, attrJsonValue, eem);
                break;

            case MANY_TO_MANY:
            case MANY_TO_ONE:
            case ONE_TO_MANY:
            case ONE_TO_ONE:
                if (attr instanceof ErraiSingularAttribute) {
                    parseSingularJsonReference(entity, (ErraiSingularAttribute<? super X, ?>) attr,
                            attrJsonValue, eem);
                } else if (attr instanceof ErraiPluralAttribute) {
                    parsePluralJsonReference(entity, (ErraiPluralAttribute<? super X, ?, ?>) attr,
                            attrJsonValue.isArray(), eem);
                } else {
                    throw new PersistenceException("Unknown attribute type " + attr);
                }
            }
        }
        return entity;
    } finally {
        eem.removePartiallyConstructedEntity(key);
    }
}

From source file:org.jboss.errai.jpa.client.local.ErraiIdentifiableType.java

License:Apache License

private Key<X, ?> keyFromJson(JSONValue json) {
    JSONValue keyJson = json.isObject().get(id.getName());
    Object idValue = JsonUtil.basicValueFromJson(keyJson, id.getJavaType());
    return new Key<X, Object>(this, idValue);
}