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

282 lines
9.6 KiB
Java

package org.gcube.application.geoportalcommon.geoportal;
import static org.gcube.application.geoportal.client.plugins.GeoportalAbstractPlugin.projects;
import java.io.File;
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
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.configuration.Configuration;
import org.gcube.application.geoportal.common.model.document.Project;
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.model.rest.RegisterFileSetRequest;
import org.gcube.application.geoportal.common.rest.Projects;
import org.gcube.application.geoportal.common.utils.FileSets;
import org.gcube.application.geoportal.common.utils.StorageUtils;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
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.geoportal.ProjectDV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
public class ProjectsCaller {
private static Logger LOG = LoggerFactory.getLogger(GeoportalClientCaller.class);
public Projects<Project> getClient(String profileID) {
LOG.info("getProjectsClient called for profileID={}", profileID);
return projects(profileID).build();
}
public Project createNew(String profileID, String jsonDocument) throws RemoteException {
LOG.info("createNew called on profileID={}", profileID);
Document myDocument = Document.parse(jsonDocument);
Projects<Project> client = getClient(profileID);
Project project = client.createNew(myDocument);
return project;
}
public Project registerFileSet(String profileID, Project project, File theFile, String parentPath, String fieldName,
String fieldDefinition) throws RemoteException, FileNotFoundException, JsonProcessingException {
LOG.info(
"registerFileSet called with [profileID={}, projectID={}, theFile={}, parentPath={}, fieldName={}, fieldDefinition={}",
parentPath, project.getId(), theFile, parentPath, fieldName, fieldDefinition);
Projects<Project> client = getClient(profileID);
// Prepare request
RegisterFileSetRequest fsRequest = FileSets.prepareRequest(new StorageUtils(), parentPath, fieldName,
fieldDefinition, theFile);
project = client.registerFileSet(project.getId(), fsRequest);
LOG.trace("Resulting Project : " + project);
return project;
}
public List<Project> getListForProfileID(String profileID) throws Exception {
LOG.info("getlistOfProjectsForProfileID called for profileID: {}", profileID);
Projects<Project> client = (Projects<Project>) getClient(profileID);
List<Project> listProjects = new ArrayList<Project>();
Iterator<Project> projects = client.query(new QueryRequest());
for (Iterator<Project> iterator = projects; projects.hasNext();) {
Project prg = (Project) iterator.next();
listProjects.add(prg);
}
LOG.info("returning %d {}", listProjects.size(), Project.class.getName());
return listProjects;
}
public Configuration getConfiguration(String profileID) throws Exception {
LOG.info("getConfiguration called for profileID: {} ", profileID);
Projects<Project> client = (Projects<Project>) getClient(profileID);
Configuration config = client.getConfiguration();
LOG.debug("returning: {} ", config);
return config;
}
/**
* 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(String profileID, Integer totalItems, Integer offset, Integer limit,
SearchingFilter filter, String recordType, ProjectDVBuilder projectDVBuilder) throws Exception {
try {
Projects<Project> geoportalClient = getClient(profileID);
if (totalItems == null || totalItems < 0) {
// TODO MUST BE REPLACED BY COUNT
List<Project> listOfProjects = getListForProfileID(profileID);
int listConcessioniSize = listOfProjects.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<ProjectDV> toReturnList = new ArrayList<ProjectDV>();
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<Project> projects = geoportalClient.query(request);
int i = 0;
while (projects.hasNext()) {
Project project = projects.next();
ProjectDV projectDV = ConvertToDataValueObjectModel.toProjectDV(project, projectDVBuilder);
toReturnList.add(projectDV);
i++;
LOG.trace(i + ") converted: " + projectDV);
}
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());
}
}
}