List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java
private List<DesiredCapabilities> getNodeCapabilities() { try {//w ww .j a v a 2 s. c om List<DesiredCapabilities> capabilities = new ArrayList<DesiredCapabilities>(); JSONObject status = getNodeStatusJson(); if (status == null) { return null; } String ios = status.getJSONObject("value").getJSONObject("ios").optString("simulatorVersion"); JSONArray supportedApps = status.getJSONObject("value").getJSONArray("supportedApps"); for (int i = 0; i < supportedApps.length(); i++) { Map<String, Object> capability = new HashMap<String, Object>(); capability.put("maxInstances", "1"); if (ios.isEmpty()) { capability.put("ios", "5.1"); capability.put("browserName", "IOS Device"); capability.put(IOSCapabilities.DEVICE, DeviceType.iphone); } else { capability.put("ios", ios); capability.put("browserName", "IOS Simulator"); } JSONObject app = supportedApps.getJSONObject(i); for (String key : JSONObject.getNames(app)) { if ("locales".equals(key)) { JSONArray loc = app.getJSONArray(key); List<String> locales = new ArrayList<String>(); for (int j = 0; j < loc.length(); j++) { locales.add(loc.getString(j)); } capability.put("locales", locales); } else { Object o = app.get(key); capability.put(key, o); } } capabilities.add(new DesiredCapabilities(capability)); } return capabilities; } catch (Exception e) { return null; } }
From source file:cc.redpen.server.api.RedPenConfigurationResourceTest.java
@Test public void availableDocumentParsersAreReturned() throws Exception { JSONObject response = (JSONObject) resource.getRedPens("").getEntity(); assertEquals(new JSONArray(DocumentParser.PARSER_MAP.keySet()).toString(), response.get("documentParsers").toString()); }
From source file:com.citruspay.mobile.payment.oauth2.OAuth2Token.java
public static OAuth2Token create(JSONObject json) { // enhance object w/ expiry date JSONObject jtoken = json;/*from w w w. j a v a 2s. c om*/ if (!json.has("expiry")) { // copy input jtoken = new JSONObject(); for (Iterator<?> keys = json.keys(); keys.hasNext();) { String key = (String) keys.next(); try { jtoken.put(key, json.get(key)); } catch (JSONException jx) { throw new RuntimeException(jx); } } // add expiry date long expiry = new Date().getTime() / 1000l; try { expiry += json.getLong("expires_in"); } catch (JSONException jx) { /* ignore => expires now ! */ } try { jtoken.put("expiry", expiry); } catch (JSONException jx) { throw new RuntimeException(jx); } } // create token return new OAuth2Token(jtoken); }
From source file:org.everit.json.schema.NullSchemaTest.java
@Test public void success() { JSONObject obj = new JSONObject("{\"a\" : null}"); NullSchema.INSTANCE.validate(obj.get("a")); }
From source file:com.md87.charliebravo.commands.DefineCommand.java
public void execute(final InputHandler handler, Response response, String line) throws MalformedURLException, IOException, JSONException { URL url = new URL("http://apps.md87.co.uk/services/wiktionary/?query=" + URLEncoder.encode(line, Charset.defaultCharset().name())); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://chris.smith.name/"); String input;/*from w w w.ja v a2 s. c om*/ StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((input = reader.readLine()) != null) { builder.append(input); } JSONObject json = new JSONObject(builder.toString()); if (json.getInt("responseStatus") != 200) { throw new IOException(json.getString("responseDetails")); } if (json.getJSONArray("responseData").length() == 0) { response.sendMessage("There were no results for '" + line + "'", true); } else { final StringBuilder res = new StringBuilder(); res.append("there "); if (json.getJSONArray("responseData").length() == 1) { res.append("was 1 match"); } else { res.append("were "); res.append(json.getJSONArray("responseData").length()); res.append(" matches"); } res.append(" for '"); res.append(line); res.append("'"); if (json.getJSONArray("responseData").length() == 1) { res.append(". It is "); } else { res.append(". Result 1 is "); } final String name = json.getJSONArray("responseData").getJSONObject(0).getString("title"); res.append('\''); res.append(name); res.append("', which has "); final int defs = json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions") .length(); res.append(defs); res.append(" definition"); if (defs != 1) { res.append("s, the first of which is"); } res.append(": "); res.append(json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions").get(0)); response.sendMessage(res.toString()); response.addFollowup(new NextWordFollowup(json.getJSONArray("responseData"), 1)); response.addFollowup(new NextDefinitionFollowup( json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions"), 1, new NextWordFollowup(json.getJSONArray("responseData"), 1))); } }
From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java
/** * Make remote request to get all loyalty cards stored in Cozy *//*from w ww . j a v a 2 s .co m*/ public String getRemoteExpenses() { URL urlO = null; try { urlO = new URL(designUrl); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() == 0) { EventBus.getDefault() .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored.")); Expense.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE, "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value"); Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString()); if (expense == null) { expense = new Expense(expenseJson); } else { expense.setRemoteId(expenseJson.getString("_id")); expense.setAmount(expenseJson.getDouble("amount")); expense.setCategory(expenseJson.getString("category")); expense.setDate(expenseJson.getString("date")); if (expenseJson.has("deviceId")) { expense.setDeviceId(expenseJson.getString("deviceId")); } else { expense.setDeviceId(Device.registeredDevice().getLogin()); } } expense.save(); if (expenseJson.has("receipts")) { JSONArray receiptsArray = expenseJson.getJSONArray("receipts"); for (int j = 0; j < receiptsArray.length(); j++) { JSONObject recJsonObject = receiptsArray.getJSONObject(i); Receipt receipt = new Receipt(); receipt.setBase64(recJsonObject.getString("base64")); receipt.setExpense(expense); receipt.setName(""); receipt.save(); } } } catch (JSONException e) { EventBus.getDefault() .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
From source file:com.voidsearch.data.provider.facebook.objects.NewsEntry.java
public NewsEntry(JSONObject data) throws Exception { super(data);//from w w w .ja v a2 s . c o m createdTime = (String) data.get("created_time"); updatedTime = (String) data.get("updated_time"); }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * Parses the specified method call for an article. * /* w w w . j a v a2 s.c o m*/ * @param methodCall the specified method call * @return article * @throws Exception exception */ private JSONObject parsetPost(final JSONObject methodCall) throws Exception { final JSONObject ret = new JSONObject(); final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param"); final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct"); final JSONArray members = post.getJSONArray("member"); for (int i = 0; i < members.length(); i++) { final JSONObject member = members.getJSONObject(i); final String name = member.getString("name"); if ("dateCreated".equals(name)) { final JSONObject preference = preferenceQueryService.getPreference(); final String dateString = member.getJSONObject("value").getString("dateTime.iso8601"); Date date = null; try { date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString); } catch (final ParseException e) { LOGGER.log(Level.WARNING, "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]"); final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID); final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId); final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss"); format.setTimeZone(timeZone); date = format.parse(dateString); } ret.put(Article.ARTICLE_CREATE_DATE, date); } else if ("title".equals(name)) { ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string")); } else if ("description".equals(name)) { final String content = member.getJSONObject("value").getString("string"); ret.put(Article.ARTICLE_CONTENT, content); final String plainTextContent = Jsoup.parse(content).text(); if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) { ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH)); } else { ret.put(Article.ARTICLE_ABSTRACT, plainTextContent); } } else if ("categories".equals(name)) { final StringBuilder tagBuilder = new StringBuilder(); final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data"); if (0 == data.length()) { throw new Exception("At least one Tag"); } final Object value = data.get("value"); if (value instanceof JSONArray) { final JSONArray tags = (JSONArray) value; for (int j = 0; j < tags.length(); j++) { final String tagTitle = tags.getJSONObject(j).getString("string"); tagBuilder.append(tagTitle); if (j < tags.length() - 1) { tagBuilder.append(","); } } } else { final JSONObject tag = (JSONObject) value; tagBuilder.append(tag.getString("string")); } ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString()); } } final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean") ? true : false; ret.put(Article.ARTICLE_IS_PUBLISHED, publish); ret.put(Article.ARTICLE_COMMENTABLE, true); ret.put(Article.ARTICLE_VIEW_PWD, ""); return ret; }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * Builds a post (post struct) with the specified post id. * /* ww w . jav a 2 s.c om*/ * @param postId the specified post id * @return blog info XML * @throws Exception exception */ private String buildPost(final String postId) throws Exception { final StringBuilder stringBuilder = new StringBuilder(); final JSONObject result = articleQueryService.getArticle(postId); if (null == result) { throw new Exception("Not found article[id=" + postId + "]"); } final JSONObject article = result.getJSONObject(Article.ARTICLE); final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE); final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE)); stringBuilder.append("<struct>"); stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>") .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate)) .append("</dateTime.iso8601></value></member>"); stringBuilder.append("<member><name>description</name>").append("<value>") .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT))) .append("</value></member>"); stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle) .append("</value></member>"); stringBuilder.append("<member><name>categories</name>").append("<value><array><data>"); final JSONArray tags = article.getJSONArray(Article.ARTICLE_TAGS_REF); for (int i = 0; i < tags.length(); i++) { final String tagTitle = tags.getJSONObject(i).getString(Tag.TAG_TITLE); stringBuilder.append("<value>").append(tagTitle).append("</value>"); } stringBuilder.append("</data></array></value></member></struct>"); return stringBuilder.toString(); }
From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java
/** * Builds recent posts (array of post structs) with the specified * fetch size.// ww w . ja va 2s. c om * * @param fetchSize the specified fetch size * @return blog info XML * @throws Exception exception */ private String buildRecentPosts(final int fetchSize) throws Exception { final StringBuilder stringBuilder = new StringBuilder(); final List<JSONObject> recentArticles = articleQueryService.getRecentArticles(fetchSize); for (final JSONObject article : recentArticles) { final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE); final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE)); stringBuilder.append("<value><struct>"); stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>") .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate)) .append("</dateTime.iso8601></value></member>"); stringBuilder.append("<member><name>description</name>").append("<value>") .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT))) .append("</value></member>"); stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle) .append("</value></member>"); stringBuilder.append("<member><name>postid</name>").append("<value>") .append(article.getString(Keys.OBJECT_ID)).append("</value></member>"); stringBuilder.append("<member><name>categories</name>").append("<value><array><data>"); final String tagTitles = article.getString(Article.ARTICLE_TAGS_REF); final String[] tagTitleArray = tagTitles.split(","); for (int i = 0; i < tagTitleArray.length; i++) { final String tagTitle = tagTitleArray[i]; stringBuilder.append("<value>").append(tagTitle).append("</value>"); } stringBuilder.append("</data></array></value></member>"); stringBuilder.append("</struct></value>"); } return stringBuilder.toString(); }