List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:com.joyfulmongo.db.QueryConditionFilterGeoQuery.java
public static void adjustConstraints(JSONObject constraints) { String geoPointKey = null;//from w w w.j a v a 2s . c o m ContainerObjectGeoPoint geoPoint = null; Iterator<String> iter = constraints.keys(); while (iter.hasNext()) { String constraintKey = iter.next(); Object o = constraints.get(constraintKey); if (o instanceof JSONObject) { Object nearSphere = ((JSONObject) o).opt(S_KEY); if (nearSphere != null && nearSphere instanceof JSONObject) { ContainerObject childObj = ContainerObjectFactory.getChildObject(S_KEY, (JSONObject) nearSphere); if (childObj instanceof ContainerObjectGeoPoint) { geoPointKey = constraintKey; geoPoint = (ContainerObjectGeoPoint) childObj; break; } } } } if (geoPointKey != null && geoPoint != null) { constraints.remove(geoPointKey); JSONArray geoArray = geoPoint.to2DArray(); JSONObject nearSphereCondition = new JSONObject(); nearSphereCondition.put(S_KEY, geoArray); constraints.put(ContainerObjectGeoPoint.S_GEO_POINT, nearSphereCondition); } }
From source file:com.cubusmail.user.UserAccountDao.java
/** * @param preferencesJson//ww w. j a v a 2s.co m * @param preferences */ private void json2Preferences(String preferencesJson, Preferences preferences) { try { JSONObject object = new JSONObject(preferencesJson); Field[] fields = Preferences.class.getFields(); if (fields != null) { for (Field field : fields) { Object value = object.has(field.getName()) ? object.get(field.getName()) : null; if (value != null) { if (value instanceof Integer) { field.setInt(preferences, ((Integer) value).intValue()); } else if (value instanceof Boolean) { field.setBoolean(preferences, ((Boolean) value).booleanValue()); } else if (value instanceof String) { field.set(preferences, value); } } } } } catch (JSONException e) { logger.error(e.getMessage(), e); } catch (NumberFormatException e) { logger.error(e.getMessage(), e); } catch (IllegalArgumentException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } }
From source file:org.cfg4j.source.context.propertiesprovider.JsonBasedPropertiesProvider.java
/** * Convert given Json document to a multi-level map. *///from www.j a va 2 s.c om @SuppressWarnings("unchecked") private Map<String, Object> convertToMap(Object jsonDocument) { Map<String, Object> jsonMap = new LinkedHashMap<>(); // Document is a text block if (!(jsonDocument instanceof JSONObject)) { jsonMap.put("content", jsonDocument); return jsonMap; } JSONObject obj = (JSONObject) jsonDocument; for (String key : obj.keySet()) { Object value = obj.get(key); if (value instanceof JSONObject) { value = convertToMap(value); } else if (value instanceof JSONArray) { ArrayList<Map<String, Object>> collection = new ArrayList<>(); for (Object element : ((JSONArray) value)) { collection.add(convertToMap(element)); } value = collection; } jsonMap.put(key, value); } return jsonMap; }
From source file:edu.mit.scratch.ScratchUserManager.java
public ScratchUserManager update() throws ScratchUserException { try {/* w w w .j a va2 s .c o m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang); cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://scratch.mit.edu/messages/ajax/get-message-count/") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("Cookie", "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken=" + this.session.getCSRFToken()) .addHeader("X-CSRFToken", this.session.getCSRFToken()).build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchUserException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject(result.toString().trim()); final Iterator<?> keys = jsonOBJ.keys(); while (keys.hasNext()) { final String key = "" + keys.next(); final Object o = jsonOBJ.get(key); final String val = "" + o; switch (key) { case "msg_count": this.message_count = Integer.parseInt(val); break; default: System.out.println("Missing reference:" + key); break; } } } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } return this; }
From source file:io.cslinmiso.line.utils.Utility.java
public static Map toMap(JSONObject object) throws JSONException { Map map = new LinkedHashMap(); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (object.get(key) instanceof JSONObject || object.get(key) instanceof JSONArray) { map.put(key, fromJson(object.get(key))); } else {//from www . ja va 2s .c o m map.put(key, object.get(key) == null ? null : String.valueOf(object.get(key))); } } return map; }
From source file:ui.frame.UILogin.java
public UILogin() { super("Login"); Label l = new Label(); setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(400, 300)); Panel p = new Panel(); loginPanel = p.createPanel(Layouts.grid, 4, 2); loginPanel.setBorder(new EmptyBorder(25, 25, 0, 25)); lblUser = l.createLabel("Username:"); lblPassword = l.createLabel("Password:"); lblURL = l.createLabel("Server URL"); lblBucket = l.createLabel("Bucket"); tfURL = new JTextField(); tfURL.setText("kaiup.kaisquare.com"); tfBucket = new JTextField(); PromptSupport.setPrompt("BucketName", tfBucket); tfUser = new JTextField(); PromptSupport.setPrompt("Username", tfUser); pfPassword = new JPasswordField(); PromptSupport.setPrompt("Password", pfPassword); buttonPanel = p.createPanel(Layouts.flow); buttonPanel.setBorder(new EmptyBorder(0, 0, 25, 0)); Button b = new Button(); JButton btnLogin = b.createButton("Login"); JButton btnExit = b.createButton("Exit"); btnLogin.setPreferredSize(new Dimension(150, 50)); btnExit.setPreferredSize(new Dimension(150, 50)); Component[] arrayBtn = { btnExit, btnLogin }; p.addComponentsToPanel(buttonPanel, arrayBtn); Component[] arrayComponents = { lblURL, tfURL, lblBucket, tfBucket, lblUser, tfUser, lblPassword, pfPassword };//from w ww . java 2 s. co m p.addComponentsToPanel(loginPanel, arrayComponents); add(loginPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (tfUser.getText().equals("") || String.valueOf(pfPassword.getPassword()).equals("") || tfBucket.getText().equals("")) { JOptionPane.showMessageDialog(Data.mainFrame, "Please fill up all the fields", "Error", JOptionPane.ERROR_MESSAGE); } else { String username = tfUser.getText(); String password = String.valueOf(pfPassword.getPassword()); Data.URL = Data.protocol + tfURL.getText(); Data.targetURL = Data.protocol + tfURL.getText() + "/api/" + tfBucket.getText() + "/"; String response = api.loginBucket(Data.targetURL, username, password); try { if (DesktopAppMain.checkResult(response)) { JSONObject responseJSON = new JSONObject(response); Data.sessionKey = responseJSON.get("session-key").toString(); response = api.getUserFeatures(Data.targetURL, Data.sessionKey); if (checkFeatures(response)) { Data.mainFrame = new KAIQRFrame(); Data.mainFrame.uiInventorySelect = new UIInventorySelect(); Data.mainFrame.addPanel(Data.mainFrame.uiInventorySelect, "inventory"); Data.mainFrame.showPanel("inventory"); Data.mainFrame.pack(); setVisible(false); Data.mainFrame.setVisible(true); } else { JOptionPane.showMessageDialog(Data.loginFrame, "User does not have necessary features", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(Data.loginFrame, "Wrong username/password", "Error", JOptionPane.ERROR_MESSAGE); } } catch (JSONException e1) { e1.printStackTrace(); } } return null; } }; Window win = SwingUtilities.getWindowAncestor((AbstractButton) e.getSource()); final JDialog dialog = new JDialog(win, "Login", 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("Logging in .........."), BorderLayout.PAGE_START); dialog.add(panel); dialog.pack(); dialog.setBounds(50, 50, 300, 100); dialog.setLocationRelativeTo(Data.mainFrame); dialog.setVisible(true); } }); btnExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); }
From source file:ui.frame.UILogin.java
public static boolean checkFeatures(String response) { boolean result = false; HashMap<String, String> featureList = new HashMap<String, String>(); JSONObject responseObject; try {/*from w w w. j av a2 s. c o m*/ responseObject = new JSONObject(response); if (responseObject.get("result").equals("ok")) { JSONArray features = responseObject.getJSONArray("features"); for (int i = 0; i < features.length(); i++) { JSONObject feature = features.getJSONObject(i); String featureName = feature.getString("name"); if (featureName.equals("global-license-management") || featureName.equals("inventory-management") || featureName.equals("access-key-management") || featureName.equals("bucket-management")) { featureList.put(featureName, feature.getString("name")); } } if (featureList.size() == 4) { return true; } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
From source file:org.wso2.emm.agent.services.PolicyComplianceChecker.java
/** * Checks Wifi policy on the device (Particular wifi configuration in the policy should be enforced). * * @param operation - Operation object.// w w w . j av a2s.c o m * @return policy - ComplianceFeature object. */ private ComplianceFeature checkWifiPolicy(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)) { policy.setCompliance(true); } else { policy.setCompliance(false); policy.setMessage(resources.getString(R.string.error_wifi_policy)); } } catch (JSONException e) { throw new AndroidAgentException("Invalid JSON format.", e); } return policy; }
From source file:org.wso2.emm.agent.services.PolicyComplianceChecker.java
/** * Checks Work-Profile policy on the device (Particular work-profile configuration in the policy should be enforced). * * @param operation - Operation object.//from w w w . jav a 2s . c o m * @return policy - ComplianceFeature object. */ private ComplianceFeature checkWorkProfilePolicy(org.wso2.emm.agent.beans.Operation operation) throws AndroidAgentException { String profileName; String systemAppsData; String googlePlayAppsData; try { JSONObject profileData = new JSONObject(operation.getPayLoad().toString()); if (!profileData.isNull(resources.getString(R.string.intent_extra_profile_name))) { profileName = (String) profileData.get(resources.getString(R.string.intent_extra_profile_name)); //yet there is no method is given to get the current profile name. //add a method to test whether profile name is set correctly once introduced. } if (!profileData.isNull(resources.getString(R.string.intent_extra_enable_system_apps))) { // generate the System app list which are configured by user and received to agent as a single String // with packages separated by Commas. systemAppsData = (String) profileData .get(resources.getString(R.string.intent_extra_enable_system_apps)); List<String> systemAppList = Arrays .asList(systemAppsData.split(resources.getString(R.string.split_delimiter))); for (String packageName : systemAppList) { if (!applicationManager.isPackageInstalled(packageName)) { policy.setCompliance(false); policy.setMessage(resources.getString(R.string.error_work_profile_policy)); return policy; } } } if (!profileData.isNull(resources.getString(R.string.intent_extra_enable_google_play_apps))) { googlePlayAppsData = (String) profileData .get(resources.getString(R.string.intent_extra_enable_google_play_apps)); List<String> playStoreAppList = Arrays .asList(googlePlayAppsData.split(resources.getString(R.string.split_delimiter))); for (String packageName : playStoreAppList) { if (!applicationManager.isPackageInstalled(packageName)) { policy.setCompliance(false); policy.setMessage(resources.getString(R.string.error_work_profile_policy)); return policy; } } } } catch (JSONException e) { throw new AndroidAgentException("Invalid JSON format.", e); } policy.setCompliance(true); return policy; }
From source file:com.facebook.internal.JsonUtilTest.java
@Test public void testJsonObjectPutAll() throws JSONException { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("hello", "world"); map.put("hocus", "pocus"); JSONObject jsonObject = new JSONObject(); JsonUtil.jsonObjectPutAll(jsonObject, map); assertEquals("pocus", jsonObject.get("hocus")); assertEquals(2, jsonObject.length()); }