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:com.smartgwt.mobile.client.data.DSResponse.java

License:Open Source License

DSResponse(DSRequest dsRequest, int status, JSONObject responseObj) {
    init(dsRequest);/*w ww.j  a v a 2 s. co m*/
    Map<String, String> errors = null;

    if (responseObj != null) {
        JSONValue val = responseObj.get("status");
        JSONNumber num = (val == null ? null : val.isNumber());
        if (num != null) {
            status = (int) num.doubleValue();
        }
        val = responseObj.get("startRow");
        num = (val == null ? null : val.isNumber());
        if (num != null) {
            setStartRow(Integer.valueOf((int) num.doubleValue()));
        }
        val = responseObj.get("endRow");
        num = (val == null ? null : val.isNumber());
        if (num != null) {
            setEndRow(Integer.valueOf((int) num.doubleValue()));
        }
        val = responseObj.get("totalRows");
        num = (val == null ? null : val.isNumber());
        if (num != null) {
            setTotalRows(Integer.valueOf((int) num.doubleValue()));
        }
        val = responseObj.get("errors");
        JSONObject errorsObj = (val == null ? null : val.isObject());
        if (errorsObj != null) {
            errors = new HashMap<String, String>();
            for (final String key : errorsObj.keySet()) {
                val = errorsObj.get(key);
                if (val == null || val.isNull() != null)
                    continue;
                final String errorMessage;
                JSONString str = val.isString();
                if (str != null)
                    errorMessage = str.stringValue();
                else
                    errorMessage = val.toString();
                errors.put(key, errorMessage);
            }
        }
    }

    setStatus(status);
    if (errors != null)
        setErrors(errors);

    // No need to handle the response data here.
}

From source file:com.tasktop.c2c.server.tasks.client.presenters.EditTaskPresenter.java

License:Open Source License

private void handleAttachmentUploadResultJson(String json) {
    JSONValue value = JSONParser.parseLenient(json);
    JSONValue uploadResultValue = value.isObject().get("uploadResult");
    JSONObject uploadResult = uploadResultValue == null ? null
            : value.isObject().get("uploadResult").isObject();

    if (uploadResult != null) {
        // update the taskHandle for the task
        TaskHandle taskHandle = buildTaskHandle(uploadResult);
        task.setTaskHandle(taskHandle);/*from  w w w  .  ja  va 2 s  .c o m*/
        // update the the hidden taskHandle field
        editTaskView.getAttachmentDisplay()
                .setValueHiddenTaskValue(AttachmentUploadUtil.createTaskHandleValue(taskHandle));

        // update the attachments table
        JSONArray attachments = uploadResult.get("attachments").isArray();
        JSONObject attachmentJSON = attachments.get(0).isObject();
        Attachment newAttachment = buildAttachment(attachmentJSON);
        addAttachment(newAttachment);

        // reset the attachment upload form
        editTaskView.getAttachmentDisplay().resetForm();

    } else {
        String message = super.tasksMessages.unexpectedServerResponse();
        JSONValue errorValue = value.isObject().get("error");
        JSONObject errorObject = errorValue == null ? null : errorValue.isObject();
        if (errorObject != null) {
            JSONString errorMessage = errorObject.get("message").isString();
            if (errorMessage != null) {
                message = errorMessage.stringValue();
            }
        }
        ProfileGinjector.get.instance().getNotifier().displayMessage(Message.createErrorMessage(message));
    }
}

From source file:com.tasktop.c2c.server.wiki.web.ui.client.presenter.EditWikiPagePresenter.java

License:Open Source License

