Merge pull request 'feature_22506' (#3) from feature_22506 into master

Reviewed-on: #3
This commit is contained in:
Francesco Mangiacrapa 2022-01-13 16:51:29 +01:00
commit 274be83613
23 changed files with 2426 additions and 118 deletions

View File

@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.3.0-SNAPSHOT] - 2021-12-03
#### Enhancements
- [#22506] Added classes to read configurations and common classes from the GNA components: DataEntry and DataViewer
## [v1.2.0] - 2021-09-29
#### Enhancements

View File

@ -10,7 +10,7 @@
<groupId>org.gcube.application</groupId>
<artifactId>geoportal-data-common</artifactId>
<version>1.2.0</version>
<version>1.3.0-SNAPSHOT</version>
<description>GeoPortal Data Common is common library used by GUI components developed for GeoNA</description>
<scm>

View File

@ -0,0 +1,134 @@
package org.gcube.application.geoportalcommon;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.gcube.application.geoportalcommon.config.CSVFile;
import org.gcube.application.geoportalcommon.config.CSVReader;
import org.gcube.application.geoportalcommon.config.CSVRow;
import org.gcube.application.geoportalcommon.config.FileUtil;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.exception.GNAConfigException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class GNAConfigsConverter.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 21, 2021
*/
public class GNAConfigsConverter {
private static final Logger LOG = LoggerFactory.getLogger(GNAConfigsConverter.class);
public GNAConfigsConverter() {
}
/**
* Read list items config.
*
* @param contentValue the content value
* @return the list
* @throws GNAConfigException the GNA user rights config exception
*/
public List<ItemField> readListItemsConfig(String contentValue) throws GNAConfigException {
LOG.debug("readListItemsConfig called");
File configurationFile = null;
List<ItemField> listItemFields = new ArrayList<ItemField>();
try {
configurationFile = FileUtil.inputStreamToTempFile(contentValue, "GNA_ListItems_Configs"+new Random().nextInt());
CSVReader reader = new CSVReader(configurationFile);
CSVFile csvFile = reader.getCsvFile();
if(LOG.isTraceEnabled()) {
LOG.trace("CSV Header Row: "+csvFile.getHeaderRow());
}
List<CSVRow> rows = csvFile.getValueRows();
LOG.debug("CSV Value Row are: "+rows);
// Starting from index 1 (means the second row in the CSV)
for (int i = 0; i < rows.size(); i++) {
LOG.trace(i + " row");
ItemField itemField = new ItemField();
CSVRow row = rows.get(i);
// mapping to ItemFiel
List<String> rowValues = row.getListValues();
LOG.debug("rowValues: " + rowValues);
itemField.setDisplayName(rowValues.get(0));
// Reading JSON Fields
String[] jsonFields = rowValues.get(1).split(";");
List<String> theJsonFields = new ArrayList<String>(jsonFields.length);
for (String jsonField : jsonFields) {
theJsonFields.add(jsonField.trim());
}
itemField.setJsonFields(theJsonFields);
// Display as result
if (checkYesNoValue(rowValues.get(2))) {
itemField.setDisplayAsResult(true);
}
// Sortable
if (checkYesNoValue(rowValues.get(3))) {
itemField.setSortable(true);
}
// Searchable
if (checkYesNoValue(rowValues.get(4))) {
itemField.setSearchable(true);
}
listItemFields.add(itemField);
}
LOG.info("Returning item fields config: " + listItemFields);
return listItemFields;
} catch (Exception e) {
LOG.error("An error occurred on reading the GNA config from: " + contentValue, e);
throw new GNAConfigException("Error on reading the GNA config from: " + contentValue);
} finally {
if (configurationFile != null) {
try {
configurationFile.delete();
} catch (Exception e) {
// silent
}
}
}
}
/**
* Check yes no value.
*
* @param value the value
* @return true, if successful
*/
public static boolean checkYesNoValue(String value) {
if (value == null || value.isEmpty())
return false;
String lowerValue = value.toLowerCase();
if (lowerValue.equals("yes") || lowerValue.equals("true")) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,311 @@
package org.gcube.application.geoportalcommon;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.gcube.application.geoportalcommon.config.CSVFile;
import org.gcube.application.geoportalcommon.config.CSVReader;
import org.gcube.application.geoportalcommon.config.CSVRow;
import org.gcube.application.geoportalcommon.config.FileUtil;
import org.gcube.application.geoportalcommon.shared.GNADataEntryConfigProfile;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.config.ACTION_ON_ITEM;
import org.gcube.application.geoportalcommon.shared.config.GcubeUserRole;
import org.gcube.application.geoportalcommon.shared.config.RoleRights;
import org.gcube.application.geoportalcommon.shared.config.RoleRights.OPERATION_TYPE;
import org.gcube.application.geoportalcommon.shared.exception.ApplicationProfileNotFoundException;
import org.gcube.application.geoportalcommon.shared.exception.GNAConfigException;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.impl.QueryBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* The Class GNADataEntryConfigProfileReader.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 21, 2021
*/
public class GNADataEntryConfigProfileReader {
private static final String RESOURCE_PROFILE_BODY = "/Resource/Profile/Body";
public static final String SECONDARY_TYPE = "ApplicationProfile";
public static final String GENERIC_RESOURCE_NAME = "Geoportal-DataEntry-Configs";
private static final String PATH_TO_PERMISSIONS_PATH = RESOURCE_PROFILE_BODY + "/permssions_for_role";
private static final String PATH_TO_ITEM_FIELDS_CONFIG = RESOURCE_PROFILE_BODY + "/item_fields_config";
private String scope;
private static final Logger LOG = LoggerFactory.getLogger(GNADataEntryConfigProfileReader.class);
/**
* Instantiates a new application profile reader.
*/
public GNADataEntryConfigProfileReader() {
}
/**
* Read profile from infrastrucure.
*
* @return the map
* @throws Exception the exception
*/
protected GNADataEntryConfigProfile readProfileFromInfrastrucure() throws Exception {
LOG.info("called readProfileFromInfrastrucure");
String queryString = getGcubeGenericQueryString(SECONDARY_TYPE, GENERIC_RESOURCE_NAME);
this.scope = ScopeProvider.instance.get();
LOG.info("Scope " + scope + ", trying to perform query: " + queryString);
if (scope == null)
throw new Exception("Scope is null, set scope into ScopeProvider");
GNADataEntryConfigProfile gnDEC = new GNADataEntryConfigProfile();
String permissions_for_role = "";
String item_fields = "";
try {
LOG.info("Trying to fetch GR named: " + GENERIC_RESOURCE_NAME + ", in the scope: " + scope
+ ", SecondaryType: " + SECONDARY_TYPE);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("GR with SecondaryType: " + SECONDARY_TYPE
+ ", and name: " + GENERIC_RESOURCE_NAME + " is not registered in the scope: " + scope);
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(elem)));
XPathHelper helper = new XPathHelper(doc.getDocumentElement());
List<String> currValue = null;
String xPathExp = PATH_TO_PERMISSIONS_PATH + "/text()";
currValue = helper.evaluate(xPathExp);
if (currValue != null && currValue.size() > 0) {
permissions_for_role = currValue.get(0);
} else
throw new Exception("I'm not able to read the path: " + xPathExp);
// replacing \n with new_line string
LOG.debug("read " + PATH_TO_PERMISSIONS_PATH + ": " + permissions_for_role);
String value_with_new_lines = permissions_for_role.replaceAll("\\\\n", System.lineSeparator());
LOG.debug(PATH_TO_PERMISSIONS_PATH + " with new lines: " + value_with_new_lines);
List<RoleRights> listRoleRights = readRoleRightsConfig(value_with_new_lines);
gnDEC.setPermissionsForRole(listRoleRights);
xPathExp = PATH_TO_ITEM_FIELDS_CONFIG + "/text()";
currValue = helper.evaluate(xPathExp);
if (currValue != null && currValue.size() > 0) {
item_fields = currValue.get(0);
} else
throw new Exception("I'm not able to read the path: " + xPathExp);
// replacing \n with new_line string
LOG.debug("read " + PATH_TO_ITEM_FIELDS_CONFIG + ": " + item_fields);
value_with_new_lines = item_fields.replaceAll("\\\\n", System.lineSeparator());
LOG.debug(PATH_TO_ITEM_FIELDS_CONFIG + " with new lines: " + value_with_new_lines);
GNAConfigsConverter gnc = new GNAConfigsConverter();
List<ItemField> listItemFieldsConfig = gnc.readListItemsConfig(value_with_new_lines);
gnDEC.setListItemFields(listItemFieldsConfig);
LOG.info("returning: " + gnDEC);
return gnDEC;
}
} catch (Exception e) {
LOG.error("Error while trying to read the " + SECONDARY_TYPE + " with SecondaryType "
+ GENERIC_RESOURCE_NAME + " from scope " + scope, e);
return null;
} finally {
}
}
/**
* To gcube user role.
*
* @param name the name
* @return the gcube user role
*/
protected static GcubeUserRole toGcubeUserRole(String name) {
for (GcubeUserRole gCubeUserRole : GcubeUserRole.values()) {
if (gCubeUserRole.getName().equalsIgnoreCase(name))
return gCubeUserRole;
}
return null;
}
/**
* Read user rights config.
*
* @param permissions_for_role the permissions for role
* @return the list
* @throws GNAConfigException the GNA user rights config not found
* exception
*/
public List<RoleRights> readRoleRightsConfig(String permissions_for_role) throws GNAConfigException {
LOG.debug("readRoleRightsConfig called");
File configurationFile = null;
List<RoleRights> listUserRights = new ArrayList<RoleRights>();
try {
configurationFile = FileUtil.inputStreamToTempFile(permissions_for_role, "GNA_RoleRights_Configurations"+new Random().nextInt());
CSVReader reader = new CSVReader(configurationFile);
CSVFile csvFile = reader.getCsvFile();
List<String> headerKeys = csvFile.getHeaderRow().getListValues();
List<CSVRow> rows = csvFile.getValueRows();
// MAPPING OPERATION TYPE AS READ, WRITE, etc.
Map<String, OPERATION_TYPE> mapOperationTypes = new HashMap<String, RoleRights.OPERATION_TYPE>();
CSVRow operationTypeRow = rows.get(0);
List<String> rowValues = operationTypeRow.getListValues();
for (int j = 1; j < rowValues.size(); j++) {
String operationType = rowValues.get(j);
RoleRights.OPERATION_TYPE ot = RoleRights.OPERATION_TYPE.UNKNOWN;
if (operationType.equalsIgnoreCase("R")) {
ot = RoleRights.OPERATION_TYPE.READ;
} else if (operationType.equalsIgnoreCase("RW")) {
ot = RoleRights.OPERATION_TYPE.READ_WRITE;
} else if (operationType.equalsIgnoreCase("W")) {
ot = RoleRights.OPERATION_TYPE.WRITE;
}
mapOperationTypes.put(headerKeys.get(j), ot);
}
LOG.debug("Map of operation types: " + mapOperationTypes);
// Starting from index 1 (means the second row in the CSV)
for (int i = 1; i < rows.size(); i++) {
LOG.trace(i + " row");
RoleRights useRights = new RoleRights();
CSVRow row = rows.get(i);
// to map properties
rowValues = row.getListValues();
LOG.debug("rowValues: " + rowValues);
Map<String, String> mapUserRolePermissions = new HashMap<String, String>();
GcubeUserRole gCubeUserRole = toGcubeUserRole(rowValues.get(0));
if (gCubeUserRole == null) {
LOG.warn("The Role " + rowValues.get(0) + " not found into roleName of: " + GcubeUserRole.values());
continue;
}
useRights.setUserRole(gCubeUserRole);
for (int j = 1; j < rowValues.size(); j++) {
mapUserRolePermissions.put(headerKeys.get(j), rowValues.get(j));
}
LOG.debug("Role: " + useRights.getUserRole());
LOG.debug("Permissions read: " + mapUserRolePermissions);
Map<ACTION_ON_ITEM, OPERATION_TYPE> listPermessions = new HashMap<ACTION_ON_ITEM, OPERATION_TYPE>();
for (ACTION_ON_ITEM value : ACTION_ON_ITEM.values()) {
String yesno = mapUserRolePermissions.get(value.name());
if (GNAConfigsConverter.checkYesNoValue(yesno)) {
listPermessions.put(value, mapOperationTypes.get(value.name()));
}
}
useRights.setListPermessions(listPermessions);
// String writeOwn = mapUserRolePermissions.get(WRITE_OWN_CONFIG);
// if (writeOwn != null && writeOwn.equalsIgnoreCase("yes")) {
// useRights.setWriteOwn(true);
// }
//
// String writeAny = mapUserRolePermissions.get(WRITE_ANY_CONFIG);
// if (writeAny != null && writeAny.equalsIgnoreCase("yes")) {
// useRights.setWriteAny(true);
// }
listUserRights.add(useRights);
}
LOG.info("Returning user rights config: " + listUserRights);
return listUserRights;
} catch (Exception e) {
LOG.error("An error occurred on reading the GNA DataEntry config from: " + permissions_for_role, e);
throw new GNAConfigException("Error on reading the GNA DataEntry from: " + permissions_for_role);
} finally {
if (configurationFile != null) {
try {
configurationFile.delete();
} catch (Exception e) {
// silent
}
}
}
}
/**
* Gets the gcube generic query string.
*
* @param secondaryType the secondary type
* @param genericResourceName the generic resource name
* @return the gcube generic query string
*/
public static String getGcubeGenericQueryString(String secondaryType, String genericResourceName) {
return "for $profile in collection('/db/Profiles/GenericResource')//Resource "
+ "where $profile/Profile/SecondaryType/string() eq '" + secondaryType
+ "' and $profile/Profile/Name/string() " + " eq '" + genericResourceName + "'" + "return $profile";
}
/**
* Gets the secondary type.
*
* @return the secondary type
*/
public String getSecondaryType() {
return SECONDARY_TYPE;
}
/**
* Gets the scope.
*
* @return the scope
*/
public String getScope() {
return scope;
}
}

