Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:com.primitive.applicationmanager.datagram.ApplicationSummary.java

/**
 * ApplicationManagerDatagram initialize
 * @param json// ww  w .  j  a  v  a  2s  . c  om
 */
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: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);
        });//ww w.  j  a  v  a  2s  .c  o m
        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

/**
 * /* w  w w. j  av  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);/*from w w  w  .  j  av  a2 s . c  o m*/
    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);/*from  w w  w  .j a v  a2  s .com*/
    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 {/*ww w  . j  a  v a 2  s. co 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:com.layer.atlas.messenger.AtlasIdentityProvider.java

private boolean load() {
    String jsonString = context.getSharedPreferences("contacts", Context.MODE_PRIVATE).getString("json", null);
    if (jsonString == null)
        return false;

    List<Participant> participants;
    try {//  w  w  w. j  ava  2s.  co m
        JSONArray contactsJson = new JSONArray(jsonString);
        participants = new ArrayList<Participant>(contactsJson.length());
        for (int i = 0; i < contactsJson.length(); i++) {
            JSONObject contactJson = contactsJson.getJSONObject(i);
            Participant participant = new Participant();
            participant.userId = contactJson.optString("id");
            participant.firstName = contactJson.optString("first_name");
            participant.lastName = contactJson.optString("last_name");
            participants.add(participant);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error while saving", e);
        return false;
    }

    setParticipants(participants);

    return true;
}

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/*from  ww w  .j a  va 2  s .c om*/
 * @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;

}

From source file:fi.elfcloud.sci.container.Cluster.java

/**
 * Returns child {@link Cluster}s /*  w  ww.java 2  s.c  om*/
 * @return child {@link Cluster}s
 * @throws ECException
 * @throws IOException
 */
public Cluster[] getChildren() throws ECException, IOException {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("parent_id", this.id);
    Object response;
    try {
        response = this.client.getConnection().sendRequest("list_clusters", params);
        JSONArray clusters = (JSONArray) response;
        Cluster result[] = new Cluster[clusters.length()];
        for (int i = 0; i < clusters.length(); i++) {
            JSONObject object = clusters.getJSONObject(i);
            result[i] = new Cluster(this.client, object);
        }
        this.childCount = result.length;
        return result;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:fi.elfcloud.sci.container.Cluster.java

/**
 * Returns child {@link DataItem}s/*from w w w.  j  a  v  a2  s . c o  m*/
 * @param    keynames array of {@link DataItem} names. Can be empty Array to list all.
 * @return {@link DataItem}s filtered by <code>keynames</code> or all direct {@link DataItem}s if
 *       array is empty
 * @throws ECException
 * @throws IOException
 */
public DataItem[] getDataItems(String[] keynames) throws ECException, IOException {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("parent_id", this.id);
    params.put("names", keynames);
    Object response;
    try {
        response = (JSONArray) this.client.getConnection().sendRequest("list_dataitems", params);
        JSONArray dataItems = (JSONArray) response;
        DataItem result[] = new DataItem[dataItems.length()];
        for (int i = 0; i < dataItems.length(); i++) {
            result[i] = new DataItem(this.client, dataItems.getJSONObject(i), this.id);
        }
        this.dataItemCount = result.length;
        return result;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}