private void attachmentsSubmitted(SubmitCompleteEvent event) {
    JSONValue value = JSONParser.parseLenient(event.getResults());
    JSONValue uploadResultValue = value.isObject().get("uploadResult");
    JSONObject uploadResult = uploadResultValue == null ? null
            : value.isObject().get("uploadResult").isObject();
    if (uploadResult != null) {
        // get updated modification stamp and list of attachments
        JSONObject updatedPage = uploadResult.get("page") == null ? null : uploadResult.get("page").isObject();
        if (updatedPage != null) {
            JSONNumber number = updatedPage.get("modificationDate") == null ? null
                    : updatedPage.get("modificationDate").isNumber();
            if (number != null) {
                page.setModificationDate(new Date(new Long(number.toString())));
            }/*from  ww w .j a  v  a  2 s  .  co  m*/
        }
        ProfileGinjector.get.instance().getNotifier().displayMessage(Message
                .createSuccessMessage(super.wikiMessages.attachmentUploaded(view.getAttachmentFileName())));
        getEventBus().fireEvent(new ClearCacheEvent());
        view.clearAttachementForm();
        // Ideally we would simply update with the results for the json content.
        fetchAttachments();
    } else {
        String message = super.commonProfileMessages.unexpectedServerResponse();
        JSONValue errorValue = value.isObject().get("error");
        JSONObject errorObject = errorValue == null ? null : errorValue.isObject();
        if (errorObject != null) {
            JSONString errorMessage = errorObject.get("message").isString();
            if (errorMessage != null) {
                message = errorMessage.stringValue();
            }
        }
        ProfileGinjector.get.instance().getNotifier().displayMessage(Message.createErrorMessage(message));
    }
}

From source file:com.teardrop.client.JSONFunctions.java

License:Apache License

public static String getJSONSetValue(JSONValue jsonValue, String name) {
    JSONObject jsonObject;/*  w  ww .  j  a va 2  s  .  co  m*/
    JSONString jsonString;
    if ((jsonObject = jsonValue.isObject()) != null) {
        Set keys = jsonObject.keySet();
        for (Iterator iter = keys.iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            if (key.equals(name))
                if ((jsonString = jsonObject.get(key).isString()) != null) {
                    return jsonString.stringValue();
                }
        }
    }
    return null;
}

From source file:com.teardrop.client.JSONFunctions.java

License:Apache License

public static JSONValue getJSONSet(JSONValue jsonValue, String name) {
    JSONObject jsonObject;/*  www .j  a  va2s  .com*/
    if ((jsonObject = jsonValue.isObject()) != null) {
        Set keys = jsonObject.keySet();
        for (Iterator iter = keys.iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            if (key.equals(name))
                return jsonObject.get(key);
        }
    }
    return null;
}

From source file:com.vaadin.client.communication.JsonDecoder.java

License:Apache License

private static Object decodeObject(Type type, JSONValue jsonValue, Object target,
        ApplicationConnection connection) {
    Profiler.enter("JsonDecoder.decodeObject");
    JSONSerializer<Object> serializer = (JSONSerializer<Object>) type.findSerializer();
    if (serializer != null) {
        if (target != null && serializer instanceof DiffJSONSerializer<?>) {
            DiffJSONSerializer<Object> diffSerializer = (DiffJSONSerializer<Object>) serializer;
            diffSerializer.update(target, type, jsonValue, connection);
            Profiler.leave("JsonDecoder.decodeObject");
            return target;
        } else {//from w  ww  .  j a  v  a2  s  . co  m
            Object object = serializer.deserialize(type, jsonValue, connection);
            Profiler.leave("JsonDecoder.decodeObject");
            return object;
        }
    } else {
        try {
            Profiler.enter("JsonDecoder.decodeObject meta data processing");
            JsArrayObject<Property> properties = type.getPropertiesAsArray();
            if (target == null) {
                target = type.createInstance();
            }
            JSONObject jsonObject = jsonValue.isObject();

            int size = properties.size();
            for (int i = 0; i < size; i++) {
                Property property = properties.get(i);
                JSONValue encodedPropertyValue = jsonObject.get(property.getName());
                if (encodedPropertyValue == null) {
                    continue;
                }

                Type propertyType = property.getType();

                Object propertyReference;
                if (needsReferenceValue(propertyType)) {
                    propertyReference = property.getValue(target);
                } else {
                    propertyReference = null;
                }

                Profiler.leave("JsonDecoder.decodeObject meta data processing");
                Object decodedValue = decodeValue(propertyType, encodedPropertyValue, propertyReference,
                        connection);
                Profiler.enter("JsonDecoder.decodeObject meta data processing");
                property.setValue(target, decodedValue);
            }
            Profiler.leave("JsonDecoder.decodeObject meta data processing");
            Profiler.leave("JsonDecoder.decodeObject");
            return target;
        } catch (NoDataException e) {
            Profiler.leave("JsonDecoder.decodeObject meta data processing");
            Profiler.leave("JsonDecoder.decodeObject");
            throw new RuntimeException("Can not deserialize " + type.getSignature(), e);
        }
    }
}