View File

@ -14,7 +14,8 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.gcube.application.geoportalcommon.shared.GeoNaDataViewerProfile;
import org.gcube.application.geoportalcommon.shared.GNADataViewerConfigProfile;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.LayerItem;
import org.gcube.application.geoportalcommon.shared.exception.ApplicationProfileNotFoundException;
import org.gcube.common.resources.gcore.utils.XPathHelper;
@ -31,22 +32,23 @@ import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* The Class GeoNaViewerProfileReader.
* The Class GNADataViewerConfigProfileReader.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 12, 2020
* Dec 21, 2021
*/
public class GeoNaDataViewerProfileReader {
public class GNADataViewerConfigProfileReader {
private static final String RESOURCE_PROFILE_BODY = "/Resource/Profile/Body";
/**
*
*/
public static final String SECONDARY_TYPE = "ApplicationProfile";
public static final String WORKSPACE_EXPLORER_APP_NAME = "GeoNa-Viewer-Profile";
public static final String GENERIC_RESOURCE_NAME = "Geoportal-DataViewer-Configs";
private static final String PATH_TO_ITEM_FIELDS_CONFIG = RESOURCE_PROFILE_BODY + "/item_fields_config";
private Logger logger = LoggerFactory.getLogger(GeoNaDataViewerProfileReader.class);
private static Logger LOG = LoggerFactory.getLogger(GNADataViewerConfigProfileReader.class);
private String secondaryType;
private String scope;
private String appID;
@ -56,7 +58,7 @@ public class GeoNaDataViewerProfileReader {
*
* @param appID the app id
*/
public GeoNaDataViewerProfileReader(String appID) {
public GNADataViewerConfigProfileReader(String appID) {
this.appID = appID;
this.secondaryType = SECONDARY_TYPE;
@ -67,25 +69,27 @@ public class GeoNaDataViewerProfileReader {
* Read profile from infrastrucure.
*
* @return the map
* @throws Exception the exception
*/
public GeoNaDataViewerProfile readProfileFromInfrastrucure() throws Exception {
protected GNADataViewerConfigProfile readProfileFromInfrastructure() throws Exception {
String queryString = getGcubeGenericQueryString(secondaryType, appID);
logger.info("Scope " + scope + ", trying to perform query: " + queryString);
LOG.info("Scope " + scope + ", trying to perform query: " + queryString);
try {
if (scope == null)
throw new Exception("Scope is null, set scope into ScopeProvider");
GeoNaDataViewerProfile profile = new GeoNaDataViewerProfile();
GNADataViewerConfigProfile profile = new GNADataViewerConfigProfile();
logger.info("Trying to fetch ApplicationProfile in the scope: " + scope + ", SecondaryType: "
LOG.info("Trying to fetch ApplicationProfile in the scope: " + scope + ", SecondaryType: "
+ secondaryType + ", AppId: " + appID);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
String item_fields = "";
if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("ApplicationProfile with SecondaryType: " + secondaryType
+ ", AppId: " + appID + " is not registered in the scope: " + scope);
@ -131,13 +135,31 @@ public class GeoNaDataViewerProfileReader {
}
profile.setMapLayers(mapLayers);
logger.info("returning: " + profile);
xPathExp = PATH_TO_ITEM_FIELDS_CONFIG + "/text()";
currValue = helper.evaluate(xPathExp);
if (currValue != null && currValue.size() > 0) {
item_fields = currValue.get(0);
} else
throw new Exception("I'm not able to read the path: " + xPathExp);
// replacing \n with new_line string
LOG.debug("read " + PATH_TO_ITEM_FIELDS_CONFIG + ": " + item_fields);
String value_with_new_lines = item_fields.replaceAll("\\\\n", System.lineSeparator());
LOG.debug(PATH_TO_ITEM_FIELDS_CONFIG + " with new lines: " + value_with_new_lines);
GNAConfigsConverter gnc = new GNAConfigsConverter();
List<ItemField> listItemFieldsConfig = gnc.readListItemsConfig(value_with_new_lines);
profile.setListItemFields(listItemFieldsConfig);
LOG.info("returning: " + profile);
return profile;
}
} catch (Exception e) {
logger.error("Error while trying to read the " + SECONDARY_TYPE + " with SecondaryType "
+ WORKSPACE_EXPLORER_APP_NAME + " from scope " + scope, e);
LOG.error("Error while trying to read the " + SECONDARY_TYPE + " with SecondaryType "
+ GENERIC_RESOURCE_NAME + " from scope " + scope, e);
return null;
} finally {
@ -179,22 +201,17 @@ public class GeoNaDataViewerProfileReader {
@Override
public String toString() {
return "GeoNaViewerProfileReader [secondaryType=" + secondaryType + ", scope=" + scope + ", appID=" + appID
+ "]";
StringBuilder builder = new StringBuilder();
builder.append("GNADataViewerConfigProfileReader [LOG=");
builder.append(LOG);
builder.append(", secondaryType=");
builder.append(secondaryType);
builder.append(", scope=");
builder.append(scope);
builder.append(", appID=");
builder.append(appID);
builder.append("]");
return builder.toString();
}
/*
* public static void main(String[] args) throws Exception {
* ScopeProvider.instance.set("/gcube/devNext/NextNext");
* GeoNaDataViewerProfileReader gdvp = new
* GeoNaDataViewerProfileReader("geoportal-data-viewer-app");
* GeoNaDataViewerProfile profile = gdvp.readProfileFromInfrastrucure();
* System.out.println(profile.getRestrictedPortletURL());
* System.out.println(profile.getOpenPortletURL());
*
* if(profile.getMapLayers()!=null) { for (String type :
* profile.getMapLayers().keySet()) {
* System.out.println("key: "+type+", value: "+profile.getMapLayers().get(type))
* ; } } }
*/
}

View File

@ -4,27 +4,27 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import org.gcube.application.geoportalcommon.shared.GeoNaDataViewerProfile;
import org.gcube.application.geoportalcommon.shared.GNADataEntryConfigProfile;
import org.gcube.application.geoportalcommon.shared.GNADataViewerConfigProfile;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.application.geoportalcommon.shared.PublicLink;
import org.gcube.portlets.user.urlshortener.UrlShortener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class GeoportalCommon.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Aug 5, 2021
* Aug 5, 2021
*/
public class GeoportalCommon {
/** The Constant LOG. */
private static final Logger LOG = LoggerFactory.getLogger(GeoportalCommon.class);
private GeoNaDataViewerProfile geonaDataProfile;
private GNADataViewerConfigProfile geonaDataProfile;
/**
* Instantiates a new geoportal common.
@ -37,14 +37,14 @@ public class GeoportalCommon {
*
* @param geonaDataProfile the geona data profile
*/
public GeoportalCommon(GeoNaDataViewerProfile geonaDataProfile) {
public GeoportalCommon(GNADataViewerConfigProfile geonaDataProfile) {
this.geonaDataProfile = geonaDataProfile;
}
/**
* Gets the public links for.
*
* @param item the item
* @param item the item
* @param createShortURL creates and returns the short URL also.
* @return the public links for
* @throws Exception the exception
@ -63,8 +63,8 @@ public class GeoportalCommon {
if (item.getItemType() == null)
throw new Exception("Bad request, the item type is null");
if(this.geonaDataProfile==null)
this.geonaDataProfile = getGeoNaDataViewProfile(GeoportalCommonConstants.GEOPORTAL_DATA_VIEWER_APP);
if (this.geonaDataProfile == null)
this.geonaDataProfile = readGNADataViewerConfig(GeoportalCommonConstants.GEOPORTAL_DATA_VIEWER_APP);
// Restricted Link
String link = String.format("%s?%s=%s&%s=%s", geonaDataProfile.getRestrictedPortletURL(),
@ -73,7 +73,7 @@ public class GeoportalCommon {
String shortUrl = link;
try {
if(createShortURL)
if (createShortURL)
shortUrl = getShortUrl(link);
} catch (Exception e) {
LOG.warn("Error on shortening the URL: ", e);
@ -103,27 +103,6 @@ public class GeoportalCommon {
}
}
/**
* Gets the GeoNaData Viewer Profile.
*
* @param appID if null or empty uses the default appID that is
* {@link GeoportalCommonConstants#GEOPORTAL_DATA_VIEWER_APP}
* @return the GeoNaData Viewer Profile
* @throws Exception the exception
*/
public GeoNaDataViewerProfile getGeoNaDataViewProfile(String appID) throws Exception {
LOG.info("getGeoNaDataViewProfile called for: " + appID);
if (appID == null || appID.isEmpty())
appID = GeoportalCommonConstants.GEOPORTAL_DATA_VIEWER_APP;
LOG.info("using AppId: " + appID);
GeoNaDataViewerProfileReader gdvp = new GeoNaDataViewerProfileReader(appID);
GeoNaDataViewerProfile profile = gdvp.readProfileFromInfrastrucure();
LOG.info("Returning profile: " + profile);
return profile;
}
/**
* Gets the short url.
*
@ -173,8 +152,44 @@ public class GeoportalCommon {
*
* @return the geona data profile
*/
public GeoNaDataViewerProfile getGeonaDataProfile() {
public GNADataViewerConfigProfile getGeonaDataProfile() {
return geonaDataProfile;
}
/**
* Read GNA data viewer config.
*
* @param appID the app ID. If null uses the default
* {@link GeoportalCommonConstants#GEOPORTAL_DATA_VIEWER_APP}
* @return the GNA data viewer config profile
* @throws Exception the exception
*/
public GNADataViewerConfigProfile readGNADataViewerConfig(String appID) throws Exception {
LOG.info("getGeoNaDataViewProfile called for AppID: " + appID);
if (appID == null || appID.isEmpty()) {
appID = GeoportalCommonConstants.GEOPORTAL_DATA_VIEWER_APP;
LOG.info("AppID is null, so using DEFAULT: " + appID);
}
GNADataViewerConfigProfileReader gdvp = new GNADataViewerConfigProfileReader(appID);
GNADataViewerConfigProfile profile = gdvp.readProfileFromInfrastructure();
LOG.info("Returning profile: " + profile);
return profile;
}
/**
* Gets the GNA data config read from ApplicationProfile stored into IS.
*
* @return the GNA data config
* @throws Exception the exception
*/
public GNADataEntryConfigProfile readGNADataEntryConfig() throws Exception {
LOG.info("readGNADataEntryConfig called");
GNADataEntryConfigProfileReader gnaConfigReader = new GNADataEntryConfigProfileReader();
GNADataEntryConfigProfile config = gnaConfigReader.readProfileFromInfrastrucure();
return config;
}
}

View File

@ -0,0 +1,266 @@
package org.gcube.application.geoportalcommon;
import static org.gcube.application.geoportal.client.GeoportalAbstractPlugin.mongoConcessioni;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.gcube.application.geoportal.common.model.legacy.Concessione;
import org.gcube.application.geoportal.common.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.OrderedRequest;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.OrderedRequest.Direction;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.PagedRequest;
import org.gcube.application.geoportal.common.rest.MongoConcessioni;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.ResultSetPaginatedData;
import org.gcube.application.geoportalcommon.shared.SearchingFilter;
import org.gcube.application.geoportalcommon.shared.SearchingFilter.LOGICAL_OP;
import org.gcube.application.geoportalcommon.shared.SearchingFilter.ORDER;
import org.gcube.application.geoportalcommon.shared.WhereClause;
import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
/**
* The Class MongoServiceCommon.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 3, 2021
*/
public class MongoServiceCommon {
private static Logger LOG = LoggerFactory.getLogger(MongoServiceCommon.class);
/**
* Gets the instance mongo concessioni.
*
* @return the instance mongo concessioni
*/
public MongoConcessioni getInstanceMongoConcessioni() {
return mongoConcessioni().build();
}
/**
* Gets the list of concessioni.
*
* @param reloadFromService the reload from service
* @return the list of concessioni
* @throws Exception the exception
*/
public List<Concessione> getListOfConcessioni() throws Exception {
LOG.info("called getListOfConcessioni");
List<Concessione> listOfConcessioni = new ArrayList<Concessione>();
LOG.info("Loading list of concessioni from client mongo");
MongoConcessioni clientMongo = getInstanceMongoConcessioni();
Iterator<Concessione> concessioni = clientMongo.getList();
if (concessioni != null) {
while (concessioni.hasNext()) {
Concessione concessione = (Concessione) concessioni.next();
listOfConcessioni.add(concessione);
}
}
LOG.info("read list of concessioni with size: " + listOfConcessioni.size());
return listOfConcessioni;
}
/**
* Query on mongo.
*
* @param offset the offset
* @param limit the limit
* @param filter the filter
* @param recordType the record type
* @return the result set paginated data
* @throws Exception the exception
*/
public ResultSetPaginatedData queryOnMongo(Integer totalItems, Integer offset, Integer limit, SearchingFilter filter, String recordType) throws Exception {
try {
if (recordType.equalsIgnoreCase("concessione")) {
MongoConcessioni clientMongo = getInstanceMongoConcessioni();
if(totalItems==null || totalItems < 0) {
// TODO MUST BE REPLACED BY COUNT
List<Concessione> listOfConcessioni = getListOfConcessioni();
int listConcessioniSize = listOfConcessioni.size();
totalItems = listConcessioniSize;
}
Integer offsetIndex = offset;
Integer limitIndex = limit;
if (offset == null || offset<0) {
offsetIndex = 0;
}
if (limit == null || limit<0) {
limitIndex = totalItems;
}
ResultSetPaginatedData searchedData = new ResultSetPaginatedData(offsetIndex, limitIndex, false);
searchedData.setTotalItems(totalItems);
List<ConcessioneDV> toReturnList = new ArrayList<ConcessioneDV>();
Direction sDirection = null;
List<String> orderingFields = new ArrayList<String>();
if (filter == null) {
LOG.info("No filter found, creating empty filter");
filter = new SearchingFilter();
}
ORDER order = filter.getOrder();
if (order == null) {
order = ORDER.ASC;
LOG.info("No direction/order found, using default: " + order);
}
switch (order) {
case ASC:
sDirection = Direction.ASCENDING;
break;
case DESC:
sDirection = Direction.DESCENDING;
break;
}
List<ItemField> orderByFields = filter.getOrderByFields();
if(orderByFields==null) {
orderByFields = new ArrayList<ItemField>();
}
if(orderByFields.isEmpty()) {
ItemField orderD = new ItemField("", Arrays.asList("name"), false, false, false);
LOG.info("Order by is null, adding default: " + orderD);
orderByFields.add(orderD);
}
for (ItemField itemField : orderByFields) {
if (itemField.getJsonFields() != null) {
for (String field : itemField.getJsonFields()) {
orderingFields.add(field);
}
}
}
QueryRequest request = new QueryRequest();
PagedRequest paging = new PagedRequest();
paging.setOffset(offsetIndex);
paging.setLimit(limitIndex);
request.setPaging(paging);
OrderedRequest ordering = new OrderedRequest();
ordering.setDirection(sDirection);
ordering.setFields(orderingFields);
request.setOrdering(ordering);
Document query = new Document();
if(filter.getConditions()!=null) {
for (WhereClause whereClause : filter.getConditions()) {
LOGICAL_OP searchWithOperator = whereClause.getOperator();
if(searchWithOperator==null) {
searchWithOperator = LOGICAL_OP.OR;
}
if (whereClause.getSearchInto() != null) {
Map<String, Object> searchFields = whereClause.getSearchInto();
BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
for (String key : searchFields.keySet()) {
// using regex and case-insensitive
BasicDBObject bs = new BasicDBObject();
bs.append("$regex", searchFields.get(key));
bs.append("$options", "i");
builder.append(key, bs);
}
//Building list of Document in OR clause
BasicDBList list = new BasicDBList();
Map map = builder.get().toMap();
for (Object key : map.keySet()) {
BasicDBObject value = (BasicDBObject) map.get(key);
Document doc = new Document((String) key, value);
list.add(doc);
}
//query = new Document();
query.put(searchWithOperator.getOperator(), list);
// BasicDBObject bs = new BasicDBObject();
// bs.append("$eq", "PASSED");
// query.put("report.status", bs);
}
}
}
request.setFilter(query);
LOG.info("Paging offset: " + offsetIndex + ", limit: " + limitIndex);
LOG.info("Direction: " + sDirection);
LOG.info("Order by Fields: " + orderingFields);
LOG.info("Search for conditions: " + filter.getConditions());
if (query != null) {
LOG.info("Search query to JSON: " + query.toJson());
}
Iterator<Concessione> concessioni = clientMongo.query(request);
int i = 0;
while (concessioni.hasNext()) {
Concessione concessione = concessioni.next();
ConcessioneDV concessioneDV = ConvertToDataViewModel.toMetadataConcessione(concessione, true);
toReturnList.add(concessioneDV);
i++;
LOG.trace(i+") converted: " + concessioneDV);
}
LOG.debug("read " + toReturnList + " project/s");
searchedData.setData(toReturnList);
// TODO WORKAROUND MUST BE REMOVE AFTER THE QUERY COUNT
// AND LIST.SIZE WILL BE AVAILABLE IN THE SERVICE
if (filter.getConditions() != null) {
searchedData.setTotalItems(toReturnList.size());
totalItems = toReturnList.size();
}
if (totalItems == limit || totalItems == 0) {
LOG.debug("Page completed returning " + totalItems + " items");
int newOffset = offsetIndex + limitIndex;
searchedData.setServerSearchFinished(newOffset > totalItems || totalItems == 0);
LOG.debug("is Search finished: " + searchedData.isServerSearchFinished());
}
return searchedData;
}
} catch (Exception e) {
LOG.error("Error on loading paginated and filtered list of concessioni: ", e);
throw new Exception("Error occurred on loading list of Concessioni. Error: " + e.getMessage());
}
return null;
}
}

View File

@ -0,0 +1,152 @@
/**
*
*/
package org.gcube.application.geoportalcommon.config;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* The Class CSVFile.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 29, 2019
*/
public class CSVFile implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6408321963787244600L;
private CSVRow headerRow;
private List<CSVRow> valueRows;
private String fileName;
/**
* Instantiates a new CSV file.
*/
public CSVFile(){
}
/**
* Instantiates a new csv file.
*
* @param fileName the file name
* @param headerRow the header row
* @param valueRows the value rows
*/
public CSVFile(String fileName, CSVRow headerRow, List<CSVRow> valueRows) {
this.fileName = fileName;
this.headerRow = headerRow;
this.valueRows = valueRows;
}
/**
* Gets the header row.
*
* @return the headerRow
*/
public CSVRow getHeaderRow() {
return headerRow;
}
/**
* Adds the value row.
*
* @param row the row
*/
public void addValueRow(CSVRow row) {
if(valueRows==null)
valueRows = new ArrayList<CSVRow>();
valueRows.add(row);
}
/**
* Sets the value rows.
*
* @param valueRows the new value rows
*/
public void setValueRows(List<CSVRow> valueRows) {
this.valueRows = valueRows;
}
/**
* Gets the value rows.
*
* @return the valueRows
*/
public List<CSVRow> getValueRows() {
return valueRows;
}
/**
* Sets the header row.
*
* @param headerRow the headerRow to set
*/
public void setHeaderRow(CSVRow headerRow) {
this.headerRow = headerRow;
}
/**
* Gets the file name.
*
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* Sets the file name.
*
* @param fileName the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* To string.
*
* @return the string
*/
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CSVFile [headerRow=");
builder.append(headerRow);
builder.append(", valueRows=");
builder.append(valueRows);
builder.append(", fileName=");
builder.append(fileName);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,192 @@
/**
*
*/
package org.gcube.application.geoportalcommon.config;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* The Class CSVReader.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 29, 2019
*/
public class CSVReader {
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE = '"';
private File file;
private CSVFile csvFile;
/**
* Instantiates a new CSV reader.
*
* @param file the file
* @throws FileNotFoundException the file not found exception
*/
public CSVReader(File file) throws FileNotFoundException {
this.file = file;
this.csvFile = new CSVFile();
readCSV(file);
}
/**
* Read csv.
*
* @param file the file
* @throws FileNotFoundException the file not found exception
*/
private void readCSV(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(file);
csvFile.setFileName(file.getName());
int i = 0;
while (scanner.hasNext()) {
CSVRow csvRow = new CSVRow();
List<String> line = parseLine(scanner.nextLine());
csvRow.setListValues(line);
if(i==0){
csvFile.setHeaderRow(csvRow);
}else{
csvFile.addValueRow(csvRow);
}
i++;
}
scanner.close();
}
/**
* Parses the line.
*
* @param cvsLine the cvs line
* @return the list
*/
public static List<String> parseLine(String cvsLine) {
return parseLine(cvsLine, DEFAULT_SEPARATOR, DEFAULT_QUOTE);
}
/**
* Parses the line.
*
* @param cvsLine the cvs line
* @param separators the separators
* @return the list
*/
public static List<String> parseLine(String cvsLine, char separators) {
return parseLine(cvsLine, separators, DEFAULT_QUOTE);
}
/**
* Parses the line.
*
* @param cvsLine the cvs line
* @param separators the separators
* @param customQuote the custom quote
* @return the list
*/
private static List<String> parseLine(String cvsLine, char separators, char customQuote) {
List<String> result = new ArrayList<>();
// if empty, return!
if (cvsLine == null || cvsLine.isEmpty()) {
return result;
}
if (customQuote == ' ') {
customQuote = DEFAULT_QUOTE;
}
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuffer curVal = new StringBuffer();
boolean inQuotes = false;
boolean startCollectChar = false;
boolean doubleQuotesInColumn = false;
char[] chars = cvsLine.toCharArray();
for (char ch : chars) {
if (inQuotes) {
startCollectChar = true;
if (ch == customQuote) {
inQuotes = false;
doubleQuotesInColumn = false;
}
else {
// Fixed : allow "" in custom quote enclosed
if (ch == '\"') {
if (!doubleQuotesInColumn) {
curVal.append(ch);
doubleQuotesInColumn = true;
}
}
else {
curVal.append(ch);
}
}
}
else {
if (ch == customQuote) {
inQuotes = true;
// Fixed : allow "" in empty quote enclosed
if (chars[0] != '"' && customQuote == '\"') {
curVal.append('"');
}
// double quotes in column will hit this!
if (startCollectChar) {
curVal.append('"');
}
}
else if (ch == separators) {
result.add(curVal.toString());
curVal = new StringBuffer();
startCollectChar = false;
}
else if (ch == '\r') {
// ignore LF characters
continue;
}
else if (ch == '\n') {
// the end, break!
break;
}
else {
curVal.append(ch);
}
}
}
result.add(curVal.toString());
return result;
}
/**
* Gets the csv file.
*
* @return the csvFile
*/
public CSVFile getCsvFile() {
return csvFile;
}
/**
* Gets the file.
*
* @return the file
*/
public File getFile() {
return file;
}
}

View File

@ -0,0 +1,81 @@
/**
*
*/
package org.gcube.application.geoportalcommon.config;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* The Class CSVRow.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* Jan 29, 2019
*/
public class CSVRow implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6254861811998867626L;
private List<String> listValues;
/**
* Instantiates a new CSV row.
*/
public CSVRow(){
}
/**
* Gets the list values.
*
* @return the listValues
*/
public List<String> getListValues() {
return listValues;
}
/**
* @param listValues the listValues to set
*/
public void setListValues(List<String> listValues) {
this.listValues = listValues;
}
/**
* Adds the value.
*
* @param value the value
*/
public void addValue(String value) {
if(listValues==null)
listValues = new ArrayList<String>();
listValues.add(value);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CSVRow [listValues=");
builder.append(listValues);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,100 @@
package org.gcube.application.geoportalcommon.config;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* The Class FileUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 2, 2021
*/
public class FileUtil {
/**
* Input stream to temp file.
*
* @param inputStream the input stream
* @param fileName the file name
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
// InputStream -> Temp File
public static File inputStreamToTempFile(InputStream inputStream, String fileName) throws IOException {
File tempFile = File.createTempFile(fileName, ".tmp");
// File tempFile = File.createTempFile("MyAppName-", ".tmp");
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
return tempFile;
} finally {
tempFile.deleteOnExit();
}
}
/**
* Input stream to temp file.
*
* @param copyString the copy string
* @return
* @throws IOException Signals that an I/O exception has occurred.
*/
public static File inputStreamToTempFile(String copyString, String prefixFile) throws IOException {
File targetFile = null;
try {
InputStream initialStream = new ByteArrayInputStream(copyString.getBytes());
targetFile = File.createTempFile(prefixFile, ".tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
try {
if (initialStream != null) {
initialStream.close();
}
} catch (IOException ioe) {
// ignore
}
return targetFile;
} finally {
try {
if (targetFile != null)
targetFile.deleteOnExit();
} catch (Exception e) {
}
}
}
/**
* Copy input stream to file.
*
* @param is the is
* @param to the to
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
public static File copyInputStreamToFile(InputStream is, String to) throws IOException {
Path dest = Paths.get(to);
Files.copy(is, dest);
return new File(to);
}
}

View File

@ -0,0 +1,93 @@
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.List;
import org.gcube.application.geoportalcommon.shared.config.RoleRights;
/**
* The Class GNADataEntryConfigProfile.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 21, 2021
*/
public class GNADataEntryConfigProfile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5152380669677928785L;
private List<ItemField> listItemFields;
private List<RoleRights> permissionsForRole;
/**
* Instantiates a new GNA data entry config profile.
*/
public GNADataEntryConfigProfile() {
}
/**
* Instantiates a new GNA data entry config profile.
*
* @param listItemFields the list item fields
* @param permissionsForRole the permissions for role
*/
public GNADataEntryConfigProfile(List<ItemField> listItemFields, List<RoleRights> permissionsForRole) {
super();
this.listItemFields = listItemFields;
this.permissionsForRole = permissionsForRole;
}
/**
* Gets the list item fields.
*
* @return the list item fields
*/
public List<ItemField> getListItemFields() {
return listItemFields;
}
/**
* Sets the list item fields.
*
* @param listItemFields the new list item fields
*/
public void setListItemFields(List<ItemField> listItemFields) {
this.listItemFields = listItemFields;
}
/**
* Gets the permissions for role.
*
* @return the permissions for role
*/
public List<RoleRights> getPermissionsForRole() {
return permissionsForRole;
}
/**
* Sets the permissions for role.
*
* @param permissionsForRole the new permissions for role
*/
public void setPermissionsForRole(List<RoleRights> permissionsForRole) {
this.permissionsForRole = permissionsForRole;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GNADataEntryConfigProfile [listItemFields=");
builder.append(listItemFields);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,17 +1,17 @@
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* The Class GeoNaDataViewerProfile.
* The Class GNADataViewerConfigProfile.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 13, 2020
* Dec 21, 2021
*/
public class GeoNaDataViewerProfile implements Serializable{
public class GNADataViewerConfigProfile implements Serializable {
/**
*
@ -19,13 +19,14 @@ public class GeoNaDataViewerProfile implements Serializable{
private static final long serialVersionUID = 2968334957258327191L;
private String restrictedPortletURL;
private String openPortletURL;
//the key is the layer type
// the key is the layer type
private Map<String, LayerItem> mapLayers;
private List<ItemField> listItemFields;
/**
* Instantiates a new geo na data viewer profile.
*/
public GeoNaDataViewerProfile() {
public GNADataViewerConfigProfile() {
}
@ -84,22 +85,36 @@ public class GeoNaDataViewerProfile implements Serializable{
}
/**
* To string.
* Gets the list item fields.
*
* @return the string
* @return the list item fields
*/
public List<ItemField> getListItemFields() {
return listItemFields;
}
/**
* Sets the list item fields.
*
* @param listItemFields the new list item fields
*/
public void setListItemFields(List<ItemField> listItemFields) {
this.listItemFields = listItemFields;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("GeoNaDataViewerProfile [restrictedPortletURL=");
builder.append("GNADataViewerConfigProfile [restrictedPortletURL=");
builder.append(restrictedPortletURL);
builder.append(", openPortletURL=");
builder.append(openPortletURL);
builder.append(", mapLayers=");
builder.append(mapLayers);
builder.append(", listItemFields=");
builder.append(listItemFields);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,164 @@
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.List;
/**
* The Class ItemField.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 21, 2021
*/
public class ItemField implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1856714668390438433L;
private String displayName;
private List<String> jsonFields;
private boolean sortable;
private boolean searchable;
private boolean displayAsResult;
/**
* Instantiates a new item field.
*/
public ItemField() {
}
/**
* Instantiates a new item field.
*
* @param displayName the display name
* @param jsonFields the json fields
* @param displayAsResult the display as result
* @param sortable the sortable
* @param searchable the searchable
*/
public ItemField(String displayName, List<String> jsonFields, boolean displayAsResult, boolean sortable,
boolean searchable) {
super();
this.displayName = displayName;
this.jsonFields = jsonFields;
this.displayAsResult = displayAsResult;
this.sortable = sortable;
this.searchable = searchable;
}
/**
* Gets the display name.
*
* @return the display name
*/
public String getDisplayName() {
return displayName;
}
/**
* Gets the json fields.
*
* @return the json fields
*/
public List<String> getJsonFields() {
return jsonFields;
}
/**
* Sets the display name.
*
* @param displayName the new display name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* Sets the json fields.
*
* @param jsonFields the new json fields
*/
public void setJsonFields(List<String> jsonFields) {
this.jsonFields = jsonFields;
}
/**
* Checks if is sortable.
*
* @return true, if is sortable
*/
public boolean isSortable() {
return sortable;
}
/**
* Sets the sortable.
*
* @param sortable the new sortable
*/
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
/**
* Checks if is searchable.
*
* @return true, if is searchable
*/
public boolean isSearchable() {
return searchable;
}
/**
* Sets the searchable.
*
* @param searchable the new searchable
*/
public void setSearchable(boolean searchable) {
this.searchable = searchable;
}
/**
* Checks if is display as result.
*
* @return true, if is display as result
*/
public boolean isDisplayAsResult() {
return displayAsResult;
}
/**
* Sets the display as result.
*
* @param displayAsResult the new display as result
*/
public void setDisplayAsResult(boolean displayAsResult) {
this.displayAsResult = displayAsResult;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ItemField [displayName=");
builder.append(displayName);
builder.append(", jsonFields=");
builder.append(jsonFields);
builder.append(", sortable=");
builder.append(sortable);
builder.append(", searchable=");
builder.append(searchable);
builder.append(", displayAsResult=");
builder.append(displayAsResult);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,184 @@
/**
*
*/
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.List;
import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV;
/**
* The Class ResultSetPaginatedData.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Aug 6, 2021
*/
public class ResultSetPaginatedData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6800997954077785719L;
private List<ConcessioneDV> data;
private int offset = 0;
private int limit;
private boolean isServerSearchFinished = false;
private long totalItems;
/**
* Instantiates a new searched folder.
*/
public ResultSetPaginatedData() {
}
/**
* Instantiates a new result set paginated data.
*
* @param offset the offset
* @param limit the limit
* @param isServerSearchFinished the is server search finished
*/
public ResultSetPaginatedData(int offset, int limit, boolean isServerSearchFinished) {
this.offset = offset;
this.limit = limit;
this.isServerSearchFinished = isServerSearchFinished;
}
/**
* Gets the data.
*
* @return the data
*/
public List<ConcessioneDV> getData() {
return data;
}
/**
* Gets the client start index.
*
* @return the client start index
*/
public int getClientStartIndex() {
return offset;
}
/**
* Gets the limit.
*
* @return the limit
*/
public int getLimit() {
return limit;
}
/**
* Checks if is server search finished.
*
* @return true, if is server search finished
*/
public boolean isServerSearchFinished() {
return isServerSearchFinished;
}
/**
* Sets the data.
*
* @param data the new data
*/
public void setData(List<ConcessioneDV> data) {
this.data = data;
}
/**
* Sets the client start index.
*
* @param clientStartIndex the new client start index
*/
public void setClientStartIndex(int clientStartIndex) {
this.offset = clientStartIndex;
}
/**
* Sets the limit.
*
* @param limit the new limit
*/
public void setLimit(int limit) {
this.limit = limit;
}
/**
* Sets the server search finished.
*
* @param isServerSearchFinished the new server search finished
*/
public void setServerSearchFinished(boolean isServerSearchFinished) {
this.isServerSearchFinished = isServerSearchFinished;
}
/**
* Gets the total items.
*
* @return the total items
*/
public long getTotalItems() {
return totalItems;
}
/**
* Sets the total items.
*
* @param totalItems the new total items
*/
public void setTotalItems(long totalItems) {
this.totalItems = totalItems;
}
/**
* Gets the serialversionuid.
*
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
/**
* Gets the offset.
*
* @return the offset
*/
public int getOffset() {
return offset;
}
/**
* Sets the offset.
*
* @param offset the new offset
*/
public void setOffset(int offset) {
this.offset = offset;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ResultSetPaginatedData [data=");
builder.append(data);
builder.append(", offset=");
builder.append(offset);
builder.append(", limit=");
builder.append(limit);
builder.append(", isServerSearchFinished=");
builder.append(isServerSearchFinished);
builder.append(", totalItems=");
builder.append(totalItems);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,176 @@
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.List;
/**
* The Class SearchingFilter.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 30, 2021
*/
public class SearchingFilter implements Serializable {
/**
* The Enum ORDER.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 30, 2021
*/
public static enum ORDER {
ASC("ASCENDING"), DESC("DESCENDING");
String label;
/**
* Instantiates a new order.
*
* @param label the label
*/
ORDER(String label) {
this.label = label;
}
/**
* Gets the label.
*
* @return the label
*/
public String getLabel() {
return label;
}
}
/**
* The Enum LOGICAL_OP.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 15, 2021
*/
public static enum LOGICAL_OP {
AND("$and"), OR("$or");
String operator;
/**
* Instantiates a new order.
*
* @param operator the operator
*/
LOGICAL_OP(String operator) {
this.operator = operator;
}
/**
* Gets the operator.
*
* @return the operator
*/
public String getOperator() {
return operator;
}
}
/**
*
*/
private static final long serialVersionUID = -4004094263090373626L;
private List<ItemField> orderByFields;
private ORDER order = ORDER.ASC;
private List<WhereClause> conditions;
/**
* Instantiates a new sort filter.
*/
public SearchingFilter() {
}
/**
* Instantiates a new sort filter.
*
* @param orderByFields the order by fields
* @param order the order
*/
public SearchingFilter(List<ItemField> orderByFields, ORDER order) {
this.orderByFields = orderByFields;
this.order = order;
}
/**
* Instantiates a new sort filter.
*
* @param orderByFields the order by fields
* @param order the order
* @param searchInto the search into
*/
public SearchingFilter(List<ItemField> orderByFields, ORDER order, List<WhereClause> conditions) {
this.orderByFields = orderByFields;
this.order = order;
this.conditions = conditions;
}
public List<WhereClause> getConditions() {
return conditions;
}
public void setConditions(List<WhereClause> conditions) {
this.conditions = conditions;
}
/**
* Gets the order by fields.
*
* @return the order by fields
*/
public List<ItemField> getOrderByFields() {
return orderByFields;
}
/**
* Gets the order.
*
* @return the order
*/
public ORDER getOrder() {
return order;
}
/**
* Sets the order by fields.
*
* @param orderByFields the new order by fields
*/
public void setOrderByFields(List<ItemField> orderByFields) {
this.orderByFields = orderByFields;
}
/**
* Sets the order.
*
* @param order the new order
*/
public void setOrder(ORDER order) {
this.order = order;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("SearchingFilter [orderByFields=");
builder.append(orderByFields);
builder.append(", order=");
builder.append(order);
builder.append(", conditions=");
builder.append(conditions);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,97 @@
package org.gcube.application.geoportalcommon.shared;
import java.io.Serializable;
import java.util.Map;
import org.gcube.application.geoportalcommon.shared.SearchingFilter.LOGICAL_OP;
/**
* The Class WhereClause.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 15, 2021
*/
public class WhereClause implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8577885822669878296L;
private LOGICAL_OP operator = LOGICAL_OP.OR;
private Map<String, Object> searchInto;
/**
* Instantiates a new where clause.
*/
public WhereClause() {
}
/**
* Instantiates a new where clause.
*
* @param operator the operator
* @param searchInto the search into
*/
public WhereClause(LOGICAL_OP operator, Map<String, Object> searchInto) {
super();
this.operator = operator;
this.searchInto = searchInto;
}
/**
* Gets the operator.
*
* @return the operator
*/
public LOGICAL_OP getOperator() {
return operator;
}
/**
* Gets the search into.
*
* @return the search into
*/
public Map<String, Object> getSearchInto() {
return searchInto;
}
/**
* Sets the operator.
*
* @param operator the new operator
*/
public void setOperator(LOGICAL_OP operator) {
this.operator = operator;
}
/**
* Sets the search into.
*
* @param searchInto the search into
*/
public void setSearchInto(Map<String, Object> searchInto) {
this.searchInto = searchInto;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("WhereClause [operator=");
builder.append(operator);
builder.append(", searchInto=");
builder.append(searchInto);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,29 @@
package org.gcube.application.geoportalcommon.shared.config;
/**
* The Class ACTION_ON_ITEM.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 24, 2021
*/
public enum ACTION_ON_ITEM {
CREATE_NEW_PROJECT("Create New Project"),
VIEW_ON_MAP("View on Map"),
SHOW_METADATA("Show Metadata"),
VIEW_REPORT("View the Report"),
EDIT_PROJECT("Edit the Project"),
DELETE_PROJECT("Delete the Project");
String label;
ACTION_ON_ITEM(String label){
this.label = label;
}
public String getLabel() {
return label;
}
}

View File

@ -0,0 +1,55 @@
package org.gcube.application.geoportalcommon.shared.config;
/**
* The Enum GcubeUserRole.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 25, 2021
*/
public enum GcubeUserRole {
DATA_MEMBER("Data-Member", false, false),
DATA_EDITOR("Data-Editor", true, false),
DATA_MANAGER("Data-Manager", true, true);
private String name;
private boolean writeOwn;
private boolean writeAny;
/**
* Instantiates a new gcube user role.
*
* @param name the name
*/
private GcubeUserRole(String name, boolean writeOwn, boolean writeAny) {
this.name = name;
this.writeOwn = writeOwn;
this.writeAny = writeAny;
}
public String getName() {
return name;
}
public boolean isWriteOwn() {
return writeOwn;
}
public boolean isWriteAny() {
return writeAny;
}
public void setName(String name) {
this.name = name;
}
public void setWriteOwn(boolean writeOwn) {
this.writeOwn = writeOwn;
}
public void setWriteAny(boolean writeAny) {
this.writeAny = writeAny;
}
}

View File

@ -0,0 +1,100 @@
package org.gcube.application.geoportalcommon.shared.config;
import java.io.Serializable;
import java.util.Map;
/**
* The Class RoleRights.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 26, 2021
*/
public class RoleRights implements Serializable {
/**
*
*/
private static final long serialVersionUID = -304157165851633221L;
/**
* The Enum OPERATION_TYPE.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 26, 2021
*/
public static enum OPERATION_TYPE {
READ, WRITE, READ_WRITE, UNKNOWN
}
private Map<ACTION_ON_ITEM, OPERATION_TYPE> listPermessions;
private GcubeUserRole userRole;
/**
* Instantiates a new user rights.
*/
public RoleRights() {
super();
}
/**
* Instantiates a new role rights.
*
* @param myUsername the my username
* @param listPermessions the list permessions
* @param userRole the user role
*/
public RoleRights(Map<ACTION_ON_ITEM, OPERATION_TYPE> listPermessions, GcubeUserRole userRole) {
this.listPermessions = listPermessions;
this.userRole = userRole;
}
/**
* Gets the list permessions.
*
* @return the list permessions
*/
public Map<ACTION_ON_ITEM, OPERATION_TYPE> getListPermessions() {
return listPermessions;
}
/**
* Gets the user role.
*
* @return the user role
*/
public GcubeUserRole getUserRole() {
return userRole;
}
/**
* Sets the list permessions.
*
* @param listPermessions the list permessions
*/
public void setListPermessions(Map<ACTION_ON_ITEM, OPERATION_TYPE> listPermessions) {
this.listPermessions = listPermessions;
}
/**
* Sets the user role.
*
* @param userRole the new user role
*/
public void setUserRole(GcubeUserRole userRole) {
this.userRole = userRole;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RoleRights [listPermessions=");
builder.append(listPermessions);
builder.append(", userRole=");
builder.append(userRole);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,8 @@
package org.gcube.application.geoportalcommon.shared.exception;
@SuppressWarnings("serial")
public class GNAConfigException extends Exception {
public GNAConfigException(String message) {
super(message);
}
}

View File

@ -0,0 +1,156 @@
package org.gcube.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.gcube.application.geoportalcommon.GeoportalCommon;
import org.gcube.application.geoportalcommon.GeoportalCommonConstants;
import org.gcube.application.geoportalcommon.MongoServiceCommon;
import org.gcube.application.geoportalcommon.shared.GNADataEntryConfigProfile;
import org.gcube.application.geoportalcommon.shared.GNADataViewerConfigProfile;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.ResultSetPaginatedData;
import org.gcube.application.geoportalcommon.shared.SearchingFilter;
import org.gcube.application.geoportalcommon.shared.SearchingFilter.LOGICAL_OP;
import org.gcube.application.geoportalcommon.shared.WhereClause;
import org.gcube.application.geoportalcommon.shared.config.RoleRights;
import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.Before;
import org.junit.Test;
public class TestGNACommon {
private static String TOKEN = "";
private static String CONTEXT = "/gcube/devsec/devVRE";
private static String USERNAME = "francesco.mangiacrapa";
//@Before
public void init() {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
}
// @Test
public GNADataViewerConfigProfile getGeoNaDataViewProfile() throws Exception {
System.out.println("getGeoNaDataViewProfile called");
ScopeProvider.instance.set(CONTEXT);
GeoportalCommon gc = new GeoportalCommon();
GNADataViewerConfigProfile profile = gc.readGNADataViewerConfig(null);
System.out.println("Returning profile: " + profile);
return profile;
}
// @Test
public GeoNaItemRef getLinks() throws Exception {
System.out.println("getGeoNaDataViewProfile called");
ScopeProvider.instance.set(CONTEXT);
GeoportalCommon gc = new GeoportalCommon();
GeoNaItemRef item = new GeoNaItemRef("", "concessione");
GeoNaItemRef links = gc.getPublicLinksFor(item, true);
return links;
}
// @Test
public void queryConcessioniTest() throws Exception {
try {
ScopeProvider.instance.set(CONTEXT);
MongoServiceCommon msc = new MongoServiceCommon();
SearchingFilter filter = new SearchingFilter();
Map<String, Object> searchInto = new HashMap<String, Object>();
searchInto.put("nome", "san");
searchInto.put("authors", "silvia");
// searchInto.put("report.status", "PASSED");
WhereClause where1 = new WhereClause(LOGICAL_OP.OR, searchInto);
Map<String, Object> searchInto2 = new HashMap<String, Object>();
searchInto2.put("report.status", "PASSED");
WhereClause where2 = new WhereClause(LOGICAL_OP.AND, searchInto2);
ArrayList<WhereClause> list = new ArrayList<WhereClause>();
list.add(where1);
// list.add(where2);
filter.setConditions(list);
ResultSetPaginatedData result = msc.queryOnMongo(30, 0, 30, filter, "concessione");
int i = 0;
for (ConcessioneDV concessione : result.getData()) {
System.out.println(++i + ") " + concessione);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void readGNDataEntryConfigsFromIS() throws Exception {
Thread thread = new Thread() {
public void run() {
geoCommon();
}
};
Thread thread2 = new Thread() {
public void run() {
geoCommon();
}
};
thread.run();
thread2.run();
}
private void geoCommon() {
GeoportalCommon r = new GeoportalCommon();
try {
ScopeProvider.instance.set(CONTEXT);
GNADataEntryConfigProfile configurations = r.readGNADataEntryConfig();
System.out.println("Permissions are:");
int i = 0;
for (RoleRights role : configurations.getPermissionsForRole()) {
System.out.println(++i + " " + role);
}
System.out.println("Item Fields are:");
i = 0;
for (ItemField item : configurations.getListItemFields()) {
System.out.println(++i + " " + item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test
public void readGNDataViewerConfigsFromIS() throws Exception {
GeoportalCommon r = new GeoportalCommon();
try {
ScopeProvider.instance.set(CONTEXT);
GNADataViewerConfigProfile configurations = r.readGNADataViewerConfig(null);
System.out.println("Map layers are:");
System.out.println(configurations.getMapLayers());
System.out.println("Item Fields are:");
int i = 0;
for (ItemField item : configurations.getListItemFields()) {
System.out.println(++i + " " + item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,43 +0,0 @@
package org.gcube.application;
import org.gcube.application.geoportalcommon.GeoportalCommon;
import org.gcube.application.geoportalcommon.shared.GeoNaDataViewerProfile;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.common.scope.api.ScopeProvider;
public class TestGeonaReader {
private static String scope ="/gcube/devsec/devVRE";
public static void main(String[] args) throws Exception {
//System.out.println(getGeoNaDataViewProfile());
System.out.println(getLinks());
}
public static GeoNaDataViewerProfile getGeoNaDataViewProfile() throws Exception{
System.out.println("getGeoNaDataViewProfile called");
ScopeProvider.instance.set(scope);
GeoportalCommon gc = new GeoportalCommon();
GeoNaDataViewerProfile profile = gc.getGeoNaDataViewProfile(null);
System.out.println("Returning profile: "+profile);
return profile;
}
public static GeoNaItemRef getLinks() throws Exception{
System.out.println("getGeoNaDataViewProfile called");
ScopeProvider.instance.set(scope);
GeoportalCommon gc = new GeoportalCommon();
GeoNaItemRef item = new GeoNaItemRef("", "concessione");
GeoNaItemRef links = gc.getPublicLinksFor(item,true);
return links;
}
}