All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jelastic.api.ListResponse Maven / Gradle / Ivy

The newest version!
/*Server class MD5: 25c3a77989caf2c2d28b780ef6eed44f*/
package com.jelastic.api;

import com.jelastic.api.Response;
import com.jelastic.api.ResponseInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

/**
 * @name Jelastic API Client
 * @version 8.11.2
 * @copyright Jelastic, Inc.
 */
public class ListResponse extends Response {

    private List responses = new ArrayList();

    private Class genericClass;

    private static final String RESPONSES_KEY = "responses";

    public ListResponse() {
        super(OK);
    }

    public ListResponse(int result, String error) {
        super(result, error);
    }

    public ListResponse(List responses, Class genericClass) {
        super(OK);
        this.responses = responses;
        this.genericClass = genericClass;
    }

    public List getResponses() {
        return responses;
    }

    public void setResponses(List responses) {
        this.responses = responses;
    }

    @Override
    public JSONObject _toJSON() throws JSONException {
        JSONObject json = super._toJSON();
        if (responses != null) {
            JSONArray jsonArray = new JSONArray();
            for (ResponseInterface response : responses) {
                jsonArray.put(response.toJSON());
            }
            json.put(RESPONSES_KEY, jsonArray);
            if (genericClass != null) {
                json.put("className", genericClass.getCanonicalName());
            }
        }
        return json;
    }

    @Override
    protected ListResponse _fromJSON(JSONObject json) throws JSONException {
        super._fromJSON(json);
        if (json.has("className")) {
            String clazzName = json.getString("className");
            try {
                genericClass = Class.forName(clazzName);
            } catch (ClassNotFoundException ex) {
                try {
                    clazzName = json.getString("className").replace(".server", "");
                    genericClass = Class.forName(clazzName);
                } catch (ClassNotFoundException e) {
                    throw new JSONException(e);
                }
            }
        }
        responses = new ArrayList<>();
        if (json.has(RESPONSES_KEY)) {
            JSONArray arrayJson = json.getJSONArray(RESPONSES_KEY);
            for (int i = 0; i < arrayJson.length(); i++) {
                try {
                    Object item = genericClass.newInstance();
                    responses.add((ResponseInterface) ((ResponseInterface) item).fromJSON(arrayJson.getJSONObject(i)));
                } catch (Exception ex) {
                }
            }
        }
        return this;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy