Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

In this page you can find the example usage for org.json JSONObject get.

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:ui.panel.UILicenseAdd.java

private JPanel createPnlFeature() {
    JPanel panel = p.createPanel(Layouts.gridbag);

    GridBagConstraints g = new GridBagConstraints();
    lblSelectFeature = l.createLabel("Select Features", SwingConstants.LEFT);
    g.gridx = 0;/*  w ww.  j a v a 2s. c om*/
    g.gridy = 0;
    g.gridwidth = 2;
    g.insets = new Insets(5, 5, 5, 5);
    panel.add(lblSelectFeature, g);

    lblServiceApi = l.createLabel("Service APIs Used", SwingConstants.LEFT);
    g.gridx = 4;
    g.gridy = 0;
    g.gridwidth = 2;
    g.insets = new Insets(5, 5, 5, 5);
    panel.add(lblServiceApi, g);
    getFeaturesData();
    DefaultMutableTreeNode root = new MyDataNode("Features", "Features");
    for (String key : Data.featureList.keySet()) {
        try {
            DefaultMutableTreeNode element = new MyDataNode(key, Data.fieldNames.get(key));

            JSONArray features = Data.featureList.get(key);
            ArrayList<DefaultMutableTreeNode> arrayFeatureCheckBox = new ArrayList<DefaultMutableTreeNode>();

            for (int i = 0; i < features.length(); i++) {
                JSONObject feature = features.getJSONObject(i);
                DefaultMutableTreeNode featureElement = new MyDataNode((String) feature.get("name"),
                        Data.fieldNames.get(feature.get("name")));
                element.add(featureElement);
                arrayFeatureCheckBox.add(featureElement);
            }

            root.add(element);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    tree = new JTree(root);
    tree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = tree.getSelectionModel().getSelectionPath();
            model.removeAllElements();
            String item = tree.getSelectionModel().getSelectionPath().getLastPathComponent().toString();
            MyDataNode node = (MyDataNode) tree.getSelectionModel().getSelectionPath().getLastPathComponent();
            String selected = node.getValue();
            servicesList = new HashMap<String, String>();
            try {
                if (selected.equalsIgnoreCase("Features")) {
                    for (String key : Data.featureList.keySet()) {
                        JSONArray featureArray = Data.featureList.get(key);

                        for (int i = 0; i < featureArray.length(); i++) {
                            JSONArray servicesArray = featureArray.getJSONObject(i).getJSONArray("services");

                            for (int x = 0; x < servicesArray.length(); x++) {
                                servicesList.put(Integer.toString(servicesArray.getJSONObject(x).getInt("id")),
                                        servicesArray.getJSONObject(x).getString("name"));
                            }
                        }
                    }
                } else if (path.getPathCount() == 2) {
                    for (String key : Data.featureList.keySet()) {
                        if (key.equals(selected)) {
                            JSONArray featureArray = Data.featureList.get(key);

                            for (int i = 0; i < featureArray.length(); i++) {
                                JSONArray servicesArray = featureArray.getJSONObject(i)
                                        .getJSONArray("services");

                                for (int x = 0; x < servicesArray.length(); x++) {
                                    servicesList.put(
                                            Integer.toString(servicesArray.getJSONObject(x).getInt("id")),
                                            servicesArray.getJSONObject(x).getString("name"));
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                } else {
                    MyDataNode nodePath = (MyDataNode) path.getPathComponent(1);
                    for (String key : Data.featureList.keySet()) {
                        if (key.equals(nodePath.getValue())) {

                            JSONArray featureArray = Data.featureList.get(key);
                            for (int i = 0; i < featureArray.length(); i++) {
                                System.out.println(
                                        featureArray.getJSONObject(i).getString("name") + ":" + selected);
                                if (featureArray.getJSONObject(i).getString("name").equals(selected)) {
                                    JSONArray servicesArray = featureArray.getJSONObject(i)
                                            .getJSONArray("services");
                                    System.out.println(servicesArray);
                                    for (int x = 0; x < servicesArray.length(); x++) {
                                        servicesList.put(
                                                Integer.toString(servicesArray.getJSONObject(x).getInt("id")),
                                                servicesArray.getJSONObject(x).getString("name"));
                                    }
                                } else {
                                    continue;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
            for (String serviceKey : servicesList.keySet()) {
                model.addElement(servicesList.get(serviceKey));
            }
            listServiceUsed.setModel(model);
        }
    });
    checkTreeManager = new CheckTreeManager(tree);

    spTreeCheckBox = new JScrollPane(tree);
    spTreeCheckBox.setPreferredSize(new Dimension(300, 300));
    g.gridx = 0;
    g.gridy = 1;
    g.gridwidth = 3;
    g.anchor = g.LINE_START;
    g.insets = new Insets(5, 5, 5, 5);
    panel.add(spTreeCheckBox, g);

    model = new DefaultListModel<>();
    model.addElement("");
    listServiceUsed = new JList<String>(model);
    spList = new JScrollPane(listServiceUsed);
    spList.setPreferredSize(new Dimension(300, 300));
    g.gridx = 4;
    g.gridy = 1;
    g.gridwidth = 3;
    g.anchor = g.LINE_START;
    panel.add(spList, g);

    return panel;
}

From source file:ui.panel.UILicenseAdd.java

public JPanel createButtonPanel() {
    JPanel panel = p.createPanel(Layouts.flow);
    panel.setLayout(new FlowLayout(FlowLayout.CENTER));

    btnSubmit = b.createButton("Submit");
    btnCancel = b.createButton("Cancel");

    btnSubmit.addActionListener(new ActionListener() {

        @Override/*from w  w w. j  a v a  2 s .  c  o m*/
        public void actionPerformed(ActionEvent e) {

            SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    TreePath[] path = checkTreeManager.getSelectionModel().getSelectionPaths();
                    ArrayList<String> featureL = new ArrayList<String>();
                    String[] features = new String[] {};
                    for (TreePath tp : path) {

                        if (tp.getLastPathComponent().toString().equals("Features")) {
                            Object rootNode = tree.getModel().getRoot();
                            int parentCount = tree.getModel().getChildCount(rootNode);
                            for (int i = 0; i < parentCount; i++) {
                                Object parentNode = tree.getModel().getChild(rootNode, i);
                                int childrenCount = tree.getModel().getChildCount(parentNode);

                                for (int x = 0; x < childrenCount; x++) {
                                    MyDataNode node = (MyDataNode) tree.getModel().getChild(parentNode, x);
                                    featureL.add(node.getValue());
                                }
                            }
                        } else if (tp.getPathCount() == 2) {
                            Object rootNode = tree.getModel().getRoot();
                            int parentCount = tree.getModel().getChildCount(rootNode);
                            for (int i = 0; i < parentCount; i++) {
                                Object parentNode = tree.getModel().getChild(rootNode, i);
                                if (parentNode.toString().equals(tp.getLastPathComponent().toString())) {

                                    int childrenCount = tree.getModel().getChildCount(parentNode);

                                    for (int x = 0; x < childrenCount; x++) {
                                        MyDataNode node = (MyDataNode) tree.getModel().getChild(parentNode, x);
                                        featureL.add(node.getValue());
                                    }
                                }
                            }
                        } else if (tp.getPathCount() == 3) {
                            MyDataNode node = (MyDataNode) tp.getLastPathComponent();
                            featureL.add(node.getValue());
                        }

                    }
                    features = featureL.toArray(features);
                    String duration = spnValidity.getValue().toString();
                    if (cbPerpetual.isSelected()) {
                        duration = "-1";
                    }
                    String storage = spnCloud.getValue().toString();
                    String maxVCA = spnConcurrentVCA.getValue().toString();
                    String response = apiCall.addNodeLicense(Data.targetURL, Data.sessionKey, Data.bucketID,
                            features, duration, storage, maxVCA);

                    try {
                        JSONObject responseObject = new JSONObject(response);
                        if (responseObject.get("result").equals("ok")) {
                            Data.mainFrame.uiLicenseDetail.getLicenseData();
                            Data.mainFrame.showPanel("license");
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    return null;
                }
            };
            Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource());
            final JDialog dialog = new JDialog(win, "Loading", ModalityType.APPLICATION_MODAL);

            mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals("state")) {
                        if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
                            dialog.dispose();
                        }
                    }
                }
            });
            mySwingWorker.execute();

            JProgressBar progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(progressBar, BorderLayout.CENTER);
            panel.add(new JLabel("Retrieving License..."), BorderLayout.PAGE_START);
            dialog.add(panel);
            dialog.pack();
            dialog.setBounds(50, 50, 300, 100);
            dialog.setLocationRelativeTo(Data.mainFrame);
            dialog.setVisible(true);
        }
    });

    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            Data.mainFrame.showPanel("license");
        }
    });

    panel.add(btnSubmit);
    panel.add(btnCancel);

    return panel;
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private Object executeRawScript(String toExecute) {
    String result = null;/* w ww  . j  av a 2  s. com*/
    /*
     * result = executeJavascriptInWebView("window.webdriver.resultMethod("
     * + toExecute + ")");
     */
    result = executeJavascriptInWebView(toExecute);

    System.out.println("Result === " + result);

    if (result == null || "undefined".equals(result) || "null".equals(result)) {
        return null;
    }
    try {
        JSONObject json = new JSONObject(result);
        throwIfError(json);
        Object value = json.get(VALUE);
        return convertJsonToJavaObject(value);
    } catch (JSONException e) {
        throw new RuntimeException("Failed to parse JavaScript result: " + result.toString(), e);
    }
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private Object convertJsonToJavaObject(final Object toConvert) {
    try {/*from   w ww.j a va 2  s  . c  om*/
        if (toConvert == null || toConvert.equals(null) || "undefined".equals(toConvert)
                || "null".equals(toConvert)) {
            return null;
        } else if (toConvert instanceof Boolean) {
            return toConvert;
        } else if (toConvert instanceof Double || toConvert instanceof Float) {
            return Double.valueOf(String.valueOf(toConvert));
        } else if (toConvert instanceof Integer || toConvert instanceof Long) {
            return Long.valueOf(String.valueOf(toConvert));
        } else if (toConvert instanceof JSONArray) { // List
            return convertJsonArrayToList((JSONArray) toConvert);
        } else if (toConvert instanceof JSONObject) { // Map or WebElment
            JSONObject map = (JSONObject) toConvert;
            if (map.opt(ELEMENT_KEY) != null) { // WebElement
                return getOrCreateWebElement((String) map.get(ELEMENT_KEY));
            } else if (map.opt(WINDOW_KEY) != null) { // DomWindow
                return new DomWindow((String) map.get(WINDOW_KEY));
            } else { // Map
                return convertJsonObjectToMap(map);
            }
        } else {
            return toConvert.toString();
        }
    } catch (JSONException e) {
        throw new RuntimeException("Failed to parse JavaScript result: " + toConvert.toString(), e);
    }
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private Map<Object, Object> convertJsonObjectToMap(final JSONObject json) {
    Map<Object, Object> toReturn = Maps.newHashMap();
    for (Iterator it = json.keys(); it.hasNext();) {
        String key = (String) it.next();
        try {/* w  ww .  j a  v  a2 s.  c o  m*/
            Object value = json.get(key);
            toReturn.put(convertJsonToJavaObject(key), convertJsonToJavaObject(value));
        } catch (JSONException e) {
            throw new RuntimeException("Failed to parse JSON:" + json.toString(), e);
        }
    }
    return toReturn;
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private void throwIfError(final JSONObject jsonObject) {
    int status;//from  w  w  w  .j  av  a  2  s.  c o  m
    String errorMsg;
    try {
        status = (Integer) jsonObject.get(STATUS);
        errorMsg = String.valueOf(jsonObject.get(VALUE));
    } catch (JSONException e) {
        throw new RuntimeException("Failed to parse JSON Object: " + jsonObject, e);
    }
    switch (status) {
    case ErrorCodes.SUCCESS:
        return;
    case ErrorCodes.NO_SUCH_ELEMENT:
        throw new NoSuchElementException("Could not find " + "WebElement.");
    case ErrorCodes.STALE_ELEMENT_REFERENCE:
        throw new StaleElementReferenceException("WebElement is stale.");
    default:
        if (jsonObject.toString()
                .contains("Result of expression 'd.evaluate' [undefined] is" + " not a function.")) {
            throw new WebDriverException("You are using a version of Android WebDriver APK"
                    + " compatible with ICS SDKs or more recent SDKs. For more info take a look at"
                    + " http://code.google.com/p/selenium/wiki/AndroidDriver#Supported_Platforms. Error:" + " "
                    + jsonObject.toString());
        }
        throw new WebDriverException("Error: " + errorMsg);
    }
}

From source file:org.wso2.emm.agent.services.PolicyRevokeHandler.java

/**
 * Revokes Wifi policy on the device (Particular wifi configuration in the policy should be disabled).
 *
 * @param operation - Operation object.//from  w w  w . j  a v a2  s. c om
 */
private void revokeWifiPolicy(org.wso2.emm.agent.beans.Operation operation) throws AndroidAgentException {
    String ssid = null;

    try {
        JSONObject wifiData = new JSONObject(operation.getPayLoad().toString());
        if (!wifiData.isNull(resources.getString(R.string.intent_extra_ssid))) {
            ssid = (String) wifiData.get(resources.getString(R.string.intent_extra_ssid));
        }

        WiFiConfig config = new WiFiConfig(context.getApplicationContext());
        if (config.findWifiConfigurationBySsid(ssid)) {
            config.removeWifiConfigurationBySsid(ssid);
        }
    } catch (JSONException e) {
        throw new AndroidAgentException("Invalid JSON format.", e);
    }
}

From source file:com.atolcd.alfresco.AuditFilter.java

@Override
public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain)
        throws IOException, ServletException {

    // Get the HTTP request/response/session
    HttpServletRequest request = (HttpServletRequest) sReq;
    // HttpServletResponse response = (HttpServletResponse) sRes;

    // Initialize a new request context
    RequestContext context = ThreadLocalRequestContext.getRequestContext();

    if (context == null) {
        try {/*from  www  . j a v  a2 s.  c o  m*/
            // Perform a "silent" init - i.e. no user creation or remote
            // connections
            context = RequestContextUtil.initRequestContext(getApplicationContext(), request, true);
            try {
                RequestContextUtil.populateRequestContext(context, request);
            } catch (ResourceLoaderException e) {
                // e.printStackTrace();
            } catch (UserFactoryException e) {
                // e.printStackTrace();
            }
        } catch (RequestContextException ex) {
            throw new ServletException(ex);
        }
    }
    User user = context.getUser();
    String requestURI = request.getRequestURI();
    if (user != null && requestURI != null && !ignoredUrl.contains(requestURI)) {
        try {
            // Preparation of JSON to send.
            JSONObject auditSample = new JSONObject();
            auditSample.put(AUDIT_ID, "0");
            auditSample.put(AUDIT_USER_ID, user.getId());

            String ref = request.getHeader("referer");
            if (requestURI.endsWith("/dologin") && (ref != null)) {
                requestURI = ref;
            }
            HashMap<String, String> auditData = getAuditData(request, user.getId(), requestURI);
            // Parsing sometimes includes parameters when the page loading
            // is interrupted prematurely
            if ((auditData.get(KEY_MODULE).length() > 0) && (!auditData.get(KEY_ACTION).contains("?"))) {
                auditSample.put(AUDIT_SITE, auditData.get(KEY_SITE));
                auditSample.put(AUDIT_APP_NAME, auditData.get(KEY_MODULE));
                auditSample.put(AUDIT_ACTION_NAME, auditData.get(KEY_ACTION));
                auditSample.put(AUDIT_OBJECT, auditData.get(KEY_OBJECT));
                auditSample.put(AUDIT_TIME, Long.toString(System.currentTimeMillis()));

                // Remote call for DB
                if (moduleIds.containsKey(auditSample.get(AUDIT_APP_NAME))) {
                    remoteCall(request, auditSample);
                } else {
                    logger.info("Ignored: " + requestURI);
                }
            }
        } catch (Exception e) {
            logger.error(" Error while auditing data in AuditFilter");
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage(), e);
            }
        }
    }
    chain.doFilter(sReq, sRes);
}

From source file:com.atolcd.alfresco.AuditFilter.java

/**
 * @param request//from  w  ww  . j a  va2  s .c  o  m
 * @param userId
 * @param siteId
 * @param componentId
 * @param objectId
 * @return
 * @throws JSONException
 * @throws URIException
 * @throws UnsupportedEncodingException
 */
private String getNodeRefRemoteCall(HttpServletRequest request, String userId, String siteId,
        String componentId, String objectId) throws JSONException, URIException, UnsupportedEncodingException {
    Connector connector;
    try {
        connector = FrameworkUtil.getConnector(request.getSession(true), userId,
                AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
        // <url>/share-stats/slingshot/details/{siteId}/{componentId}/{objectId}</url>
        Response resp = connector.call("/share-stats/slingshot/details/" + siteId + "/" + componentId + "/"
                + URLEncoder.encode(objectId, "UTF-8"));

        if (resp.getStatus().getCode() == Status.STATUS_OK) {
            try {
                JSONObject json = new JSONObject(resp.getResponse());
                if (json.has("nodeRef")) {
                    return (String) json.get("nodeRef");
                }
            } catch (JSONException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug(e.getMessage(), e);
                }
            }
        }
    } catch (ConnectorServiceException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
    }

    return objectId;
}

From source file:com.googlecode.goclipse.tooling.oracle.JSONParseHelpers.java

public static String readString(JSONObject jsonObject, String key) throws JSONException, CommonException {
    Object stringValue = jsonObject.get(key);
    if (stringValue instanceof String) {
        return (String) stringValue;
    } else {/* www .  java2  s  . c om*/
        throw new CommonException("Member " + key + " not a String.");
    }
}