geoportal-data-viewer-app/src/main/java/org/gcube/portlets/user/geoportaldataviewer/server/GeoportalDataViewerServiceI...

1630 lines
58 KiB
Java

package org.gcube.portlets.user.geoportaldataviewer.server;
import static org.gcube.application.geoportal.client.plugins.GeoportalAbstractPlugin.projects;
import static org.gcube.application.geoportal.client.plugins.GeoportalAbstractPlugin.useCaseDescriptors;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.bson.Document;
import org.gcube.application.geoportal.common.model.configuration.Configuration;
import org.gcube.application.geoportal.common.model.configuration.Index;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.identification.IdentificationReference;
import org.gcube.application.geoportal.common.model.document.relationships.Relationship;
import org.gcube.application.geoportal.common.model.document.relationships.RelationshipNavigationObject;
import org.gcube.application.geoportal.common.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.rest.Projects;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.GeoportalCommon;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
import org.gcube.application.geoportalcommon.geoportal.ProjectsCaller;
import org.gcube.application.geoportalcommon.geoportal.UseCaseDescriptorCaller;
import org.gcube.application.geoportalcommon.geoportal.access.GeportalCheckAccessPolicy;
import org.gcube.application.geoportalcommon.geoportal.access.GeportalCheckAccessPolicy.ACCESS_POLICY;
import org.gcube.application.geoportalcommon.shared.GNADataViewerConfigProfile;
import org.gcube.application.geoportalcommon.shared.GeoportalItemReferences;
import org.gcube.application.geoportalcommon.shared.SearchingFilter;
import org.gcube.application.geoportalcommon.shared.geoportal.ConfigurationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.DocumentDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ResultDocumentDV;
import org.gcube.application.geoportalcommon.shared.geoportal.config.ItemFieldDV;
import org.gcube.application.geoportalcommon.shared.geoportal.geojson.GeoJSON;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.GCubeSDIViewerLayerDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.IndexLayerDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.PayloadDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.IdentificationReferencesTYPE;
import org.gcube.application.geoportalcommon.shared.geoportal.project.ProjectDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.TemporalReferenceDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.GEOPORTAL_DATA_HANDLER;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.HandlerDeclarationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.UseCaseDescriptorDV;
import org.gcube.application.geoportalcommon.shared.geoportal.view.ProjectView;
import org.gcube.application.geoportalcommon.shared.gis.BoundsMap;
import org.gcube.application.geoportalcommon.util.URLParserUtil;
import org.gcube.portlets.user.geoportaldataviewer.client.GeoportalDataViewerConstants;
import org.gcube.portlets.user.geoportaldataviewer.client.GeoportalDataViewerService;
import org.gcube.portlets.user.geoportaldataviewer.server.gis.FeatureParser;
import org.gcube.portlets.user.geoportaldataviewer.server.gis.GisMakers;
import org.gcube.portlets.user.geoportaldataviewer.server.gis.WMSUrlValidator;
import org.gcube.portlets.user.geoportaldataviewer.server.mongoservice.GeoportalServiceIdentityProxy;
import org.gcube.portlets.user.geoportaldataviewer.server.util.ContextRequest;
import org.gcube.portlets.user.geoportaldataviewer.server.util.SessionUtil;
import org.gcube.portlets.user.geoportaldataviewer.server.util.TemporalComparatorUtil;
import org.gcube.portlets.user.geoportaldataviewer.shared.GCubeCollection;
import org.gcube.portlets.user.geoportaldataviewer.shared.GeoNaSpatialQueryResult;
import org.gcube.portlets.user.geoportaldataviewer.shared.ItemFieldsResponse;
import org.gcube.portlets.user.geoportaldataviewer.shared.ResultSetPaginatedDataIDs;
import org.gcube.portlets.user.geoportaldataviewer.shared.ViewerConfiguration;
import org.gcube.portlets.user.geoportaldataviewer.shared.faults.ControlledError;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.BaseMapLayer;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.LayerItem;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.LayerObject;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.LayerObjectType;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.wfs.FeatureRow;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.wms.GeoInformationForWMSRequest;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.wms.Styles;
import org.gcube.portlets.user.geoportaldataviewer.shared.gis.wms.ZAxis;
import org.gcube.spatial.data.geoutility.GeoNcWMSMetadataUtility;
import org.gcube.spatial.data.geoutility.bean.LayerStyles;
import org.gcube.spatial.data.geoutility.bean.LayerZAxis;
import org.gcube.spatial.data.geoutility.bean.WmsParameters;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Nov 12, 2020
*/
@SuppressWarnings("serial")
public class GeoportalDataViewerServiceImpl extends RemoteServiceServlet implements GeoportalDataViewerService {
private static final Logger LOG = LoggerFactory.getLogger(GeoportalDataViewerServiceImpl.class);
/**
* The Enum COMMON_IMAGES_FORMAT.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Oct 18, 2022
*/
public static enum COMMON_IMAGES_FORMAT {
gif, png, jpeg, jpg, bmp, tif, tiff, svg, avif, webp
}
/**
* The Class ImageDetector.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Oct 18, 2022
*/
public static class ImageDetector {
/**
* Gets the names.
*
* @param e the e
* @return the names
*/
private static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}
public static List<String> listFormatImages;
static {
String[] arrayImgs = ImageDetector.getNames(COMMON_IMAGES_FORMAT.class);
listFormatImages = Arrays.asList(arrayImgs);
}
/**
* Checks if is image.
*
* @param mimeType the mime type
* @return true, if is image
*/
public static boolean isImage(String mimeType) {
if (mimeType == null || mimeType.isEmpty())
return false;
String inputImageFormat = mimeType.replaceAll("image/", "");
return listFormatImages.contains(inputImageFormat);
}
}
/**
* Gets the GNA data viewe config profile.
*
* @return the GNA data viewe config profile
* @throws Exception the exception
*/
private GNADataViewerConfigProfile getGNADataVieweConfigProfile() throws Exception {
GNADataViewerConfigProfile profile = SessionUtil.getGNADataViewerConfigProfile(getThreadLocalRequest());
if (profile == null) {
LOG.info(GNADataViewerConfigProfile.class.getSimpleName() + " is null, loading configurations from IS");
// to be sure
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GeoportalCommon geoportalComm = new GeoportalCommon();
profile = geoportalComm.readGNADataViewerConfig(null);
} else {
LOG.info(GNADataViewerConfigProfile.class.getSimpleName() + " read from session");
}
return profile;
}
/**
* Parses the wms request.
*
* @param wmsRequest the wms request
* @param layerName the layer name
* @return the geo information for WMS request
* @throws Exception the exception
*/
@Override
public GeoInformationForWMSRequest parseWmsRequest(String wmsRequest, String layerName) throws Exception {
return loadGeoInfoForWmsRequest(wmsRequest, layerName);
}
/**
* Load geo info for wms request.
*
* @param wmsLink the wms link
* @param layerName the layer name
* @return the geo information for WMS request
* @throws Exception the exception
*/
public GeoInformationForWMSRequest loadGeoInfoForWmsRequest(String wmsLink, String layerName) throws Exception {
try {
WMSUrlValidator validator = new WMSUrlValidator(wmsLink, layerName);
String wmsServiceHost = validator.getWmsServiceHost();
String validWMSRequest = validator.parseWMSRequest(true, true);
layerName = validator.getLayerName();
String versionWms = validator.getValueOfParsedWMSParameter(WmsParameters.VERSION);
String crs = validator.getValueOfParsedWMSParameter(WmsParameters.CRS);
//
HashMap<String, String> mapWmsNotStandard = new HashMap<String, String>();
if (validator.getMapWmsNoStandardParams() != null) {
mapWmsNotStandard.putAll(validator.getMapWmsNoStandardParams());
}
//
GeoNcWMSMetadataUtility geoGS = new GeoNcWMSMetadataUtility(validWMSRequest, 4000);
// STYLES
LayerStyles layerStyle = geoGS.loadStyles();
Map<String, String> mapNcWmsStyles = layerStyle.getMapNcWmsStyles() == null ? new HashMap<String, String>(1)
: layerStyle.getMapNcWmsStyles();
mapWmsNotStandard.putAll(mapNcWmsStyles);
// MAP STYLES INTO GWT-SERIALIZABLE OBJECT
Styles styles = new Styles(layerStyle.getGeoStyles(), layerStyle.getMapNcWmsStyles(), layerStyle.isNcWms());
// ZAxis
LayerZAxis layerZAxis = geoGS.loadZAxis();
// MAP ZAXIS INTO GWT-SERIALIZABLE OBJECT
ZAxis zAxis = layerZAxis != null
? new ZAxis(layerZAxis.getUnits(), layerZAxis.isPositive(), layerZAxis.getValues())
: null;
return new GeoInformationForWMSRequest(wmsServiceHost, validWMSRequest, layerName, versionWms, crs,
mapWmsNotStandard, styles, styles.isNcWms(), zAxis);
} catch (Exception e) {
String msg = "An error occurred during wms request validation for layer: " + layerName;
LOG.error(msg, e);
throw new Exception(msg);
}
}
/**
* Gets the parameters from URL.
*
* @param theURL the the URL
* @param parameters the parameters
* @return a map with couple (paramKey, paramValue)
*/
public Map<String, String> getParametersFromURL(String theURL, List<String> parameters) {
if (theURL == null)
return null;
if (parameters == null || parameters.size() == 0)
return null;
Map<String, String> hashParameters = new HashMap<String, String>(parameters.size());
for (String paramKey : parameters) {
String paramValue = URLParserUtil.extractValueOfParameterFromURL(paramKey, theURL);
hashParameters.put(paramKey, paramValue);
}
return hashParameters;
}
/**
* Gets the my login.
*
* @return the my login
*/
@Override
public String getMyLogin() {
try {
GCubeUser user = SessionUtil.getCurrentUser(this.getThreadLocalRequest());
if (user == null)
return null;
return user.getUsername();
} catch (Exception e) {
LOG.warn("Error on getting the login, am I out of portal? Returning null");
return null;
}
}
/**
* Gets the geo na data view profile.
*
* @return the geo na data view profile
* @throws Exception the exception
*/
@Override
public GNADataViewerConfigProfile getGeoNaDataViewProfile() throws Exception {
LOG.info("getGeoNaDataViewProfile called");
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GNADataViewerConfigProfile profile = getGNADataVieweConfigProfile();
LOG.info("Returning profile: " + profile);
return profile;
}
/**
* Gets the public links for.
*
* @param item the item
* @return the public links for
* @throws Exception the exception
*/
@Override
public GeoportalItemReferences getPublicLinksFor(GeoportalItemReferences item) throws Exception {
LOG.info("getPublicLinksFor called for: " + item);
try {
if (item == null)
throw new Exception("Bad request, the item is null");
if (item.getProjectID() == null)
throw new Exception("Bad request, the projectID is null");
if (item.getProfileID() == null)
throw new Exception("Bad request, the profileID is null");
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GeoportalCommon gc = new GeoportalCommon();
return gc.getPublicLinksFor(item, true);
} catch (Exception e) {
LOG.error("Error on getPublicLinksFor for: " + item, e);
throw new Exception("Share link not available for this item. Try later or contact the support. Error: "
+ e.getMessage());
}
}
/**
* Checks if is session expired.
*
* @return true, if is session expired
* @throws Exception the exception
*/
public boolean isSessionExpired() throws Exception {
return SessionUtil.isSessionExpired(this.getThreadLocalRequest());
}
/**
* Gets the WFS features.
*
* @param layerObjects the layer objects
* @param mapSrsName the map srs name
* @param selectBBOX the select BBOX
* @param maxWFSFeature the max WFS feature. If 0 means all feature
* @param zoomLevel the zoom level
* @return the WFS features
*/
@Override
public List<GeoNaSpatialQueryResult> getWFSFeatures(List<LayerObject> layerObjects, String mapSrsName,
BoundsMap selectBBOX, int maxWFSFeature, double zoomLevel) {
LOG.info("getWFSFeatures called");
List<GeoNaSpatialQueryResult> listDAO = new ArrayList<GeoNaSpatialQueryResult>(layerObjects.size());
for (LayerObject layerObject : layerObjects) {
GeoNaSpatialQueryResult geoDAO = new GeoNaSpatialQueryResult();
List<FeatureRow> features = FeatureParser.getWFSFeatures(layerObject.getLayerItem(), mapSrsName, selectBBOX,
maxWFSFeature);
LOG.debug("For layer name: " + layerObject.getLayerItem().getName() + " got features: " + features);
geoDAO.setFeatures(features);
geoDAO.setSourceLayerObject(layerObject);
LOG.info("For layer name: " + layerObject.getLayerItem().getName() + " got " + features.size()
+ " feature/s");
listDAO.add(geoDAO);
}
LOG.info("returning " + listDAO + " geona data objects");
return listDAO;
}
/**
* Gets the list base layers.
*
* @return the list base layers
*/
@Override
public List<BaseMapLayer> getListBaseLayers() {
LOG.info("getListBaseLayers called");
List<BaseMapLayer> listBL = new ArrayList<BaseMapLayer>();
// Setting scope in the cuurent thread
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
listBL = SessionUtil.getGNABaseMaps(this.getThreadLocalRequest());
LOG.info("getListBaseLayers returning " + listBL.size() + " base maps");
return listBL;
}
/**
* NEW CODE HERE.
*
* @return the initial configuration
* @throws Exception the exception
*/
@Override
public ViewerConfiguration getInitialConfiguration() throws Exception {
LOG.debug("getInitialConfiguration called");
return new ContextRequest<ViewerConfiguration>(this.getThreadLocalRequest()) {
@Override
protected ViewerConfiguration run() throws Exception, ControlledError {
try {
// ************* LOAD BASE LAYERS
final ViewerConfiguration config = new ViewerConfiguration();
LOG.info("Getting initial configuration ");
LOG.debug("Loading base layers..");
List<BaseMapLayer> listBL = SessionUtil.getGNABaseMaps(request);
LOG.debug("getListBaseLayers returning " + listBL.size() + " base maps");
config.setBaseLayers(listBL);
// ************** LOAD AVAILABLE COLLECTIONS
LOG.debug("Loading available collections.. ");
config.setAvailableCollections(new HashMap<String, GCubeCollection>());
// TODO filter by
// configured ?
// gis indexed
QueryRequest request = new QueryRequest();
// TODO Constant
String Id = "org.gcube.portlets.user.geoportaldataviewer";
request.setFilter(Document.parse("{\"" + UseCaseDescriptor.HANDLERS + "."
+ org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration.ID
+ "\" : " + "{\"$eq\" : \"" + Id + "\"}}"));
useCaseDescriptors().build().query(new QueryRequest()).forEachRemaining(u -> {
try {
LOG.debug("Checking configuration for collection " + u.getId());
Projects<Project> p = projects(u.getId()).build();
UseCaseDescriptorDV ucd = ConvertToDataValueObjectModel.toUseCaseDescriptorDV(u, null);
Configuration ucdConfig = p.getConfiguration();
GCubeCollection coll = new GCubeCollection();
coll.setUcd(ucd);
// TODO TO Check index flag should be in configuration or evaluated according to
// user credentials
String indexFlag = "public"; // default
GeoportalServiceIdentityProxy gsp = getGeoportalServiceProxy();
if (gsp.isUser()) {
indexFlag = "internal";
LOG.info("user logged - using indexFlag: " + indexFlag);
} else if (gsp.isIAMClient()) {
indexFlag = "public";
LOG.info("user not logged - using indexFlag: " + indexFlag);
}
// TODO constant
coll.setIndexes(new ArrayList());
LOG.debug(
"Checking if " + u.getId() + " is GIS Indexed. Index flag needed is " + indexFlag);
for (Index index : ucdConfig.getIndexes()) {
try {
IndexLayerDV toAdd = ConvertToDataValueObjectModel.convert(index);
if (toAdd.getFlag().equals(indexFlag)) {
coll.getIndexes().add(toAdd);
}
} catch (Exception e) {
LOG.debug("Skipping invalid index ", e);
} catch (Throwable t) {
LOG.error("Unable to check index ", t);
}
}
// Return only if gis indexed
if (coll.getIndexes().isEmpty())
LOG.info("No available GIS Index for collection " + coll.getUcd().getName());
else
config.getAvailableCollections().put(coll.getUcd().getId(), coll);
} catch (Throwable t) {
LOG.warn("Invalid UCD, can't translate to DV. UCID : " + u.getId(), t);
}
});
// TODO load initial layers from query parameters
LOG.debug("Found " + config.getAvailableCollections().size() + " collections");
return config;
} catch (Throwable t) {
LOG.error("Unexpected exception while loading initial config", t);
throw new ControlledError("Unable to configure viewer. Please retry in a few minutes.");
}
}
}.execute().getResult();
}
/**
* Gets the config list of fields for searching.
*
* @return the config list of fields for searching
* @throws Exception the exception
*/
@Override
public List<ItemFieldsResponse> getConfigListOfFieldsForSearching() throws Exception {
LOG.info("listOfFieldsForSearching called");
try {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
List<ItemFieldsResponse> listIFResponse = new ArrayList<ItemFieldsResponse>();
List<String> handlersIds = Arrays.asList(GEOPORTAL_DATA_HANDLER.geoportal_basic_data_list.getId());
List<UseCaseDescriptor> listUseCaseDescriptor;
try {
UseCaseDescriptorCaller client = GeoportalClientCaller.useCaseDescriptors();
listUseCaseDescriptor = client.getListForHandlerIds(handlersIds);
} catch (Exception e) {
LOG.error("Error on reading handlerIds: " + handlersIds + ", in the UCDs", e);
throw e;
}
if (listUseCaseDescriptor == null) {
listUseCaseDescriptor = new ArrayList<UseCaseDescriptor>();
}
for (UseCaseDescriptor ucd : listUseCaseDescriptor) {
UseCaseDescriptorDV ucdDV = ConvertToDataValueObjectModel.toUseCaseDescriptorDV(ucd, null);
HandlerDeclarationDV dataListHandler = getHandlerDeclarationFor(ucdDV,
GEOPORTAL_DATA_HANDLER.geoportal_basic_data_list);
if (dataListHandler != null) {
ConfigurationDV<?> config = dataListHandler.getConfiguration();
switch (config.getConfigurationType()) {
case item_fields:
ItemFieldsResponse ifResponse = new ItemFieldsResponse();
ifResponse.setUseCaseDescriptorDV(ucdDV);
List<ItemFieldDV> listItemFields = (List<ItemFieldDV>) config.getConfiguration();
ifResponse.setListItemFields(listItemFields);
listIFResponse.add(ifResponse);
break;
default:
break;
}
}
}
LOG.info("listOfFieldsForSearching returning: " + listIFResponse);
return listIFResponse;
} catch (Exception e) {
LOG.error("Error on loading list of fields for searching: ", e);
throw new Exception("Error occurred on loading list of fields for searching. Error: " + e.getMessage());
}
}
/**
* Gets the handler declaration for.
*
* @param useCaseDescriptor the use case descriptor
* @param dataHandler the data handler
* @return the handler declaration for
*/
public static HandlerDeclarationDV getHandlerDeclarationFor(UseCaseDescriptorDV useCaseDescriptor,
GEOPORTAL_DATA_HANDLER dataHandler) {
if (useCaseDescriptor == null)
return null;
for (HandlerDeclarationDV handler : useCaseDescriptor.getHandlers()) {
GEOPORTAL_DATA_HANDLER dataHandlerType = handler.getDataHandlerType();
if (dataHandlerType != null && dataHandlerType.equals(dataHandler)) {
return handler;
}
}
return null;
}
/**
* Inits the.
*
* @param config the config
* @throws ServletException the servlet exception
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
LOG.info("init called");
// Init one GcubeProfilesPerUCDIdCache for the application
new GcubeProfilesPerUCDIdCache();
}
/**
* On before request deserialized.
*
* @param serializedRequest the serialized request
*/
@Override
protected void onBeforeRequestDeserialized(String serializedRequest) {
LOG.info("onBeforeRequestDeserialized called");
String scope = "";
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
scope = SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
// Loading GcubeProfilesPerUCDIdCache per scope
GcubeProfilesPerUCDIdCache.get(scope);
} catch (Exception e) {
LOG.error("Error on loading the " + GcubeProfilesPerUCDIdCache.class.getSimpleName() + " for scope: "
+ scope, e);
}
super.onBeforeRequestDeserialized(serializedRequest);
}
/**
* Gets the list projects.
*
* @param theProfileID the the profile ID
* @param start the start
* @param limit the limit
* @param filter the filter
* @param reloadFromService the reload from service
* @return the list projects
* @throws Exception the exception
*/
@Override
public ResultSetPaginatedDataIDs getListProjects(String theProfileID, Integer start, Integer limit,
SearchingFilter filter, boolean reloadFromService) throws Exception {
LOG.info("getListProjects called with profileID: " + theProfileID + ", start: " + start + ", limit: " + limit
+ ", filter: " + filter);
try {
ProjectsCaller client = GeoportalClientCaller.projects();
SessionUtil.getCurrentContext(getThreadLocalRequest(), true);
// Saving client PROJECTION
LinkedHashMap<String, Object> originalProjection = filter.getProjection();
// Setting PROJECTION ONLY FOR PROEJCT ID
LinkedHashMap<String, Object> projectionForIDs = new LinkedHashMap<String, Object>();
projectionForIDs.put(Project.ID, 1);
filter.setProjection(projectionForIDs);
ResultSetPaginatedDataIDs searchedDataIDs = new ResultSetPaginatedDataIDs();
Integer totalProjectForProfile = SessionUtil.getTotalDocumentForProfileID(getThreadLocalRequest(),
theProfileID);
if (totalProjectForProfile == null) {
totalProjectForProfile = client.getTotalDocument(theProfileID);
SessionUtil.setTotalDocumentForProfileID(getThreadLocalRequest(), theProfileID, totalProjectForProfile);
}
searchedDataIDs.setTotalItems(totalProjectForProfile);
LOG.info("Total Docs read from config: " + totalProjectForProfile);
// FIRST QUERY TO RETRIEVE IDs
// LIMIT IS NULL AND START = 0 MEANS THAT IT IS EQUAL TO NUMBER TOTAL OF
// DOCUMENTS
final Iterator<Project> projectsIDs = client.queryOnMongo(theProfileID, totalProjectForProfile, 0, null,
filter);
// Getting the Project IDs from the Iterable
Iterable<Project> itP = () -> projectsIDs;
Stream<Project> targetStream = StreamSupport.stream(itP.spliterator(), false);
List<String> listProjectIDs = targetStream.map(Project::getId).collect(Collectors.toList());
searchedDataIDs.setResultSetProjectIDs(listProjectIDs);
// Total number of Projects are exactly listProjectIDs.size()
int totalItems = listProjectIDs.size();
searchedDataIDs.setTotalItems(totalItems);
LOG.info("Total IDs read from query: " + totalItems);
// NOW PERFORMING THE (REAL) SECOND QUERY FROM CLIENT
// SETTING ORIGINAL PROJECTION FROM CLIENT
filter.setProjection(originalProjection);
// LIMIT IS FROM CLIENT
Iterator<Project> projects = client.queryOnMongo(theProfileID, totalItems, start, limit, filter);
searchedDataIDs.setClientStartIndex(start);
searchedDataIDs.setLimit(limit);
searchedDataIDs.setServerSearchFinished(false);
List<ResultDocumentDV> toReturnList = ConvertToDataValueObjectModel.toListResultDocument(projects);
searchedDataIDs.setData(toReturnList);
// TODO BUGGY WORKAROUND. BLOCKED BY #22487 IT MUST BE REMOVE AFTER THE QUERY
// COUNT
// AND LIST.SIZE BY QUERY WILL BE AVAILABLE IN THE SERVICE
// if (filter.getConditions() != null) {
// searchedDataIDs.setTotalItems(toReturnList.size());
// int totalItems = searchedDataIDs.getResultSetProjectIDs().size();
// searchedDataIDs.setTotalItems(totalItems);
// }
if (totalProjectForProfile == limit || totalProjectForProfile == 0) {
LOG.debug("Page completed returning " + totalProjectForProfile + " projects");
int newOffset = start + limit;
searchedDataIDs
.setServerSearchFinished(newOffset > totalProjectForProfile || totalProjectForProfile == 0);
LOG.debug("is Search finished: " + searchedDataIDs.isServerSearchFinished());
}
if (LOG.isDebugEnabled()) {
LOG.debug("returning {}", searchedDataIDs.getData());
}
List<? extends DocumentDV> data = searchedDataIDs.getData();
if (data != null) {
LOG.info("returning {} project/s", data.size());
}
return searchedDataIDs;
} catch (Exception e) {
LOG.error("Error on loading paginated and filtered list of projects for id: ", e);
throw new Exception("Error occurred on loading list of Concessioni. Error: " + e.getMessage());
}
}
/**
* Gets the layers for id.
*
* @param profileID the profile ID
* @param projectID the project ID
* @return the layers for id
* @throws Exception the exception
*/
@Override
public List<GCubeSDIViewerLayerDV> getLayersForId(String profileID, String projectID) throws Exception {
LOG.info("getLayersForId [profileID: " + profileID + ", projectID: " + projectID + "] called");
if (profileID == null)
throw new Exception("Invalid parameter. The profileID is null");
if (projectID == null)
throw new Exception("Invalid parameter. The projectID is null");
List<GCubeSDIViewerLayerDV> listLayers = null;
try {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
String username = null;
try {
username = SessionUtil.getCurrentUser(this.getThreadLocalRequest()).getUsername();
} catch (Exception e) {
LOG.info("User not found in session, the userName for checking the policy will be null");
}
LOG.trace("Trying to get project for id " + projectID);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
String jsonDocument = theProject.getTheDocument().toJson();
LOG.trace("JSON Project is: " + jsonDocument);
LOG.debug("Checking access policy for the layer...");
ACCESS_POLICY accessPolicy = GeportalCheckAccessPolicy.accessPolicyFromSessionLogin(username);
LOG.info("Access policy for discovering the layers is: " + accessPolicy);
String filesetParentJSONPath = null;
//(see ticket #24390)
if (accessPolicy.equals(ACCESS_POLICY.OPEN)) {
// Filtering for ACCESS_POLICY.OPEN from the fileset when the username is not in
// session. IAM
// identity is running, no logged in user.
filesetParentJSONPath = String.format("%s..%s[?(@._access._policy=='%s')]",
Geoportal_JSON_Mapper.JSON_$_POINTER, Geoportal_JSON_Mapper.FILESET, accessPolicy);
} else {
// Accessing to all fileset (with any ACCESS_POLICY) when the user is logged in.
filesetParentJSONPath = String.format("%s..%s", Geoportal_JSON_Mapper.JSON_$_POINTER,
Geoportal_JSON_Mapper.FILESET);
}
listLayers = Geoportal_JSON_Mapper.readGcubeSDILayersForFileset(filesetParentJSONPath, jsonDocument);
LOG.info("For projectID " + projectID + ", returning " + listLayers.size() + " layer/s");
return listLayers;
} catch (Exception e) {
String erroMsg = "Layers are not available for profileID " + profileID + " with projectID " + projectID;
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
}
/**
* Gets the images for id.
*
* @param profileID the profile ID
* @param projectID the project ID
* @param limitToFirstOneFound the limit to first one found
* @return the images for id
* @throws Exception the exception
*/
protected List<PayloadDV> getImagesForId(String profileID, String projectID, boolean limitToFirstOneFound)
throws Exception {
LOG.info("getImagesForId [profileID: " + profileID + ", projectID: " + projectID + ", limitToFirstOneFound: "
+ limitToFirstOneFound + "] called");
if (profileID == null)
throw new Exception("Invalid parameter. The profileID is null");
if (projectID == null)
throw new Exception("Invalid parameter. The projectID is null");
List<PayloadDV> listImages = null;
try {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
try {
SessionUtil.getCurrentUser(this.getThreadLocalRequest()).getUsername();
} catch (Exception e) {
LOG.info("User not found in session, the userName for checking the policy will be null");
}
LOG.info("Trying to get project for id " + profileID);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
String jsonDocument = theProject.getTheDocument().toJson();
LOG.trace("JSON Project is: " + jsonDocument);
String filesetJSONPath = String.format("%s..%s", Geoportal_JSON_Mapper.JSON_$_POINTER,
Geoportal_JSON_Mapper.FILESET);
listImages = Geoportal_JSON_Mapper.readImagesForFileset(filesetJSONPath, jsonDocument,
limitToFirstOneFound);
LOG.info("For projectID " + projectID + ", returning " + listImages.size() + " image/s");
return listImages;
} catch (Exception e) {
String erroMsg = "Images are not available for profileID " + profileID + " with projectID " + projectID;
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
}
/**
* Gets the project view for id.
*
* @param profileID the profile ID
* @param projectID the project ID
* @return the project view for id
* @throws Exception the exception
*/
@Override
public ProjectView getProjectViewForId(String profileID, String projectID) throws Exception {
LOG.info("getProjectViewForId profileID: " + profileID + ", projectID: " + projectID + ", called");
if (profileID == null || projectID == null)
throw new Exception("Invalid parameter. Either profileID or projectID is null");
try {
String scope = SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
String userName = null;
try {
userName = SessionUtil.getCurrentUser(this.getThreadLocalRequest()).getUsername();
} catch (Exception e) {
LOG.info("User not found in session, the userName for checking the policy will be null");
}
LOG.info("Trying to get project for id " + profileID);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
UseCaseDescriptor ucd = SessionUtil.getUCDForId(this.getThreadLocalRequest(), profileID);
if (ucd == null) {
ucd = GeoportalClientCaller.useCaseDescriptors().getUCDForId(profileID);
SessionUtil.setUCDForId(this.getThreadLocalRequest(), profileID, ucd);
}
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
ProjectDVBuilder projectBuilder = ProjectDVBuilder.newBuilder().fullDocumentMap(true);
projectBuilder.relationships(true);
ProjectDV theProjectDV = ConvertToDataValueObjectModel.toProjectDV(theProject, projectBuilder);
theProjectDV.setProfileName(ucd.getName());
TemporalReferenceDV temporalReference = temporalReferenceForProject(theProject);
if (temporalReference == null)
temporalReference = new TemporalReferenceDV();
theProjectDV.setTemporalReference(temporalReference);
ProjectView projectView = Geoportal_JSON_Mapper.loadProjectView(theProjectDV, scope, userName);
if (LOG.isTraceEnabled()) {
Geoportal_JSON_Mapper.prettyPrintProjectView(projectView);
}
LOG.info("returning project view for id: " + projectView.getTheProjectDV().getId());
return projectView;
} catch (Exception e) {
String erroMsg = "Error occurred on creating projectView for id: " + projectID;
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
}
/**
* Gets the project edit for id.
*
* @param profileID the profile ID
* @param projectID the project ID
* @return the project edit for id
* @throws Exception the exception
*/
public ProjectView getProjectEditForId(String profileID, String projectID) throws Exception {
LOG.info("getProjectEditForId profileID: " + profileID + ", projectID: " + projectID + ", called");
if (profileID == null || projectID == null)
throw new Exception("Invalid parameter. Either profileID or projectID is null");
try {
String scope = SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
String userName = null;
try {
userName = SessionUtil.getCurrentUser(this.getThreadLocalRequest()).getUsername();
} catch (Exception e) {
LOG.info("User not found in session, the userName for checking the policy will be null");
}
LOG.info("Trying to get project for id " + profileID);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
UseCaseDescriptor ucd = SessionUtil.getUCDForId(this.getThreadLocalRequest(), profileID);
if (ucd == null) {
ucd = GeoportalClientCaller.useCaseDescriptors().getUCDForId(profileID);
SessionUtil.setUCDForId(this.getThreadLocalRequest(), profileID, ucd);
}
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
ProjectDVBuilder projectBuilder = ProjectDVBuilder.newBuilder().fullDocumentMap(true);
projectBuilder.relationships(true);
ProjectDV theProjectDV = ConvertToDataValueObjectModel.toProjectDV(theProject, projectBuilder);
theProjectDV.setProfileName(ucd.getName());
ProjectView projectView = Geoportal_JSON_Mapper.loadProjectView(theProjectDV, scope, userName);
if (LOG.isTraceEnabled()) {
Geoportal_JSON_Mapper.prettyPrintProjectView(projectView);
}
LOG.info("returning project view for id: " + projectView.getTheProjectDV().getId());
return projectView;
} catch (Exception e) {
String erroMsg = "Error occurred on creating projectView for id: " + projectID;
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
}
/**
* Gets the data result.
*
* @param layerObjects the layer objects
* @param mapSrsName the map srs name
* @param selectBBOX the select BBOX
* @param maxWFSFeature the max WFS feature
* @param zoomLevel the zoom level
* @return the data result
* @throws Exception the exception
*/
@Override
public List<GeoNaSpatialQueryResult> getDataResult(List<LayerObject> layerObjects, String mapSrsName,
BoundsMap selectBBOX, int maxWFSFeature, double zoomLevel) throws Exception {
LOG.info("getDataResult called");
for (LayerObject layerObject : layerObjects) {
LOG.info("ProfileID: " + layerObject.getProfileID() + ", ProjectID: " + layerObject.getProjectID()
+ ", TYPE: " + layerObject.getType());
}
if (LOG.isDebugEnabled()) {
LOG.debug("getDataResult parmeters layerObjects: " + layerObjects,
", mapSrsName: " + mapSrsName + ", selectBBOX: " + selectBBOX + ", maxWFSFeature: " + maxWFSFeature
+ ", zoomLevel: " + zoomLevel);
}
List<GeoNaSpatialQueryResult> listDAO = new ArrayList<GeoNaSpatialQueryResult>(layerObjects.size());
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
for (LayerObject layerObject : layerObjects) {
GeoNaSpatialQueryResult geoDAO = new GeoNaSpatialQueryResult();
List<FeatureRow> features = FeatureParser.getWFSFeatures(layerObject.getLayerItem(), mapSrsName,
selectBBOX, maxWFSFeature);
LOG.debug("For layer name: " + layerObject.getLayerItem().getName() + " got features: " + features);
geoDAO.setFeatures(features);
if (features != null && features.size() > 0) {
LayerObjectType loType = layerObject.getType();
if (loType == null)
loType = LayerObjectType.GENERIC_LAYER;
switch (layerObject.getType()) {
case INDEX_LAYER: {
// Expected more than 1 feature for the BBOX of the Map
FeatureRow fRow = features.get(0);
// using only the first feature returned from BBOX of the Map
// when querying the centroid layers
geoDAO.setFeatures(Arrays.asList(fRow));
if (fRow.getMapProperties() != null) {
List<String> productIDs = fRow.getMapProperties()
.get(GeoportalDataViewerConstants.PROJECT_ID_KEY_FEATURE);
if (productIDs != null && productIDs.size() > 0) {
String projectID = productIDs.get(0);
layerObject.setProjectID(projectID);
String profileID = layerObject.getProfileID();
List<PayloadDV> images;
// Loading images for profileID and projectID
try {
images = getImagesForId(profileID, projectID, true);
Map<String, List<PayloadDV>> mapImages = new LinkedHashMap<String, List<PayloadDV>>();
mapImages.put(projectID, images);
// mapImages.put(cId, listUI);
geoDAO.setMapImages(mapImages);
} catch (Exception e) {
LOG.warn("Error on loading images for projectID: " + projectID + " profileID: "
+ profileID);
}
// Sets only profileID and profileName into ProjectDV
if (layerObject.getProjectDV() == null
|| layerObject.getProjectDV().getTheDocument() == null) {
ProjectDV projectDV = minimalProjectDV(profileID, projectID, true, 2);
layerObject.setProjectDV(projectDV);
}
if (layerObject.getProjectDV().getTemporalReference() == null) {
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID,
projectID);
TemporalReferenceDV temporalReferenceDV = temporalReferenceForProject(theProject);
// Empty TemporalReferenceDV
if (temporalReferenceDV == null)
temporalReferenceDV = new TemporalReferenceDV();
layerObject.getProjectDV().setTemporalReference(temporalReferenceDV);
}
}
}
geoDAO.setSourceLayerObject(layerObject);
LOG.info("For layer name: " + layerObject.getLayerItem().getName() + " got " + features.size()
+ " feature/s");
listDAO.add(geoDAO);
break;
}
case PROJECT_LAYER:
case GENERIC_LAYER: {
LOG.debug("The LayerObject is a of kind: " + layerObject.getType());
// TODO CHECK THIS
// Getting the projectid from WFS features, but limiting to the first one, Do we
// have more than one centroid in the same position??
// Mininal set of info for displaying into popup
if (layerObject.getProjectDV() == null) {
ProjectDV projectDV = minimalProjectDV(layerObject.getProfileID(),
layerObject.getProjectID(), false, 0);
layerObject.setProjectDV(projectDV);
}
if (layerObject.getProjectDV().getSpatialReference() == null) {
GeoJSON geoJson = getSpatialReference(layerObject.getProfileID(),
layerObject.getProjectID());
layerObject.getProjectDV().setSpatialReference(geoJson);
}
if (layerObject.getProjectDV().getTheDocument() == null) {
try {
LinkedHashMap<String, Object> documentAsMap = getEntrySetsDocumentForProjectID(
layerObject.getProfileID(), layerObject.getProjectID(), 1);
DocumentDV documentDV = new DocumentDV();
documentDV.setDocumentAsMap(documentAsMap);
layerObject.getProjectDV().setTheDocument(documentDV);
} catch (Exception e) {
String erroMsg = "Error occurred on loading document for profileID "
+ layerObject.getProfileID() + " and projectID " + layerObject.getProjectID();
LOG.warn(erroMsg, e);
}
}
if (layerObject.getProjectDV().getTemporalReference() == null) {
Project theProject = GeoportalClientCaller.projects()
.getProjectByID(layerObject.getProfileID(), layerObject.getProjectID());
TemporalReferenceDV temporalReferenceDV = temporalReferenceForProject(theProject);
// Empty TemporalReferenceDV
if (temporalReferenceDV == null)
temporalReferenceDV = new TemporalReferenceDV();
layerObject.getProjectDV().setTemporalReference(temporalReferenceDV);
}
LOG.debug("Case PROJECT_LAYER/GENERIC_LAYER setting layerObject: " + layerObject);
geoDAO.setSourceLayerObject(layerObject);
LOG.info("For layer name: " + layerObject.getLayerItem().getName() + " got " + features.size()
+ " feature/s");
listDAO.add(geoDAO);
// Ordering for temporal dimension
try {
Collections.sort(listDAO, new TemporalComparatorUtil());
} catch (Exception e) {
// silent
}
}
default:
break;
}
}
}
} catch (Exception e) {
String erroMsg = "Error occurred on getting data results";
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
LOG.info("returning " + listDAO.size() + " geona data objects");
if (LOG.isDebugEnabled()) {
LOG.debug("returning " + listDAO + " geona data objects");
}
return listDAO;
}
/**
* Minimal project DV.
*
* @param profileID the profile ID
* @param projectID the project ID
* @param loadDocument the load document
* @param limitDocumentEntries the limit document entries
* @return the project DV
*/
private ProjectDV minimalProjectDV(String profileID, String projectID, boolean loadDocument,
int limitDocumentEntries) {
LOG.debug("called minimalProjectDV for profileID: " + profileID + ", projectID: " + projectID
+ ", loadDocument: " + loadDocument + ", limitDocumentEntries: " + limitDocumentEntries);
QueryRequest request = new QueryRequest();
request.setFilter(
Document.parse("{\"" + UseCaseDescriptor.ID + "\" : " + "{\"$eq\" : \"" + profileID + "\"}}"));
request.setProjection(Document.parse("{\"" + UseCaseDescriptor.NAME + "\" : " + "1}"));
ProjectDV projectDV = new ProjectDV();
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
useCaseDescriptors().build().query(request).forEachRemaining(u -> {
try {
LOG.debug("UCD for id" + u.getId() + " returend name: " + u.getName());
projectDV.setId(projectID);
projectDV.setProfileName(u.getName());
projectDV.setProfileID(u.getId());
} catch (Exception e) {
LOG.warn("Invalid UCD, UCID : " + u.getId());
}
});
if (loadDocument) {
LinkedHashMap<String, Object> theDocument = getEntrySetsDocumentForProjectID(profileID, projectID,
limitDocumentEntries);
DocumentDV docDV = new DocumentDV();
docDV.setDocumentAsMap(theDocument);
projectDV.setTheDocument(docDV);
}
} catch (Exception e) {
LOG.warn("Error on getting minimalProjectDV of projectID: ", e);
}
LOG.debug("minimalProjectDV returning: " + projectDV);
return projectDV;
}
/**
* Gets the spatial reference.
*
* @param profileID the profile ID
* @param projectID the project ID
* @return the spatial reference
*/
@Override
public GeoJSON getSpatialReference(String profileID, String projectID) {
LOG.trace("spatialReference for profileID: " + profileID + ", projectID: " + projectID + "called");
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
List<IdentificationReference> listIR = projects(profileID).build().getById(projectID)
.getIdentificationReferenceByType(IdentificationReferencesTYPE.SPATIAL_REFERENCE.getType());
if (listIR != null && !listIR.isEmpty()) {
String _identificationReferenceString = listIR.get(0).toJson(); // one expected
LOG.debug("converting for profileID: " + profileID + ", projectID: " + projectID + "called");
return ConvertToDataValueObjectModel.toSpatialReference(_identificationReferenceString);
}
} catch (Exception e1) {
// silent
}
return new GeoJSON();
}
/**
* Gets the entry sets document for project ID.
*
* @param profileID the profile ID
* @param projectID the project ID
* @param limit the limit
* @return the entry sets document for project ID
*/
@Override
public LinkedHashMap<String, Object> getEntrySetsDocumentForProjectID(String profileID, String projectID,
int limit) {
LOG.debug("called getEntrySetsDocumentForProjectID for profileID: " + profileID + ", projectID: " + projectID);
LinkedHashMap<String, Object> documentAsMap = new LinkedHashMap<String, Object>(limit);
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
try {
Iterator<Entry<String, Object>> entrySetsIt = theProject.getTheDocument().entrySet().iterator();
int i = 0;
while (entrySetsIt.hasNext()) {
if (i + 1 > limit)
break;
Entry<String, Object> entry = entrySetsIt.next();
documentAsMap.put(entry.getKey(), entry.getValue()!=null?entry.getValue().toString():null);
i++;
}
} catch (Exception e) {
throw e;
}
/*
* QueryRequest request = new QueryRequest();
* request.setFilter(Document.parse("{\"" + Project.ID + "\" : " +
* "{\"$eq\" : \"" + projectID + "\"}}"));
* request.setProjection(Document.parse("{\"" + Project.THE_DOCUMENT + "\" : " +
* "1}")); // should be one
* projects(profileID).build().query(request).forEachRemaining(p -> { try {
* Iterator<Entry<String, Object>> entrySetsIt =
* p.getTheDocument().entrySet().iterator(); int i = 0; while
* (entrySetsIt.hasNext()) { if (i > limit) break;
*
* Entry<String, Object> entry = entrySetsIt.next();
* documentAsMap.put(entry.getKey(), entry.getValue()); i++; }
*
* } catch (Exception e) { throw e; } });
*/
LOG.debug("getEntrySetsDocumentForProjectID returning map: " + documentAsMap);
return documentAsMap;
} catch (Exception e) {
String erroMsg = "Error occurred on loading EntrySets document for profileID " + profileID
+ " and projectID " + projectID;
LOG.warn(erroMsg, e);
}
return documentAsMap;
}
/**
* Gets the relationships for timeline.
*
* @param profileID the profile ID
* @param projectID the project ID
* @return the relationships for timeline
* @throws Exception the exception
*/
@Override
public List<String> getRelationshipsForTimeline(String profileID, String projectID) throws Exception {
if (profileID == null || projectID == null)
throw new Exception("Invalid parameter. Either profileID or projectID is null");
try {
LOG.info("Trying to getRelationshipsForTimeline for id " + profileID);
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
List<String> listJSON = new ArrayList<String>();
String template = null;
try {
template = SessionUtil.getJSONTimelineTemplate(this.getThreadLocalRequest(), profileID);
try {
if (template == null) {
Document temporalJsonTemplate = GeoportalClientCaller.useCaseDescriptors()
.readTemporalDimensionTemplate(profileID);
if (temporalJsonTemplate != null) {
template = new Document(temporalJsonTemplate).toJson();
LOG.info(UseCaseDescriptorCaller.TIMELINE_CONFIG_TJT_DOCUMENT + " read is: " + template);
SessionUtil.setJSONTimelineTemplate(this.getThreadLocalRequest(), profileID, template);
}
}
} catch (Exception e) {
LOG.warn(GEOPORTAL_DATA_HANDLER.geoportal_timeline_json_template.getType()
+ " not found!!! Timeline cannot be available");
}
// String template = "{\"content\": \"$.nome\"," + "\"title\": \"$.nome\","
// + "\"start\" : \"$.dataInizioProgetto\"," + "\"end\" : \"$.dataFineProgetto\"}";
if (template != null) {
JSONObject sourceJsonTemplate = new JSONObject(template);
Project theProject = GeoportalClientCaller.projects().getProjectByID(profileID, projectID);
List<Relationship> relationships = theProject.getRelationships();
if (relationships == null || relationships.size() == 0)
return new ArrayList<String>();
JSONObject targetJsonObject = toTimelineWithImageJSONModel(theProject, sourceJsonTemplate,
profileID, projectID, null);
targetJsonObject.put("selected", "from here");
String theJSONResult = targetJsonObject.toString();
LOG.debug("Base jsonObject " + theJSONResult);
listJSON.add(theJSONResult);
// Adding the relationships
for (Relationship relationship : relationships) {
// Adding the first level of the related project
theProject = GeoportalClientCaller.projects().getProjectByID(relationship.getTargetUCD(),
relationship.getTargetID());
targetJsonObject = toTimelineWithImageJSONModel(theProject, sourceJsonTemplate,
relationship.getTargetUCD(), relationship.getTargetID(),
relationship.getRelationshipName());
theJSONResult = targetJsonObject.toString();
listJSON.add(theJSONResult);
LOG.debug("\n\ngetRelationshipsChain for " + relationship);
Iterator<RelationshipNavigationObject> iterator = GeoportalClientCaller.projects()
.getRelationshipChain(relationship.getTargetUCD(), relationship.getTargetID(),
relationship.getRelationshipName(), true);
// Adding deep > 1
while (iterator.hasNext()) {
RelationshipNavigationObject nav = (RelationshipNavigationObject) iterator.next();
listJSON = visitRelationshipsChain(nav, relationship.getRelationshipName(), listJSON,
sourceJsonTemplate);
}
LOG.debug("Finally list of jsonObject " + listJSON);
}
}
} catch (Exception e) {
String erroMsg = "Error occurred on reading relatioships for id: " + projectID;
LOG.error(erroMsg, e);
}
LOG.debug("returning list of relantionships having size: " + listJSON.size());
return listJSON;
} catch (Exception e) {
String erroMsg = "Error occurred on reading relationships for id: " + projectID;
LOG.error(erroMsg, e);
throw new Exception(erroMsg);
}
}
/**
* Visit relationships chain.
*
* @param nav the nav
* @param relationshipName the relationship name
* @param listJSONTimelineModel the list JSON timeline model
* @param sourceJsonTemplate the source json template
* @return the list
*/
// recursive visit of the Relationships
public List<String> visitRelationshipsChain(RelationshipNavigationObject nav, String relationshipName,
List<String> listJSONTimelineModel, JSONObject sourceJsonTemplate) {
if (nav == null)
return listJSONTimelineModel;
LOG.debug("visitRelationshipsChain of target: " + nav.getTarget().getId() + ", relationshipName: "
+ relationshipName);
if (LOG.isDebugEnabled()) {
LOG.debug("visitRelationshipsChain target doc: " + nav.getTarget().getTheDocument());
LOG.debug("visitRelationshipsChain children " + nav.getChildren());
}
try {
Project targetProject = nav.getTarget();
JSONObject targetJsonObject = toTimelineWithImageJSONModel(targetProject, sourceJsonTemplate,
nav.getTarget().getProfileID(), nav.getTarget().getId(), relationshipName);
String theJSONResult = targetJsonObject.toString();
listJSONTimelineModel.add(theJSONResult);
LOG.debug("Built jsonObject " + theJSONResult);
} catch (Exception e) {
LOG.warn("Skipping " + nav.getTarget().getId() + " translate relationshipName: " + relationshipName);
}
if (nav.getChildren() != null) {
LOG.debug("visiting children...");
for (RelationshipNavigationObject relationship : nav.getChildren()) {
listJSONTimelineModel = visitRelationshipsChain(relationship, relationshipName, listJSONTimelineModel,
sourceJsonTemplate);
}
}
return listJSONTimelineModel;
}
/**
* To timeline with image JSON model.
*
* @param theProject the the project
* @param sourceJsonTemplate the source json template
* @param targetUCD the target UCD
* @param targetID the target ID
* @param relationName the relation name
* @return the JSON object
*/
private JSONObject toTimelineWithImageJSONModel(Project theProject, JSONObject sourceJsonTemplate, String targetUCD,
String targetID, String relationName) {
JSONObject targetJsonObject = ConvertToDataValueObjectModel.toTimelineJSONModel(theProject, sourceJsonTemplate,
targetUCD, targetID, relationName);
List<PayloadDV> images = null;
try {
images = getImagesForId(theProject.getProfileID(), theProject.getId(), true);
} catch (Exception e) {
}
if (images != null && images.size() > 0) {
images.get(0).getLink();
targetJsonObject.put("image_url", images.get(0).getLink());
}
return targetJsonObject;
}
/**
* Temporal reference for project.
*
* @param theProject the the project
* @return the temporal reference DV
*/
private TemporalReferenceDV temporalReferenceForProject(Project theProject) {
LOG.trace("temporalReference for profileID: " + theProject.getProfileID() + ", projectID: "
+ theProject.getId() + "called");
String template = null;
try {
new GeoportalServiceIdentityProxy(this.getThreadLocalRequest());
template = SessionUtil.getJSONTimelineTemplate(this.getThreadLocalRequest(), theProject.getProfileID());
try {
if (template == null) {
Document temporalJsonTemplate = GeoportalClientCaller.useCaseDescriptors()
.readTemporalDimensionTemplate(theProject.getProfileID());
if (temporalJsonTemplate != null) {
template = new Document(temporalJsonTemplate).toJson();
LOG.info(UseCaseDescriptorCaller.TIMELINE_CONFIG_TJT_DOCUMENT + " read is: " + template);
SessionUtil.setJSONTimelineTemplate(this.getThreadLocalRequest(), theProject.getProfileID(),
template);
}
}
} catch (Exception e) {
LOG.warn(GEOPORTAL_DATA_HANDLER.geoportal_timeline_json_template.getType()
+ " not found!!! Timeline cannot be available");
}
// String template = "{\"content\": \"$.nome\"," + "\"title\": \"$.nome\","
// + "\"start\" : \"$.dataInizioProgetto\"," + "\"end\" : \"$.dataFineProgetto\"}";
if (template != null) {
JSONObject sourceJsonTemplate = new JSONObject(template);
JSONObject targetJsonObject = ConvertToDataValueObjectModel.toTimelineJSONModel(theProject,
sourceJsonTemplate, theProject.getProfileID(), theProject.getId(), null);
return ConvertToDataValueObjectModel.toTemporalReferenceDV(theProject, targetJsonObject);
}
} catch (Exception e) {
String erroMsg = "Error occurred on reading temporalReference for id: " + theProject.getId();
LOG.warn(erroMsg, e);
}
return null;
}
/**
* Gets the WFS request.
*
* @param layerItem the layer item
* @param mapSrsName the map srs name
* @param mapBBOX the map BBOX
* @param maxFeatures the max features. If 0 means all feature
* @param outputFormat the output format
* @return the WFS request
*/
@Override
public String getWFSRequest(LayerItem layerItem, String mapSrsName, BoundsMap mapBBOX, int maxFeatures,
String outputFormat) {
LOG.info("getWFSRequest called");
if (LOG.isDebugEnabled()) {
LOG.debug("getWFSRequest parameters layerItem name: " + layerItem.getName(), ", mapSrsName: " + mapSrsName
+ ", mapBBOX: " + mapBBOX + ", maxFeatures: " + maxFeatures + ", outputFormat: " + outputFormat);
}
String url = GisMakers.buildWFSFeatureQuery(layerItem, mapSrsName, mapBBOX, maxFeatures, outputFormat);
LOG.info("returning WFSRequest: " + url);
return url;
}
/**
* Gets the WFS response.
*
* @param layerItem the layer item
* @param mapSrsName the map srs name
* @param mapBBOX the map BBOX
* @param maxFeatures the max features
* @param outputFormat the output format
* @return the WFS response
*/
@Override
public String getWFSResponse(LayerItem layerItem, String mapSrsName, BoundsMap mapBBOX, int maxFeatures,
String outputFormat) {
LOG.info("getWFSResponse called");
if (LOG.isDebugEnabled()) {
LOG.debug("getWFSResponse parameters layerItem name: " + layerItem.getName(), ", mapSrsName: " + mapSrsName
+ ", mapBBOX: " + mapBBOX + ", maxFeatures: " + maxFeatures + ", outputFormat: " + outputFormat);
}
String url = getWFSRequest(layerItem, mapSrsName, mapBBOX, maxFeatures, outputFormat);
StringBuffer response = new StringBuffer();
String theResponseString = "";
HttpURLConnection con = null;
LOG.debug("Built URL: " + url);
try {
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
LOG.debug("GET Response Code: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
LOG.info("GET request did not work.");
}
theResponseString = response.toString();
//LOG.trace(theResponseString);
if (LOG.isDebugEnabled()) {
LOG.debug("getWFSResponse is empty? " + theResponseString.isEmpty());
}
} catch (Exception e) {
LOG.error("Error on performing the request to URL: " + url, e);
} finally {
}
return theResponseString;
}
}