From source file:cz.cas.lib.proarc.webapp.client.ErrorHandler.java

License:Open Source License

/**
 * Creates response object from JSON response string in
 * {@link com.smartgwt.client.data.RestDataSource SmartGWT format}.
 * @param response JSON response string/*from w w w .j  av a 2  s.c o  m*/
 * @return response object
 */
public static DSResponse getDsResponse(String response) {
    DSResponse dsResponse;
    //        ClientUtils.info(LOG, "response: %s", response);
    if (response == null || response.isEmpty()) {
        // not JSON response
        LOG.log(Level.WARNING, null, new IllegalStateException("Empty response!"));
        dsResponse = new DSResponse();
        dsResponse.setStatus(RPCResponse.STATUS_SUCCESS);
    } else {
        JSONValue rVal = JSONParser.parseStrict(response);
        if (rVal.isObject() != null) {
            rVal = rVal.isObject().get("response");
        }
        if (rVal != null && rVal.isObject() != null) {
            JSONObject rObj = rVal.isObject();
            dsResponse = DSResponse.getOrCreateRef(rObj.getJavaScriptObject());
        } else {
            // not JSON response in expected format
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", new JSONString(response));
            dsResponse = new DSResponse(jsonObject.getJavaScriptObject());
            dsResponse.setStatus(RPCResponse.STATUS_FAILURE);
        }
    }
    return dsResponse;
}

From source file:cz.cas.lib.proarc.webapp.client.presenter.JsonTokenizer.java

License:Open Source License

public static JSONObject parseObject(String token) {
    JSONValue val = parse(token);
    return val == null ? null : val.isObject();
}

From source file:de.cau.klay.gwt.client.layout.KlayNoFloLayouter.java

License:Open Source License

