
com.jelastic.api.environment.response.ObjectResponse Maven / Gradle / Ivy
The newest version!
/*Server class MD5: a08e7469e12ec21bed87253ec4549eeb*/
package com.jelastic.api.environment.response;
import com.jelastic.api.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @name Jelastic API Client
* @version 8.11.2
* @copyright Jelastic, Inc.
*/
public class ObjectResponse extends Response {
public static final String WARNINGS = "warnings";
private String name = "object";
private Object object;
private List warnings;
public ObjectResponse(Object object) {
super(Response.OK);
this.object = object;
}
public ObjectResponse(String name, Object object) {
super(Response.OK);
this.object = object;
this.name = name;
}
public ObjectResponse(int result, String error) {
super(result, error);
}
public ObjectResponse(int result, String error, int reason) {
super(result, error, reason);
}
public ObjectResponse(Response response) {
super(response.getResult(), response.getError());
if (response.getRaw() != null && response.getRaw().length() != 0) {
this.setRaw(response.getRaw());
}
}
public ObjectResponse() {
super(Response.OK);
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public List getWarnings() {
return warnings;
}
public void setWarnings(List warnings) {
this.warnings = warnings;
}
@Override
public ObjectResponse fromJSON(JSONObject json) {
Response response = super.fromJSON(json);
try {
if (!json.has(name)) {
Iterator i = json.keys();
while (i.hasNext()) {
String key = String.valueOf(i.next());
Object value = json.get(key);
if (value instanceof JSONObject) {
name = key;
break;
}
}
}
if (json.has(name)) {
object = json.get(name);
}
if (json.has(WARNINGS)) {
warnings = new ArrayList<>();
JSONArray warns = json.getJSONArray(WARNINGS);
for (int i = 0; i < warns.length(); i++) {
warnings.add(warns.getString(i));
}
}
} catch (JSONException ex) {
response = new Response(ERROR_UNKNOWN, ex.toString());
}
setResult(response.getResult());
setError(response.getError());
return this;
}
@Override
public JSONObject toJSON() {
JSONObject json = super.toJSON();
try {
if (object != null) {
json.put(name, object);
}
if (warnings != null) {
JSONArray warns = new JSONArray();
for (String w : warnings) {
warns.put(w);
}
json.put(WARNINGS, warns);
}
} catch (Exception ex) {
ex.printStackTrace();
try {
json.put("result", Response.ERROR_UNKNOWN).put("error", ex.toString());
} catch (JSONException exc) {
}
}
return json;
}
}