gcube-cms-suite/geoportal-common/src/main/java/org/gcube/application/geoportal/common/model/JSONPathWrapper.java

92 lines
3.2 KiB
Java

package org.gcube.application.geoportal.common.model;
import com.jayway.jsonpath.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.common.JSONSerializationProvider;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import java.util.*;
@Slf4j
public class JSONPathWrapper {
public static Configuration JSON_PATH_ALWAYS_LIST_CONFIG=null;
public static Configuration JSON_PATH_PATHS_CONFIGURATION=null;
static {
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.forPackage("org.gcube.application")
.filterInputsBy(new FilterBuilder().includePackage("org.gcube.application")));
reflections.getSubTypesOf(JSONSerializationProvider.class).iterator().forEachRemaining(providerClass->{
if(!providerClass.isInterface()){
try {
log.warn("Loading JSON Provider {} ",providerClass);
JSONSerializationProvider provider = providerClass.newInstance();
provider.setJSONWrapperDefaults();
}catch (Throwable t){
log.error("Unable to instantiate provider "+providerClass,t);
}
}
});
JSON_PATH_ALWAYS_LIST_CONFIG= Configuration.builder().options(Option.ALWAYS_RETURN_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build();
JSON_PATH_PATHS_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build();
}
@Getter
DocumentContext ctx=null;
public JSONPathWrapper(String json) {
ctx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(json);
}
public List<Object> getByPath(String path){
return ctx.read(path);
}
public <T> List<T> getByPath(String path,Class<T> clazz){
List<T> l= ctx.read(path, new TypeRef<List<T>>() {});
l.removeIf(p->p==null);
return l;
}
public JSONPathWrapper set(String path, Object toSet){
ctx.set(path,toSet);
return this;
}
// public static final DocumentContext addElement(DocumentContext ctx,String path) throws JsonPathException{
// JsonPath jPath=JsonPath.compile(path);
// if(jPath.isDefinite()) {
// String parent=path.substring(0,path.lastIndexOf("."));
// List<String> found=ctx.read(parent);
// if(found==null || found.size()==0 || found.get(0)==null) {
// //missing parent, use recursion
// addElement(ctx,parent);
// }
// // found parent, adding element
// String element=path.substring(path.lastIndexOf(".")+1);
//
// Object value=new HashMap<String,String>();
// if(element.contains("[")) {
// value=new ArrayList<Object>(Collections.singletonList(value));
//
// element=element.substring(0,element.indexOf("["));
// }
//
// ctx.put(parent, element, value);
// return ctx;
// }else throw new JsonPathException("Unable to initialize non-definite path : "+path);
// }
}