public static String klayLayout(String s) {
    JSONValue jsonValue = JSONParser.parseStrict(s);
    JSONObject jsonObj = jsonValue.isObject();

    // *** Encode noflo JSON to KGraph ***

    // Create and configure the root node
    KNode rootNode = KimlUtil.createInitializedNode();
    KShapeLayout rootLayout = rootNode.getData(KShapeLayout.class);
    // Set layout direction to horizontal
    rootLayout.setProperty(LayoutOptions.DIRECTION, Direction.RIGHT);
    // Set overall element spacing
    rootLayout.setProperty(LayoutOptions.SPACING, 25f);
    rootLayout.setProperty(Properties.NODE_PLACER, NodePlacementStrategy.LINEAR_SEGMENTS);

    // Use an auxiliary hashmap to store nodes/processes id's
    HashMap<String, KNode> auxNodes = new HashMap<String, KNode>();
    HashMap<KNode, String> auxProcesses = new HashMap<KNode, String>();

    // TODO: Encode groups

    // Encode nodes (processes on noflo)
    if (jsonObj.containsKey("processes")) {
        JSONObject processes = jsonObj.get("processes").isObject();
        Set<String> keys = processes.keySet();

        for (String key : keys) {
            // Get process information from noflo JSON
            JSONObject process = processes.get(key).isObject();

            // Create a child node for the root node
            KNode childNode = KimlUtil.createInitializedNode();
            // This automatically adds the child to the list of its parent's
            // children
            childNode.setParent(rootNode);
            // Configure the child node
            KLabel nodeLabel = KimlUtil.createInitializedLabel(childNode);
            nodeLabel.setText(process.get("metadata").isObject().get("label").isString().stringValue());

            KShapeLayout childLayout = childNode.getData(KShapeLayout.class);
            // Set width and height for the node
            childLayout.setWidth(92.0f);
            childLayout.setHeight(72.0f);
            // set port constraints to fixed port positions
            childLayout.setProperty(LayoutOptions.PORT_CONSTRAINTS, PortConstraints.FIXED_POS);
            childLayout.setProperty(Properties.NODE_PLACER, NodePlacementStrategy.LINEAR_SEGMENTS);

            // Store the nodes's reference to make possible to access by it's process id in the future
            auxNodes.put(key, childNode);
            // TODO: Maybe we can do better than this...
            auxProcesses.put(childNode, key);

            // TODO: Encode ports for the child node
        }/*from   w  w w  .  j  ava  2s.  c o  m*/
    }

    // Encode edges (connections on noflo)
    if (jsonObj.containsKey("connections")) {
        JSONArray connections = jsonObj.get("connections").isArray();
        if (connections != null) {
            for (int i = 0; i < connections.size(); i++) {
                // Get connection information from noflo JSON
                JSONObject connection = connections.get(i).isObject();
                if (connection.containsKey("data")) {
                    continue;
                }

                JSONObject processSrc = connection.get("src").isObject();
                String srcProcId = processSrc.get("process").isString().stringValue();
                String srcPortId = processSrc.get("port").isString().stringValue();

                JSONObject processTgt = connection.get("tgt").isObject();
                String tgtProcId = processTgt.get("process").isString().stringValue();
                String tgtPortId = processTgt.get("port").isString().stringValue();

                // Find the source and target nodes which references are stored in our auxiliary dict/map
                KNode srcNode = auxNodes.get(srcProcId);
                // TODO: Encode port! KPort srcPort = srcNode.getPorts();
                KNode tgtNode = auxNodes.get(tgtProcId);
                // TODO: Encode port! KPort tgtPort = tgtNode.getPorts();

                // Create edge
                KEdge edge = KimlUtil.createInitializedEdge();
                // This automatically adds the edge to the node's list of outgoing
                // edges
                edge.setSource(srcNode);
                // this automatically adds the edge to the node's list of incoming
                // edges.
                edge.setTarget(tgtNode);
                // this automatically adds the edge to the port's list of edges
                // TODO: Encode port! edge.setSourcePort(srcPort);
                // TODO: Encode port! edge.setTargetPort(tgtPort);

            }

        }
    }

    // *** Apply the layouter ***

    // Create a progress monitor
    IKielerProgressMonitor progressMonitor = new BasicProgressMonitor();

    // Create the layout provider
    AbstractLayoutProvider layoutProvider = new LayeredLayoutProvider();

    // Perform layout on the created graph
    layoutProvider.doLayout(rootNode, progressMonitor);

    // *** Decode back KGraph to noflo JSON ***

    // Loop through all root nodes' children and update the respective processes nodes
    for (KNode childNode : rootNode.getChildren()) {
        KShapeLayout childLayout = childNode.getData(KShapeLayout.class);

        // Find the process in the noflo JSON
        String processId = auxProcesses.get(childNode);

        JSONObject processes = jsonObj.get("processes").isObject();
        JSONObject process = processes.get(processId).isObject();

        // Updates process metadata in the noflo JSON
        // TODO: How to convert a String to JSONValue without using the deprecated parse method?
        process.get("metadata").isObject().put("x", JSONParser.parse(Float.toString(childLayout.getXpos())));
        process.get("metadata").isObject().put("y", JSONParser.parse(Float.toString(childLayout.getYpos())));
    }

    // Convert the noflo JSON to a serialized String and return
    return jsonObj.toString();
}

From source file:de.eckhartarnold.client.ImageCollectionReader.java

License:Apache License

private HashMap<String, int[][]> interpretSizes(JSONValue json) throws JSONException {
    HashMap<String, int[][]> resolutions = new HashMap<String, int[][]>();
    HashMap<String, int[][]> sizes = new HashMap<String, int[][]>();
    JSONObject dict = json.isObject();
    JSONArray array = json.isArray();/*from   w w w . jav  a  2  s . co m*/

    if (array != null) {
        JSONObject resDict = array.get(0).isObject();
        for (String key : resDict.keySet()) {
            JSONArray resSet = resDict.get(key).isArray();
            resolutions.put(key, interpretResolutionsArray(resSet));
        }
        dict = array.get(1).isObject();
    }

    for (String key : dict.keySet()) {
        //      JSONArray list = dict.get(key).isArray();
        //      resolutions.clear();
        //      for (int i = 0; i < list.size(); i++ ) {
        //        JSONArray xy = list.get(i).isArray();
        //        int res[] = new int[2];
        //        res[0] = (int) xy.get(0).isNumber().doubleValue();
        //        res[1] = (int) xy.get(1).isNumber().doubleValue();
        //        resolutions.add(res);
        //      }
        //      sizes.put(key, resolutions.toArray(new int[resolutions.size()][]));
        JSONValue value = dict.get(key);
        array = value.isArray();
        if (array != null) {
            sizes.put(key, interpretResolutionsArray(array));
        } else {
            sizes.put(key, resolutions.get(value.isString().stringValue()));
        }
    }
    return sizes;
}