List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Basing on passed profileInfo, creates object of type BackendCapability. * /*from w w w . j a v a2s .c o m*/ * @param profileInfo Profile described in JSOSObject. * @return Object of BackendCapability derived from passed profileInfo. */ private BackendCapability createBackedCapability(JSONObject profileInfo) { /* * determine value of name parameter to be used with BackendCapability */ String profileName = profileInfo.getString(JSON_KEY_NAME); /* * determine value of type attribute to be used with BackendCapability */ BackendCapability.CapabilityType type = null; String typeAsString = profileInfo.getString(JSON_KEY_TYPE); switch (typeAsString) { case CDMI_OBJECT_TYPE_CONTAINER: type = BackendCapability.CapabilityType.CONTAINER; break; case CDMI_OBJECT_TYPE_DATAOBJECT: type = BackendCapability.CapabilityType.DATAOBJECT; break; default: throw new RuntimeException("Unknown capability type"); } /* * create new instance of BackendCapability * (it is empty for now, the metadata and capabilities properties have to be created, * populated and passed to the BackendCapability object) */ final BackendCapability returnBackendCapability = new BackendCapability(profileName, type); /* * create capabilities object (to be populated and injected into returned BackendCapability) */ Map<String, Object> capabilities = new HashMap<>(); /* * Add always present capabilities */ capabilities.put("cdmi_capabilities_templates", "true"); capabilities.put("cdmi_capabilities_exact_inherit", "true"); /* * create metadata object (to be populated and injected into returned BackendCapability) */ Map<String, Object> metadata = new HashMap<>(); /* * iterate through metadata in profileInfo and populate capabilities and * metadata in BackendCapability object */ JSONObject metadataObj = profileInfo.getJSONObject(JSON_KEY_METADATA); log.debug("Processing metadata array from profile returned by BackendGateway"); Iterator<?> keys = metadataObj.keys(); while (keys.hasNext()) { /* * get key name for current item in metadata array */ String key = (String) keys.next(); /* * get value assigned to the current key, and convert the value to String * NOTE: The convention is required because returned value can be for example of array type * or of another JSONObject, it not necessary has to be String, so usage of * metadataObj.getString(key) would be wrong */ Object valueObj = metadataObj.get(key); log.debug("Current metadata key: {}", key); log.debug("Current metadata value: {}", valueObj); log.debug("Metadata value class/type is: {}", valueObj.getClass()); /* * Create key and value to be added to capabilities. * Separate variables for key and value objects are introduced deliberately * to note that in future or in case of any special values, an additional * logic / calculation can be required to obtain key and value to be used * with capabilities map */ String cdmiCapabilityKey = key; String cdmiCapabilityValue = "true"; /* * add "calculated" key and value to the capabilities map */ capabilities.put(cdmiCapabilityKey, cdmiCapabilityValue); /* * see above comments for capabilities related keys and values */ String cdmiMetadataKey = key; Object cdmiMetadataValue = valueObj; /* * add "calculated" key and value to the metadata map */ metadata.put(cdmiMetadataKey, cdmiMetadataValue); } // while() //capabilities.put("cdmi_capabilities_allowed", "true"); /* * process allowed profiles */ try { JSONArray allowedProfiles = profileInfo.getJSONArray(JSON_KEY_ALLOWED_PROFILES); String profilesUris = profilesToUris(allowedProfiles, retriveObjectTypeAsString(profileInfo)); log.debug("allowedProfiles: {}", allowedProfiles); log.debug("profilesURIs: {}", profilesUris); metadata.put("cdmi_capabilities_allowed", profilesUris); } catch (JSONException ex) { log.debug("No {} key in processed JSON document", JSON_KEY_ALLOWED_PROFILES); } // try{} returnBackendCapability.setCapabilities(capabilities); returnBackendCapability.setMetadata(metadata); return returnBackendCapability; }
From source file:com.primitive.applicationmanager.datagram.ApplicationSummary.java
/** * ApplicationManagerDatagram initialize * @param json/*from ww w. j a v a2s . c o m*/ */ public ApplicationSummary(final JSONObject json) { super(json); Logger.start(); try { final JSONArray packageTypes = json.getJSONArray(ApplicationSummary.PackageTypes); Logger.debug(packageTypes); for (int i = 0; i < packageTypes.length(); i++) { final JSONObject obj = packageTypes.getJSONObject(i); Logger.debug(obj); this.packageTypes.add(new PackageType(obj)); } } catch (final JSONException ex) { Logger.err(ex); } Logger.end(); }
From source file:com.flurry.samples.tumblrsharing.PhotoFeedActivity.java
/** * Method to display photo feed./* ww w.ja va 2s . c o m*/ * */ private void fetchPhotoFeed() { flickrClient = new FlickrClient(); HashMap<String, String> fetchPhotosEventParams = new HashMap<>(1); fetchPhotosEventParams.put(AnalyticsHelper.PARAM_LOCATION, String.valueOf(lastLocation)); AnalyticsHelper.logEvent(AnalyticsHelper.EVENT_FETCH_PHOTOS, fetchPhotosEventParams, true); flickrClient.getPhotoFeed(lastLocation, new JsonHttpResponseHandler() { @Override public void onSuccess(int code, Header[] headers, JSONObject body) { AnalyticsHelper.endTimedEvent(AnalyticsHelper.EVENT_FETCH_PHOTOS); JSONObject photosObject = null; if (body != null) { try { if (body.has("photos")) { photosObject = body.getJSONObject("photos"); JSONArray photoArray = photosObject.getJSONArray("photo"); List<Photo> photosList = Photo.fromJson(photoArray); photoAdapter.addPhotos(photosList); photoAdapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show(); finish(); } } catch (JSONException e) { AnalyticsHelper.logError(LOG_TAG, "Photo Feed JSON Error", e); } } else { Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show(); AnalyticsHelper.logError(LOG_TAG, "Response body is null", null); finish(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show(); AnalyticsHelper.logError(LOG_TAG, "Failure in fetching photo feed", null); finish(); } }); }
From source file:net.dv8tion.jda.core.handle.MessageUpdateHandler.java
private Long handleMessageEmbed(JSONObject content) { EntityBuilder builder = api.getEntityBuilder(); final long messageId = content.getLong("id"); final long channelId = content.getLong("channel_id"); LinkedList<MessageEmbed> embeds = new LinkedList<>(); MessageChannel channel = api.getTextChannelMap().get(channelId); if (channel == null) channel = api.getPrivateChannelMap().get(channelId); if (channel == null) channel = api.getFakePrivateChannelMap().get(channelId); if (channel == null && api.getAccountType() == AccountType.CLIENT) channel = api.asClient().getGroupById(channelId); if (channel == null) { api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> { handle(responseNumber, allContent); });//from ww w. j a va 2 s . c om EventCache.LOG.debug( "Received message update for embeds for a channel/group that JDA does not have cached yet."); return null; } JSONArray embedsJson = content.getJSONArray("embeds"); for (int i = 0; i < embedsJson.length(); i++) { embeds.add(builder.createMessageEmbed(embedsJson.getJSONObject(i))); } if (channel instanceof TextChannel) { TextChannel tChannel = (TextChannel) channel; if (api.getGuildLock().isLocked(tChannel.getGuild().getIdLong())) { return tChannel.getGuild().getIdLong(); } api.getEventManager() .handle(new GuildMessageEmbedEvent(api, responseNumber, messageId, tChannel, embeds)); } else if (channel instanceof PrivateChannel) { api.getEventManager().handle( new PrivateMessageEmbedEvent(api, responseNumber, messageId, (PrivateChannel) channel, embeds)); } else { api.getEventManager() .handle(new GroupMessageEmbedEvent(api, responseNumber, messageId, (Group) channel, embeds)); } //Combo event api.getEventManager().handle(new MessageEmbedEvent(api, responseNumber, messageId, channel, embeds)); return null; }
From source file:com.mobile.system.db.abatis.AbatisService.java
/** * /* ww w . j a v a 2 s . c o m*/ * @param jsonStr * JSON String * @param beanClass * Bean class * @param basePackage * Base package name which includes all Bean classes * @return Object Bean * @throws Exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception { Object obj = null; JSONObject jsonObj = new JSONObject(jsonStr); // Check bean object if (beanClass == null) { Log.d(TAG, "Bean class is null"); return null; } // Read Class member fields Field[] props = beanClass.getDeclaredFields(); if (props == null || props.length == 0) { Log.d(TAG, "Class" + beanClass.getName() + " has no fields"); return null; } // Create instance of this Bean class obj = beanClass.newInstance(); // Set value of each member variable of this object for (int i = 0; i < props.length; i++) { String fieldName = props[i].getName(); // Skip public and static fields if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) { continue; } // Date Type of Field Class type = props[i].getType(); String typeName = type.getName(); // Check for Custom type if (typeName.equals("int")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getInt(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("long")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getLong(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("java.lang.String")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getString(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("double")) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { m.invoke(obj, jsonObj.getDouble(fieldName)); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); } } else if (typeName.equals("java.util.Date")) { // modify Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); String dateString = jsonObj.getString(fieldName); dateString = dateString.replace(" KST", ""); SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA); // Set value try { Date afterDate = genderFormat.parse(dateString); m.invoke(obj, afterDate); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } else if (type.getName().equals(List.class.getName()) || type.getName().equals(ArrayList.class.getName())) { // Find out the Generic String generic = props[i].getGenericType().toString(); if (generic.indexOf("<") != -1) { String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">")); if (genericType != null) { JSONArray array = null; try { array = jsonObj.getJSONArray(fieldName); } catch (Exception ex) { Log.d(TAG, ex.getMessage()); array = null; } if (array == null) { continue; } ArrayList arrayList = new ArrayList(); for (int j = 0; j < array.length(); j++) { arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType), basePackage)); } // Set value Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); m.invoke(obj, arrayList); } } else { // No generic defined generic = null; } } else if (typeName.startsWith(basePackage)) { Class[] parms = { type }; Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms); m.setAccessible(true); // Set value try { JSONObject customObj = jsonObj.getJSONObject(fieldName); if (customObj != null) { m.invoke(obj, parse(customObj.toString(), type, basePackage)); } } catch (JSONException ex) { Log.d(TAG, ex.getMessage()); } } else { // Skip Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip"); } } return obj; }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); SerializableBean bean = new SerializableBean(); bean.setBooleanValue(true);/* w ww .j a v a2 s . c om*/ bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("serializableBean")); json = json.getJSONObject("serializableBean"); assertEquals(true, json.getBoolean("booleanValue")); assertEquals(0.451, json.getDouble("doubleValue")); assertEquals(1.34f, (float) json.getDouble("floatValue")); assertEquals(3400100, json.getInt("intValue")); assertEquals(3400100200L, json.getLong("longValue")); assertEquals(32767, (short) json.getInt("shortValue")); assertEquals("String", json.getString("stringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue")); assertTrue(json.has("beanValue")); JSONObject inBeanJson = json.getJSONObject("beanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("stringListValue")); JSONArray stringListJson = json.getJSONArray("stringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("beanListValue")); JSONArray beanListJson = json.getJSONArray("beanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:com.nginious.http.serialize.JsonSerializerTestCase.java
public void testNamedJsonSerializer() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); NamedBean bean = new NamedBean(); bean.setBooleanValue(true);//w w w. j a v a 2s .c om bean.setDoubleValue(0.451); bean.setFloatValue(1.34f); bean.setIntValue(3400100); bean.setLongValue(3400100200L); bean.setShortValue((short) 32767); bean.setStringValue("String"); bean.setDateValue(format.parse("2011-08-24T08:50:23+0200")); Date calDate = format.parse("2011-08-24T08:52:23+0200"); Calendar cal = Calendar.getInstance(); cal.setTime(calDate); bean.setCalendarValue(cal); bean.setObjectValue(TimeZone.getDefault()); InBean inBean = new InBean(); inBean.setFirst(true); inBean.setSecond(0.567d); inBean.setThird(0.342f); inBean.setFourth(100); inBean.setFifth(3400200100L); inBean.setSixth((short) 32767); inBean.setSeventh("String"); inBean.setEight(format.parse("2011-08-25T08:50:23+0200")); cal = Calendar.getInstance(); calDate = format.parse("2011-08-25T08:52:23+0200"); cal.setTime(calDate); inBean.setNinth(cal); bean.setBeanValue(inBean); List<InBean> beanList = new ArrayList<InBean>(); beanList.add(inBean); beanList.add(inBean); bean.setBeanListValue(beanList); List<String> stringList = new ArrayList<String>(); stringList.add("One"); stringList.add("Two"); stringList.add("Three"); bean.setStringListValue(stringList); ApplicationClassLoader classLoader = new ApplicationClassLoader( Thread.currentThread().getContextClassLoader()); SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader); Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json"); assertEquals("application/json", serializer.getMimeType()); StringWriter strWriter = new StringWriter(); PrintWriter writer = new PrintWriter(strWriter); serializer.serialize(writer, bean); writer.flush(); JSONObject json = new JSONObject(strWriter.toString()); assertNotNull(json); assertTrue(json.has("testNamedBean")); json = json.getJSONObject("testNamedBean"); assertEquals(true, json.getBoolean("testBooleanValue")); assertEquals(0.451, json.getDouble("testDoubleValue")); assertEquals(1.34f, (float) json.getDouble("testFloatValue")); assertEquals(3400100, json.getInt("testIntValue")); assertEquals(3400100200L, json.getLong("testLongValue")); assertEquals(32767, (short) json.getInt("testShortValue")); assertEquals("String", json.getString("testStringValue")); assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue")); assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue")); assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue")); assertTrue(json.has("testBeanValue")); JSONObject inBeanJson = json.getJSONObject("testBeanValue"); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); assertTrue(json.has("testStringListValue")); JSONArray stringListJson = json.getJSONArray("testStringListValue"); assertEquals("One", stringListJson.get(0)); assertEquals("Two", stringListJson.get(1)); assertEquals("Three", stringListJson.get(2)); assertTrue(json.has("testBeanListValue")); JSONArray beanListJson = json.getJSONArray("testBeanListValue"); inBeanJson = beanListJson.getJSONObject(0); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); inBeanJson = beanListJson.getJSONObject(1); assertTrue(inBeanJson.has("inBean")); inBeanJson = inBeanJson.getJSONObject("inBean"); assertEquals(true, inBeanJson.getBoolean("first")); assertEquals(0.567, inBeanJson.getDouble("second")); assertEquals(0.342f, (float) inBeanJson.getDouble("third")); assertEquals(100, inBeanJson.getInt("fourth")); assertEquals(3400200100L, inBeanJson.getLong("fifth")); assertEquals(32767, (short) inBeanJson.getInt("sixth")); assertEquals("String", inBeanJson.getString("seventh")); assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight")); assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth")); }
From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java
private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) { try {/* w w w .j a va 2 s .c o m*/ String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities"; HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "application/json"); post.setHeader("X_LAYER_APP_ID", appId); JSONObject rootObject = new JSONObject(); if (requestIdentityToken) { rootObject.put("nonce", nonce); rootObject.put("name", userName); } else { rootObject.put("name", "Web"); // name must be specified to make entiry valid } StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = (new DefaultHttpClient()).execute(post); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode() && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) { StringBuilder sb = new StringBuilder(); sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [") .append(response.getStatusLine()).append("] when logging in. Request: ").append(url); if (requestIdentityToken) sb.append(" login: ").append(userName).append(", nonce: ").append(nonce); Log.e(TAG, sb.toString()); return new String[] { null, sb.toString() }; } String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonResp = new JSONObject(responseString); JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities"); List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length()); for (int i = 0; i < atlasIdentities.length(); i++) { JSONObject identity = atlasIdentities.getJSONObject(i); Participant participant = new Participant(); participant.firstName = identity.getString("name"); participant.userId = identity.getString("id"); participants.add(participant); } if (participants.size() > 0) { setParticipants(participants); save(); if (debug) Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities); } if (requestIdentityToken) { String error = jsonResp.optString("error", null); String identityToken = jsonResp.optString("identity_token"); return new String[] { identityToken, error }; } return new String[] { null, "Refreshed " + participants.size() + " contacts" }; } catch (Exception e) { Log.e(TAG, "Error when fetching identity token", e); return new String[] { null, "Cannot obtain identity token. " + e }; } }
From source file:fi.elfcloud.sci.container.Cluster.java
public Cluster(Client client, JSONObject object) throws JSONException { this.client = client; this.id = object.getInt("id"); this.name = object.getString("name"); this.childCount = object.getInt("descendants"); this.dataItemCount = object.getInt("dataitems"); this.parent_id = object.getInt("parent_id"); this.last_accessed_date = (object.get("last_accessed_date") != JSONObject.NULL ? object.getString("last_accessed_date") : ""); this.last_modified_date = (object.get("modified_date") != JSONObject.NULL ? object.getString("modified_date") : ""); this.permissions = object.getJSONArray("permissions"); }
From source file:fi.elfcloud.sci.container.Cluster.java
/** * Returns child {@link DataItem}s and {@link Cluster}s * @return {@link HashMap} with keys <code>clusters</code> and <code>dataitems</code> * @throws ECException/* w ww. j a v a2s .c o m*/ * @throws IOException */ public HashMap<String, Object[]> getElements() throws ECException, IOException { Map<String, Object> params = new HashMap<String, Object>(); params.put("parent_id", this.id); JSONObject response; try { response = (JSONObject) this.client.getConnection().sendRequest("list_contents", params); JSONArray jsonArray = response.getJSONArray("clusters"); Cluster clusterArray[] = new Cluster[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); clusterArray[i] = new Cluster(this.client, object); } this.childCount = clusterArray.length; jsonArray = response.getJSONArray("dataitems"); DataItem dataitemArray[] = new DataItem[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); dataitemArray[i] = new DataItem(this.client, object, this.id); } this.dataItemCount = dataitemArray.length; HashMap<String, Object[]> objects = new HashMap<String, Object[]>(); objects.put("clusters", clusterArray); objects.put("dataitems", dataitemArray); return objects; } catch (JSONException e) { e.printStackTrace(); } return null; }