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

com.jelastic.api.development.response.interfaces.ArrayItem Maven / Gradle / Ivy

The newest version!
package com.jelastic.api.development.response.interfaces;

import com.jelastic.api.core.utils.DateUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alexey Shponarsky
 */
public abstract class ArrayItem {

    public static final String ID = "id";

    public void set(final String name, final Object value) {
        Permissions perms = new Permissions();
        perms.add(new AllPermission());
        ProtectionDomain domain = new ProtectionDomain(new CodeSource((URL) null, (Certificate[]) null), perms);
        AccessControlContext relaxedAcc = new AccessControlContext(new ProtectionDomain[]{domain});
        final Class clazz = getClass();
        final Object _this = this;

        AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Field field = null;
                    try {
                        field = clazz.getDeclaredField(name);
                    } catch (NoSuchFieldException ex1) {
                        try {
                            field = clazz.getField(name);
                        } catch (NoSuchFieldException ex2) {
                        }
                    }
                    field.setAccessible(true);
                    field.set(_this, value);
                    return 0;
                } catch (Exception ex) {
                    //ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }, relaxedAcc);

    }

    public Object get(final String name) {
        Permissions perms = new Permissions();
        perms.add(new AllPermission());
        ProtectionDomain domain = new ProtectionDomain(new CodeSource((URL) null, (Certificate[]) null), perms);
        AccessControlContext relaxedAcc = new AccessControlContext(new ProtectionDomain[]{domain});
        final Class clazz = getClass();
        final Object _this = this;

        return AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Field field = null;
                    try {
                        field = clazz.getDeclaredField(name);
                    } catch (NoSuchFieldException ex1) {
                        try {
                            field = clazz.getField(name);
                        } catch (NoSuchFieldException ex2) {
                        }
                    }
                    if (field != null) {
                        field.setAccessible(true);
                        return field.get(_this);
                    } else {
                        String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
                        Method method = null;
                        try {
                            method = clazz.getDeclaredMethod(methodName);
                        } catch (NoSuchMethodException ex1) {
                            try {
                                method = clazz.getMethod(methodName);
                            } catch (NoSuchMethodException ex2) {
                            }
                        }
                        if (method != null) {
                            method.setAccessible(true);
                            return method.invoke(_this);
                        } else {
                            throw new RuntimeException("field [" + name + "] or method [" + methodName + "] doesn't exist");
                        }
                    }
                } catch (Exception ex) {
                    //ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }, relaxedAcc);

    }

    public JSONObject _toJSON() throws JSONException {

        JSONObject json = new JSONObject();
        primaryKeyToJson(json);
        for (Field field : this.getClass().getDeclaredFields()) {

            Object value = get(field.getName());
            if (value != null) {
                if (ArrayItem.class.isAssignableFrom(field.getType())) {
                    json.put(field.getName(), ((ArrayItem) value)._toJSON());
                } else {
                    json.put(field.getName(), value);
                }
            }
        }

        return json;
    }

    public ArrayItem _fromString(String stringJson) throws JSONException {
        JSONObject json = new JSONObject(stringJson);
        return _fromJSON(json);
    }

    public ArrayItem _fromJSON(JSONObject json) throws JSONException {
        primaryKeyFromJson(json);
        for (Field field : this.getClass().getDeclaredFields()) {
            if (json.has(field.getName())) {
                try {
                    if (ArrayItem.class.isAssignableFrom(field.getType())) {
                        set(field.getName(), ((ArrayItem) Class.forName(field.getType().getCanonicalName()).newInstance())._fromJSON(json.getJSONObject(field.getName())));
                    } else {
                        field.set(this, getFromJson(field, json));
                    }
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return this;
    }

    private Object getFromJson(Field field, JSONObject jsonObject) throws JSONException {
        if (field.getType().equals(String.class)) {
            return jsonObject.getString(field.getName());
        } else if (field.getType().equals(Integer.class) || field.getType().equals(int.class)) {
            return jsonObject.getInt(field.getName());
        } else if (field.getType().equals(Long.class) || field.getType().equals(long.class)) {
            return jsonObject.getLong(field.getName());
        } else if (field.getType().equals(Double.class) || field.getType().equals(double.class)) {
            return jsonObject.getDouble(field.getName());
        } else if (field.getType().equals(Date.class)) {
            try {
                return DateUtils.parseSqlDateTime(jsonObject.getString(field.getName()));
            } catch (ParseException ex) {
                throw new JSONException("JSONObject['" + field.getName() + "'] is not a Date.. Original value: [" + jsonObject.getString(field.getName()) + "]");
            }
        } else if (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class)) {
            String stringBoolean = jsonObject.getString(field.getName());
            if (stringBoolean.equalsIgnoreCase(Boolean.TRUE.toString()) || stringBoolean.equals("1")) {
                return Boolean.TRUE;
            } else if (stringBoolean.equalsIgnoreCase(Boolean.FALSE.toString()) || stringBoolean.equals("0")) {
                return Boolean.FALSE;
            } else {
                throw new JSONException("JSONObject['" + field.getName() + "'] is not a Boolean.");
            }
        }

        return jsonObject.get(field.getName());
    }

    protected void primaryKeyToJson(JSONObject json) throws JSONException {
        try {
            Method getIdMethod = this.getClass().getMethod("getId", null);
            int id = (int) (Integer) getIdMethod.invoke(this);
            json.put("id", id);
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }
    }

    protected void primaryKeyFromJson(JSONObject json) throws JSONException {
        if (json.has("id")) {
            try {
                Method getIdMethod = this.getClass().getMethod("setId", int.class);
                getIdMethod.invoke(this, json.getInt("id"));
            } catch (NoSuchMethodException e) {
            } catch (InvocationTargetException e) {
            } catch (IllegalAccessException e) {
            }
        }
    }

    protected int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public static Map convertJSONObjectToStringMap(JSONObject jsonObject) {
        Iterator iterator = jsonObject.keys();
        Map map = new HashMap<>();

        while (iterator.hasNext()) {
            String fieldName = iterator.next().toString();
            String fieldValue = null;

            if (!jsonObject.isNull(fieldName)) {
                try {
                    fieldValue = jsonObject.getString(fieldName);
                } catch (JSONException ignored) {
                }
            }

            map.put(fieldName, fieldValue);
        }

        return map;
    }
}