package jp.dip.arimodoki.common;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.stream.JsonReader;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Loader;
import javassist.NotFoundException;
@Scope("prototype")
@Component
public class JsonConvert implements JsonConvertIf, CConst {
Gson mygson = new Gson();
public Object Deserialize(String jsonData, Object parseObj) throws Exception {
if(jsonData == null || jsonData.equals("")) return null;
if(parseObj == null) return null;
InputStreamReader isr = new InputStreamReader( new ByteArrayInputStream(jsonData.getBytes()));
JsonReader jsr = new JsonReader( isr );
return (Object) mygson.fromJson( jsr, parseObj.getClass() );
}
public Object Deserialize(String jsonData, String rootClassName) throws Exception {
return this.createJson2DynamicClass(jsonData, rootClassName);
}
public String Serialize(Object obj) throws Exception {
if(obj == null) return null;
return mygson.toJson(obj);
}
public String decode(String encStr) throws Exception {
if(encStr == null || encStr.equals("")) return null;
return this.decode(encStr,"UTF-8");
}
public String decode(String encStr, String charcode) throws Exception {
if(encStr == null || encStr.equals("")) return null;
if(charcode == null || charcode.equals("")) return null;
String decStr = "";
String decparam = URLDecoder.decode(encStr,charcode);
int len = decparam.length();
int last = decparam.lastIndexOf('=');
if(last == len-1) {
decStr = decparam.substring(0, len-1);
} else {
decStr = decparam;
}
return decStr;
}
private synchronized Object createJson2DynamicClass(String jsonData, String clsName) throws Exception {
if(jsonData == null || jsonData.equals("")) return null;
if(clsName == null || clsName.equals("")) return null;
int[] depth = {0};
this.createJson2DynamicClass(jsonData,clsName, "", depth);
return this.convertJson2DynamicClass(jsonData,clsName, "");
}
private Object createJson2DynamicClass(String jsonData, String clsName, String pClassName, int[] depth) throws Exception {
CtClass cc = null;
String cname = "";
String propName = "";
String methodName = "";
String mStr = "";
depth[0]++;
logger.log_dbg(this, "depth["+depth[0]+"]");
String fullClassName = "";
if(pClassName.equals("")) {
fullClassName = clsName;
} else {
fullClassName = pClassName + "." + clsName;
}
logger.log_dbg("makeClass["+fullClassName+"]");
try {
cc= ClassPool.getDefault().get(fullClassName);
} catch(NotFoundException ne) {
logger.log_info(this, "createJson2DynamicClass create clsName["+fullClassName+"]");
cc= ClassPool.getDefault().makeClass(fullClassName);
logger.log_info("new makeClass["+fullClassName+"]");
}
JsonParser jp = new JsonParser();
JsonElement je = null;
Set<Map.Entry<String, JsonElement>> entrySet = null;
Set<Map.Entry<String, JsonElement>> chkentrySet = null;
try {
logger.log_info("Parse["+jsonData+"]");
je = jp.parse(jsonData);
entrySet = je.getAsJsonObject().entrySet();
} catch(Exception e) {
logger.log_error(e, "JSON parse error["+jsonData+"]");
return null;
}
Iterator<Map.Entry<String, JsonElement>> it = entrySet.iterator();
logger.log_dbg("Map entrySet Size["+entrySet.size()+"]");
CtMethod get_method = null;
CtMethod set_method = null;
boolean newFlag = false;
while(it.hasNext()) {
newFlag = false;
Map.Entry<String, JsonElement> entry = it.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
logger.log_dbg("key["+key+"]");
if ( value.isJsonNull() ) {
logger.log_warn("JsonValue Is Null key["+key+"]");
} else if ( value.isJsonObject() ) {
logger.log_dbg("JsonObject key["+key+"],value["+value.toString()+"]");
if(createJson2DynamicClass( value.toString(), key, fullClassName, depth ) == null) {
continue;
}
propName = "private Object "+key+" = null;";
logger.log_dbg("JsonObject propName["+propName+"]");
newFlag = false;
try {
if(cc.isFrozen()) {
cc.defrost();
}
try {
cc.getField(key);
} catch(NotFoundException e) {
CtField field = CtField.make(propName, cc);
cc.addField(field);
newFlag = true;
}
} catch(Exception e) {
logger.log_error(this, e);
}
String first = key.substring(0, 1).toUpperCase();
methodName = first + key.substring(1);
mStr = "public Object get"+methodName+"() {return "+key+ ";}";
try {
if(newFlag) {
get_method = CtNewMethod.make(mStr, cc);
cc.addMethod(get_method);
logger.log_dbg(this, "JsonObject getter methodName["+fullClassName+"."+mStr+"]");
}
} catch(Exception e) {
logger.log_error(this, e);
}
mStr = "public void set"+methodName+"(Object value) {"+key+ "=value;}";
try {
if(newFlag) {
set_method = CtNewMethod.make(mStr, cc);
cc.addMethod(set_method);
}
} catch(Exception e) {
logger.log_error(this, e);
}
} else if ( value.isJsonArray() ) {
logger.log_dbg("JsonArray key["+key+"],value["+value.toString()+"]");
cname = key + "List";
JsonArray ar = value.getAsJsonArray();
boolean jsonObjFlag = false;
for(JsonElement el : ar) {
logger.log_dbg("el.toString()["+el.toString()+"]");
try {
JsonElement jeckeck = jp.parse(el.toString());
chkentrySet = jeckeck.getAsJsonObject().entrySet();
} catch(Exception e) {
logger.log_dbg("el.toString()["+el.toString()+"]");
jsonObjFlag = true;
}
if(!jsonObjFlag) {
if(createJson2DynamicClass( el.toString(), cname, fullClassName, depth ) == null) {
continue;
}
}
}
propName = "private Object "+key+" = null;";
logger.log_dbg("JsonArray propName["+fullClassName+"."+propName+"]");
newFlag = false;
try {
if(cc.isFrozen()) {
cc.defrost();
}
try {
cc.getField(key);
} catch(NotFoundException e) {
CtField field = CtField.make(propName, cc);
cc.addField(field);
newFlag = true;
}
} catch(Exception e) {
logger.log_error(this, e);
}
String first = key.substring(0, 1).toUpperCase();
methodName = first + key.substring(1);
mStr = "public Object get"+methodName+"() {return "+key+ ";}";
try {
if(newFlag) {
get_method = CtNewMethod.make(mStr, cc);
cc.addMethod(get_method);
logger.log_dbg(this, "getter methodName["+fullClassName+"."+mStr+"]");
}
} catch(Exception e) {
logger.log_error(this, e);
}
mStr = "public void set"+methodName+"(Object value) {"+key+ "=value;}";
try {
if(newFlag) {
set_method = CtNewMethod.make(mStr, cc);
cc.addMethod(set_method);
}
} catch(Exception e) {
logger.log_error(this, e);
}
} else if ( value.isJsonPrimitive() ) {
logger.log_dbg("JsonPrimitive key["+key+"],value["+value.getAsString()+"]");
JsonPrimitive jval = value.getAsJsonPrimitive();
if(jval.isBoolean()) {
propName = "private boolean " + key + "=false;";
} else if(jval.isNumber()) {
String val = value.toString();
logger.log_dbg("prop val["+val+"]");
if(val.indexOf(".")>=0) {
propName = "private double " + key + "=0.0;";
} else {
propName = "private long " + key + "=0L;";
}
} else {
propName = "private String " + key + "=\"\";";
}
logger.log_dbg("JsonPrimitive propName["+fullClassName+"."+propName+"]");
try {
if(cc.isFrozen()) {
cc.defrost();
}
try {
cc.getField(key);
} catch(NotFoundException e) {
CtField field = CtField.make(propName, cc);
cc.addField(field);
newFlag = true;
}
} catch(CannotCompileException e) {
logger.log_error(this, e);
}
String first = key.substring(0, 1).toUpperCase();
methodName = first + key.substring(1);
if(jval.isBoolean()) {
try {
get_method = CtNewMethod.make("public boolean get"+methodName+"() {return "+key+ ";}", cc);
} catch(Exception e) {
logger.log_warn("Make Bool getter Method");
}
} else if(jval.isNumber()) {
String val = value.toString();
if(val.indexOf(".")>=0) {
try {
get_method = CtNewMethod.make("public double get"+methodName+"() {return "+key+ ";}", cc);
} catch(Exception e) {
logger.log_warn("Make Float getter Method");
}
} else {
try {
get_method = CtNewMethod.make("public long get"+methodName+"() {return "+key+ ";}", cc);
} catch(Exception e) {
logger.log_warn("Make Long getter Method");
}
}
} else {
try {
get_method = CtNewMethod.make("public String get"+methodName+"() {return "+key+ ";}", cc);
} catch(Exception e) {
logger.log_warn("Make String getter Method");
}
}
try {
logger.log_dbg("getter_methodName["+fullClassName+"."+get_method+"]");
if(newFlag)
cc.addMethod(get_method);
} catch(Exception e) {
logger.log_error(this, e);
}
if(jval.isBoolean()) {
try {
set_method = CtNewMethod.make("public void set"+methodName+"(boolean value) {"+key+ "=value;}", cc);
} catch(Exception e) {
logger.log_warn("Make Bool setter Method");
}
} else if(jval.isNumber()) {
String val = value.toString();
if(val.indexOf(".")>=0) {
try {
set_method = CtNewMethod.make("public void set"+methodName+"(double value) {"+key+ "=value;}", cc);
} catch(Exception e) {
logger.log_warn("Make Float setter Method");
}
} else {
try {
set_method = CtNewMethod.make("public void set"+methodName+"(long value) {"+key+ "=value;}", cc);
} catch(Exception e) {
logger.log_warn("Make Long setter Method");
}
}
} else {
try {
set_method = CtNewMethod.make("public void set"+methodName+"(String value) {"+key+ "=value;}", cc);
} catch(Exception e) {
logger.log_warn("Make String setter Method");
}
}
try {
logger.log_dbg("setter_methodName["+fullClassName+"."+set_method+"]");
if(newFlag)
cc.addMethod(set_method);
} catch(Exception e) {
logger.log_warn("addMethod");
}
}
}
logger.log_dbg(this, "ESCAPE depth["+depth[0]+"]");
depth[0]--;
Loader cl = new Loader(ClassPool.getDefault());
return cc.toClass(cl, cl.getClass().getProtectionDomain());
}
private Object convertJson2DynamicClass(String jsonData, String clsName, String pClassName) throws Exception {
Class<?> cclass = null;
Object newclass = null;
Object nchild = null;
String cname = "";
String fullClassName = "";
if(pClassName.equals("")) {
fullClassName = clsName;
} else {
fullClassName = pClassName + "." + clsName;
}
logger.log_dbg("fullClassName ["+fullClassName+"]");
try {
ClassPool pool = ClassPool.getDefault();
Loader cl = new Loader(pool);
cclass = cl.loadClass(fullClassName);
newclass = (Object)cclass.newInstance();
} catch(Exception e) {
logger.log_error(e);
logger.log_error(this, "convertJson2DynamicClass newInstance Error");
return null;
} finally {
}
JsonParser jp = new JsonParser();
JsonElement je = null;
Set<Map.Entry<String, JsonElement>> entrySet = null;
Set<Map.Entry<String, JsonElement>> chkentrySet = null;
logger.log_dbg("parse ["+jsonData+"]");
try {
je = jp.parse(jsonData);
entrySet = je.getAsJsonObject().entrySet();
} catch(Exception e) {
logger.log_dbg("parse ERRRRROOOOORRR["+jsonData+"]");
return null;
}
logger.log_dbg("entrySet size ["+entrySet.size()+"]");
Iterator<Map.Entry<String, JsonElement>> it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry<String, JsonElement> entry = it.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
logger.log_dbg("key["+key+"]");
if ( value.isJsonNull() ) {
logger.log_warn("JsonValue Is Null key["+key+"]");
} else if ( value.isJsonObject() ) {
logger.log_dbg("JsonObject key["+key+"],value["+value.toString()+"]");
nchild = convertJson2DynamicClass( value.toString(), key, fullClassName );
if(nchild != null) {
logger.log_dbg("JsonObjectsetObject key["+key+"]");
this.setObject(newclass, key, nchild);
}
} else if ( value.isJsonArray() ) {
logger.log_dbg("JsonArray key["+key+"]");
cname = key + "List";
JsonArray ar = value.getAsJsonArray();
List<Object> carray = new ArrayList<>();
boolean leafChek = false;
JsonPrimitive jval = null;
for(JsonElement el : ar) {
try {
je = jp.parse(el.toString());
chkentrySet = je.getAsJsonObject().entrySet();
} catch(Exception e) {
jval = el.getAsJsonPrimitive();
leafChek = true;
break;
}
}
if(leafChek) {
if(jval.isBoolean()) {
Boolean[] b = new Boolean[ar.size()];
int i = 0;
for(JsonElement el : ar) {
b[i] = el.getAsBoolean();
i++;
}
this.setObject(newclass, key, b);
} else if(jval.isNumber()) {
String val = value.toString();
if(val.indexOf(".")>=0) {
Double[] d = new Double[ar.size()];
int i = 0;
for(JsonElement el : ar) {
d[i] = el.getAsNumber().doubleValue();
i++;
}
this.setObject(newclass, key, d);
} else {
Long[] l = new Long[ar.size()];
int i = 0;
for(JsonElement el : ar) {
l[i] = el.getAsNumber().longValue();
i++;
}
this.setObject(newclass, key, l);
}
} else {
String[] s = new String[ar.size()];
int i = 0;
for(JsonElement el : ar) {
s[i] = el.getAsString();
i++;
}
this.setObject(newclass, key, s);
}
} else {
for(JsonElement el : ar) {
logger.log_dbg("JsonArray Element key["+key+"],value["+el.toString()+"]");
nchild = convertJson2DynamicClass( el.toString(), cname, fullClassName );
if(nchild == null) {
continue;
}
carray.add(nchild);
}
this.setObject(newclass, key, carray);
}
} else if ( value.isJsonPrimitive() ) {
logger.log_dbg("JsonPrimitive key["+key+"], value["+value.getAsString()+"]");
JsonPrimitive jval = value.getAsJsonPrimitive();
if(jval.isBoolean()) {
this.setBoolean(newclass, key, value.getAsBoolean());
} else if(jval.isNumber()) {
String val = value.toString();
logger.log_dbg("long value ["+val+"]");
if(val.indexOf(".")>=0) {
this.setDouble(newclass, key, value.getAsNumber().doubleValue());
} else {
this.setLong(newclass, key, value.getAsNumber().longValue());
}
} else {
this.setString(newclass, key, value.getAsString());
}
}
}
return newclass;
}
public void print_json(String jsonData) throws Exception {
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonData);
Set<Map.Entry<String, JsonElement>> entrySet = je.getAsJsonObject().entrySet();
Iterator<Map.Entry<String, JsonElement>> it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry<String, JsonElement> entry = it.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
if ( value.isJsonNull() ) {
return;
} else if ( value.isJsonObject() ) {
logger.log_info(this, "JsonObject key["+key+"],value["+value.toString()+"]");
} else if ( value.isJsonArray() ) {
logger.log_info(this, "JsonArray key["+key+"],value["+value.toString()+"]");
JsonArray ar = value.getAsJsonArray();
for(JsonElement el : ar) {
logger.log_info(this, "JsonArray Element key["+key+"],value["+el.toString()+"]");
print_json( el.toString() );
}
} else if ( value.isJsonPrimitive() ) {
logger.log_info(this, "JsonPrimitive key["+key+"],value["+value.getAsString()+"]");
} else {
if ( value.isJsonNull() ) {
logger.log_info(this, "NULL");
} else {
logger.log_info(this, "JsonValue["+value.toString()+"]");
}
}
}
}
private Object getValue(Object o, String propertyName) throws Exception {
Class<?> cls = o.getClass();
Method method = null;
Object data = null;
String getterName = "get";
getterName += propertyName.substring(0, 1).toUpperCase();
getterName += propertyName.substring(1);
logger.log_dbg("getterName["+getterName+"]");
try {
method = cls.getDeclaredMethod(getterName);
} catch(Exception e) {
logger.log_error(e);
throw new Exception(e);
}
Object[] args = null;
try {
data = method.invoke(o, args);
} catch(Exception e) {
logger.log_error(e);
throw new Exception(e);
}
return data;
}
public String getString(Object o, String propertyName) throws Exception {
Object ret = this.getValue(o, propertyName);
return (String)ret.toString();
}
public int getInt(Object o, String propertyName) throws Exception {
Object ret = this.getValue(o, propertyName);
return Integer.parseInt(ret.toString());
}
public long getLong(Object o, String propertyName) throws Exception {
Object ret = this.getValue(o, propertyName);
return Long.parseLong(ret.toString());
}
public double getDouble(Object o, String propertyName) throws Exception {
Object ret = this.getValue(o, propertyName);
return Double.parseDouble(ret.toString());
}
public Object getObject(Object o, String propertyName) throws Exception {
return (Object)this.getValue(o, propertyName);
}
public boolean getBoolean(Object o, String propertyName) throws Exception {
return (boolean)this.getValue(o, propertyName);
}
private void setValue(Object o, String propertyName, Object value, Class<?>[] param) throws Exception {
String setterName = "set";
setterName += propertyName.substring(0, 1).toUpperCase();
setterName += propertyName.substring(1);
Class<?> c = o.getClass();
Method method = c.getMethod(setterName, param);
try {
Object[] args = new Object[]{ value };
method.invoke(o, args);
} catch (Exception e) {
logger.log_error(e);
}
}
public void setString(Object o, String propertyName, String value) throws Exception {
Class<?>[] param = new Class[]{String.class};
this.setValue(o, propertyName, value, param);
}
public void setInt(Object o, String propertyName, int value) throws Exception {
Class<?>[] param = new Class[]{int.class};
this.setValue(o, propertyName, value, param);
}
public void setLong(Object o, String propertyName, long value) throws Exception {
Class<?>[] param = new Class[]{long.class};
this.setValue(o, propertyName, value, param);
}
public void setDouble(Object o, String propertyName, double value) throws Exception {
Class<?>[] param = new Class[]{double.class};
this.setValue(o, propertyName, value, param);
}
public void setList(Object o, String propertyName, List<?> value) throws Exception {
Class<?>[] param = new Class[]{List.class};
this.setValue(o, propertyName, value, param);
}
public void setBoolean(Object o, String propertyName, boolean value) throws Exception {
Class<?>[] param = new Class[]{boolean.class};
this.setValue(o, propertyName, value, param);
}
public void setObject(Object o, String propertyName, Object value) throws Exception {
Class<?>[] param = new Class[]{Object.class};
this.setValue(o, propertyName, value, param);
}
private void removeJson2DynamicClass(String jsonData, String clsName, String pClassName) throws Exception {
Class<?> cclass = null;
CtClass cc = null;
String cname = "";
String propName = "";
String methodName = "";
String mStr = "";
String fullClassName = "";
if(pClassName.equals("")) {
fullClassName = clsName;
} else {
fullClassName = pClassName + "." + clsName;
}
logger.log_dbg("remove target FullClass["+fullClassName+"]");
try {
cc= ClassPool.getDefault().get(fullClassName);
logger.log_dbg("detach FullClass["+fullClassName+"]");
cc.detach();
} catch(Exception ne) {
return;
}
JsonParser jp = new JsonParser();
JsonElement je = null;
Set<Map.Entry<String, JsonElement>> entrySet = null;
Set<Map.Entry<String, JsonElement>> chkentrySet = null;
try {
je = jp.parse(jsonData);
entrySet = je.getAsJsonObject().entrySet();
} catch(Exception e) {
logger.log_error(e);
return;
}
Iterator <Map.Entry<String, JsonElement>> it = entrySet.iterator();
logger.log_dbg("Map entrySet Size["+entrySet.size()+"]");
CtMethod get_method = null;
CtMethod set_method = null;
boolean newFlag = false;
while(it.hasNext()) {
newFlag = false;
Map.Entry<String, JsonElement> entry = it.next();
String key = entry.getKey();
JsonElement value = entry.getValue();
logger.log_dbg("key["+key+"]");
if ( value.isJsonNull() ) {
logger.log_warn("JsonValue Is Null key["+key+"]");
} else if ( value.isJsonObject() ) {
logger.log_dbg("JsonObject key["+key+"],value["+value.toString()+"]");
removeJson2DynamicClass( value.toString(), key, fullClassName);
} else if ( value.isJsonArray() ) {
logger.log_dbg("JsonArray key["+key+"],value["+value.toString()+"]");
cname = key + "List";
JsonArray ar = value.getAsJsonArray();
boolean jsonObjFlag = false;
for(JsonElement el : ar) {
logger.log_dbg("el.toString()["+el.toString()+"]");
try {
JsonElement jeckeck = jp.parse(el.toString());
chkentrySet = jeckeck.getAsJsonObject().entrySet();
} catch(Exception e) {
logger.log_dbg("el.toString()["+el.toString()+"]");
jsonObjFlag = true;
}
if(!jsonObjFlag) {
removeJson2DynamicClass( el.toString(), cname, fullClassName);
}
}
} else if ( value.isJsonPrimitive() ) {
;
}
}
return;
}
}
|