geoportal-data-common/src/main/java/org/gcube/application/geoportalcommon/geoportal/GeoportalConfigUtil.java

81 lines
2.5 KiB
Java

package org.gcube.application.geoportalcommon.geoportal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JsonOrgJsonProvider;
/**
* The Class GeoportalConfigUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Sep 15, 2022
*/
public class GeoportalConfigUtil {
private static Logger LOG = LoggerFactory.getLogger(GeoportalConfigUtil.class);
/**
* Read roles for STEP id.
*
* @param handler the handler
* @param stepID the step ID
* @return the list
* @throws Exception the exception
*/
public static List<String> readRolesForSTEPId(HandlerDeclaration handler, String stepID) throws Exception {
LOG.debug("readRolesForSTEPId called for stepID {}, handler {}", stepID, handler);
List<String> roles = new ArrayList<String>();
try {
com.jayway.jsonpath.Configuration configuration = com.jayway.jsonpath.Configuration.builder()
.jsonProvider(new JsonOrgJsonProvider()).build();
String toJSON = handler.getConfiguration().toJson();
LOG.debug("Handler to JSON: " + toJSON);
JSONObject jObject = new JSONObject(toJSON);
JsonPath jsonPath = JsonPath.compile("$.step_access[?(@.STEP == '" + stepID + "' )].roles");
LOG.trace("jsonPath: " + jsonPath.getPath());
// $..book[?(@.price <= $['expensive'])]
JSONArray data = jsonPath.read(jObject, configuration);
LOG.debug("jsonPath matching data lenght: " + data.length());
HashSet<String> listdata = new HashSet<String>(data.length());
if(data.length()>0) {
LOG.debug("stepID found");
try {
JSONArray arrayRoles = new JSONArray(data.get(0).toString());
for (int i = 0; i < arrayRoles.length(); i++) {
String role = arrayRoles.get(i).toString();
LOG.info("for STEP_ID {} read role {}", stepID, role);
listdata.add(role);
}
}catch (Exception e) {
LOG.warn("Error on reading array roles for STEP_ID: "+stepID, e);
}
}
roles = listdata.stream().collect(Collectors.toList());
LOG.info("for STEP_ID {} returning Roles {} ", stepID, roles);
} catch (Exception e) {
LOG.warn("Error occurred on reading roles into handler {} returning no role", handler);
}
return roles;
}
}