tabular-data-gwt-service/src/main/java/org/gcube/portlets/user/td/gwtservice/server/TDGWTServiceImpl.java

1831 lines
60 KiB
Java

/**
*
*/
package org.gcube.portlets.user.td.gwtservice.server;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.common.homelibrary.home.Home;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.HomeManager;
import org.gcube.common.homelibrary.home.HomeManagerFactory;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.data.analysis.tabulardata.metadata.NoSuchMetadataException;
import org.gcube.data.analysis.tabulardata.model.column.Column;
import org.gcube.data.analysis.tabulardata.model.column.type.IdColumnType;
import org.gcube.data.analysis.tabulardata.model.metadata.common.DescriptionsMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.common.LocalizedText;
import org.gcube.data.analysis.tabulardata.model.metadata.common.NamesMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.table.ExportMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.table.GenericMapMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.table.ImportMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.table.TableMetadata;
import org.gcube.data.analysis.tabulardata.model.metadata.table.VersionMetadata;
import org.gcube.data.analysis.tabulardata.model.table.Table;
import org.gcube.data.analysis.tabulardata.model.table.TableId;
import org.gcube.data.analysis.tabulardata.operation.OperationDescriptor;
import org.gcube.data.analysis.tabulardata.operation.invocation.InvocationCreator;
import org.gcube.data.analysis.tabulardata.operation.invocation.OperationInvocation;
import org.gcube.data.analysis.tabulardata.service.TabularDataService;
import org.gcube.data.analysis.tabulardata.service.exception.InvalidTabularResourceException;
import org.gcube.data.analysis.tabulardata.service.exception.NoSuchTabularResourceException;
import org.gcube.data.analysis.tabulardata.service.impl.TabularDataServiceFactory;
import org.gcube.data.analysis.tabulardata.service.operation.OperationInterface;
import org.gcube.data.analysis.tabulardata.service.operation.Task;
import org.gcube.data.analysis.tabulardata.service.operation.TaskStatus;
import org.gcube.data.analysis.tabulardata.service.tabular.TabularResource;
import org.gcube.data.analysis.tabulardata.service.tabular.TabularResourceId;
import org.gcube.data.analysis.tabulardata.service.tabular.TabularResourceInterface;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.AgencyMetadata;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.CreationDateMetadata;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.DescriptionMetadata;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.NameMetadata;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.RightsMetadata;
import org.gcube.data.analysis.tabulardata.service.tabular.metadata.TabularResourceMetadata;
import org.gcube.datapublishing.sdmx.api.model.SDMXRegistryDescriptor;
import org.gcube.datapublishing.sdmx.api.model.SDMXRegistryInterfaceType;
import org.gcube.datapublishing.sdmx.impl.model.GCubeSDMXRegistryDescriptor;
import org.gcube.portlets.user.td.gwtservice.client.rpc.TDGWTService;
import org.gcube.portlets.user.td.gwtservice.server.file.FileUploadSession;
import org.gcube.portlets.user.td.gwtservice.server.file.FileUtil;
import org.gcube.portlets.user.td.gwtservice.server.storage.FilesStorage;
import org.gcube.portlets.user.td.gwtservice.server.trservice.OperationsId;
import org.gcube.portlets.user.td.gwtservice.shared.Constants;
import org.gcube.portlets.user.td.gwtservice.shared.csv.AvailableCharsetList;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVExportMonitor;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVExportSession;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVFileUtil;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVImportMonitor;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVImportSession;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVParserConfiguration;
import org.gcube.portlets.user.td.gwtservice.shared.csv.CSVRowError;
import org.gcube.portlets.user.td.gwtservice.shared.exception.TDGWTServiceException;
import org.gcube.portlets.user.td.gwtservice.shared.file.FileUploadMonitor;
import org.gcube.portlets.user.td.gwtservice.shared.file.FileUploadState;
import org.gcube.portlets.user.td.gwtservice.shared.file.HeaderPresence;
import org.gcube.portlets.user.td.gwtservice.shared.sdmx.SDMXExportMonitor;
import org.gcube.portlets.user.td.gwtservice.shared.sdmx.SDMXExportSession;
import org.gcube.portlets.user.td.gwtservice.shared.sdmx.SDMXImportMonitor;
import org.gcube.portlets.user.td.gwtservice.shared.sdmx.SDMXImportSession;
import org.gcube.portlets.user.td.gwtservice.shared.source.SDMXRegistrySource;
import org.gcube.portlets.user.td.gwtservice.shared.task.State;
import org.gcube.portlets.user.td.gwtservice.shared.tr.ColumnData;
import org.gcube.portlets.user.td.gwtservice.shared.tr.TabResource;
import org.gcube.portlets.user.td.gwtservice.shared.tr.TableData;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRAgencyMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRCreationDateMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRDescriptionMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRLocalizedText;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRNameMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.metadata.TRRightsMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.open.TDOpenSession;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabDescriptionsMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabExportMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabGenericMapMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabImportMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabNamesMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.table.metadata.TabVersionMetadata;
import org.gcube.portlets.user.td.gwtservice.shared.tr.type.Agencies;
import org.gcube.portlets.user.td.gwtservice.shared.tr.type.Codelist;
import org.gcube.portlets.user.td.gwtservice.shared.tr.type.Dataset;
import org.gcube.portlets.user.td.widgetcommonevent.shared.TRId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
*
* @author "Giancarlo Panichi" <a
* href="mailto:g.panichi@isti.cnr.it">g.panichi@isti.cnr.it</a>
*
*/
public class TDGWTServiceImpl extends RemoteServiceServlet implements TDGWTService {
private static final long serialVersionUID = -5707400086333186368L;
protected static Logger logger = LoggerFactory.getLogger(TDGWTServiceImpl.class);
protected static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
/**
*
* {@inheritDoc}
*/
public void setTabResource(TabResource tabResource) throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
if (tabResource == null) {
logger.error("Error setting TabResource: null");
throw new TDGWTServiceException(
"Error setting TabResource: null");
}
SessionUtil.setTabResource(session, tabResource);
SessionUtil.setTRId(session, tabResource.getTrId());
return;
} catch (Exception e) {
logger.error(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public TabResource getTabResourceInformation() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
//ASLSession aslSession = SessionUtil.getAslSession(session);
TabResource currentTR = SessionUtil.getTabResource(session);
if (currentTR == null) {
logger.error("CURRENT_TABULAR_RESOURCE is null");
throw new TDGWTServiceException(
"CURRENT_TABULAR_RESOURCE is null");
}
ArrayList<TRMetadata> trMetadatas = getTRMetadata(currentTR.getTrId());
updateTabResourceInformation(currentTR, trMetadatas);
SessionUtil.setTabResource(session, currentTR);
return currentTR;
} catch (Exception e) {
logger.error("Error setting TabResource parameter: "+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException("Error setting TabResource parameter: "+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public TabResource getTabResourceInformation(TRId trId)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
//ASLSession aslSession = SessionUtil.getAslSession(session);
TabResource currentTR = new TabResource();
currentTR.setTrId(trId);
ArrayList<TRMetadata> trMetadatas = getTRMetadata(currentTR
.getTrId());
updateTabResourceInformation(currentTR, trMetadatas);
SessionUtil.setTabResource(session, currentTR);
return currentTR;
} catch (Exception e) {
logger.error(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage());
}
}
protected void updateTabResourceInformation(TabResource tabResource,
ArrayList<TRMetadata> trMetadatas) {
for (TRMetadata trMetadata : trMetadatas) {
if (trMetadata instanceof TRDescriptionMetadata) {
tabResource.setDescription(((TRDescriptionMetadata) trMetadata)
.getValue());
} else {
if (trMetadata instanceof TRNameMetadata) {
tabResource.setName(((TRNameMetadata) trMetadata)
.getValue());
} else {
if (trMetadata instanceof TRAgencyMetadata) {
tabResource.setAgency(((TRAgencyMetadata) trMetadata)
.getValue());
} else {
if (trMetadata instanceof TRCreationDateMetadata) {
tabResource
.setDate(((TRCreationDateMetadata) trMetadata)
.getDate());
} else {
if (trMetadata instanceof TRRightsMetadata) {
tabResource
.setRight(((TRRightsMetadata) trMetadata)
.getValue());
} else {
}
}
}
}
}
}
}
/**
*
* {@inheritDoc}
*/
public ArrayList<ColumnData> getColumns() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
TabResource currentTR = SessionUtil.getTabResource(session);
if (currentTR == null) {
logger.error("CURRENT_TABULAR_RESOURCE is null");
throw new TDGWTServiceException(
"CURRENT_TABULAR_RESOURCE is null");
}
TRId trId = currentTR.getTrId();
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
Table table = service.getLastTable(new TabularResourceId(Long
.valueOf(trId.getId())));
ArrayList<ColumnData> columns = new ArrayList<ColumnData>();
List<Column> cols = table.getColumns();
int i = 0;
for (Column c : cols) {
if (c.getColumnType() instanceof IdColumnType) {
} else {
ColumnData cData = new ColumnData();
cData.setId(Integer.toString(i));
cData.setName(c.getName());
cData.setTypeCode(c.getColumnType().getCode());
cData.setTypeName(c.getColumnType().getName());
NamesMetadata labelsMetadata = null;
try {
labelsMetadata = c.getMetadata(NamesMetadata.class);
} catch (NoSuchMetadataException e) {
logger.debug("labelMetadata: NoSuchMetadataException "
+ e.getLocalizedMessage());
}
if (labelsMetadata == null) {
cData.setLabel("nolabel");
logger.debug("LabelsMetadata no labels");
} else {
LocalizedText cl = null;
cl = labelsMetadata.getTextWithLocale("en");
if (cl == null) {
cData.setLabel("nolabel");
logger.debug("ColumnLabel no label in en");
} else {
cData.setLabel(cl.getValue());
logger.debug("Column Set Label: " + cl.getValue());
}
}
cData.setTrId(trId);
columns.add(cData);
i++;
}
}
return columns;
} catch (Exception e) {
logger.error(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error setting TabResource parameter: "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public TableData getLastTable(TRId trId) throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
Table table = service.getLastTable(new TabularResourceId(Long
.valueOf(trId.getId())));
TableData tData = new TableData();
trId.setTableId(String.valueOf(table.getId().getValue()));
tData.setTrId(trId);
tData.setName(table.getName());
tData.setTypeName(table.getTableType().getName());
tData.setTypeCode(table.getTableType().getCode());
Collection<TableMetadata> cMeta = table.getAllMetadata();
tData.setMetaData(cMeta.toString());
ArrayList<ColumnData> lColumnData = new ArrayList<ColumnData>();
for (Column column : table.getColumns()) {
ColumnData colData = new ColumnData();
colData.setName(column.getName());
colData.setTypeName(column.getColumnType().getName());
colData.setTypeCode(column.getColumnType().getCode());
lColumnData.add(colData);
}
tData.setListColumnData(lColumnData);
return tData;
} catch (Exception e) {
logger.error("Error in getLastTable(): " + e.getLocalizedMessage(),
e);
throw new TDGWTServiceException("Error in getLastTable(): "
+ e.getLocalizedMessage());
}
}
/**
* Not used now, but it will be necessary in the future to retrieve task pending
*
* {@inheritDoc}
*/
public void startTDOpen(TDOpenSession s) throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
SessionUtil.setTDOpenSession(session, s);
return;
} catch (Exception e) {
logger.error("Error setting TDOpenSession parameter: "
+ e.getLocalizedMessage());
throw new TDGWTServiceException(
"Error setting TDOpenSession parameter: "
+ e.getLocalizedMessage());
}
}
/**
*
*
* @param tr
* @param tabResource
*/
protected void syncTRMetaData(TabularResource tr, TabResource tabResource) {
Date date = Calendar.getInstance().getTime();
tabResource.setDate(sdf.format(date));
tr.setMetadata(new NameMetadata(tabResource.getName()));
tr.setMetadata(new DescriptionMetadata(tabResource.getDescription()));
tr.setMetadata(new CreationDateMetadata(date));
if (tabResource.getAgency() != null
&& !tabResource.getAgency().isEmpty()) {
tr.setMetadata(new AgencyMetadata(tabResource.getAgency()));
}
tr.setMetadata(new RightsMetadata(tabResource.getRight()));
}
/**
*
* @param tr
* @throws TDGWTServiceException
*/
protected void retriveTRMetadataFromService(TabularDataService service,TabularResource tr)
throws TDGWTServiceException {
retriveTRMetadataFromService(service,tr, 0);
}
/**
* Retrieves the informations for a specific Tabular Resource from service
*
* @param tr
* TabularResource on service
* @param i
* Index on Grid
* @return TabResource for Grid
* @throws TDGWTServiceException
*/
protected TabResource retriveTRMetadataFromService(TabularDataService service,
TabularResource tr, int i)
throws TDGWTServiceException {
Table table = null;
try {
table = service.getLastTable(tr.getId());
} catch (NoSuchTabularResourceException e) {
e.printStackTrace();
} catch (InvalidTabularResourceException e) {
e.printStackTrace();
}
TableId tableId = null;
if (table == null) {
logger.info("Tabular resource " + tr.getId() + " has no table.");
} else {
tableId = table.getId();
}
TRId trId;
TabResource t;
if (tableId == null) {
logger.info("Tabular Resource " + tr.getId()
+ " has last table with id null.");
t=new TabResource();
t.setTrId(null);
} else {
trId = new TRId(String.valueOf(tr.getId().getValue()),
String.valueOf(tableId.getValue()),table.getTableType().getName());
t=getTabResourceInformation(trId);
}
t.setId(String.valueOf(i));
return t;
}
/**
*
* {@inheritDoc}
*/
public ArrayList<TabResource> getTabularResources()
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
List<TabularResource> trs = service.getTabularResources();
SessionUtil.setTabularResources(session, trs);
ArrayList<TabResource> ltr = new ArrayList<TabResource>();
int i;
for (i = 0; i < trs.size(); i++) {
TabularResource tr = trs.get(i);
TabResource t = retriveTRMetadataFromService(service, tr, i);
if (t.getTrId() != null) {
ltr.add(t);
}
}
logger.debug("Tabular Resources retrived: " + ltr);
return ltr;
} catch (Exception e) {
e.printStackTrace();
logger.error("Error retrieving TabularResources: "
+ e.getLocalizedMessage());
throw new TDGWTServiceException(
"Error retrieving TabularResources: "
+ e.getLocalizedMessage());
}
}
/**
*
* @param tabResource
* @throws TDGWTServiceException
*/
public void removeTabularResource(TRId trId) throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
if (trId == null) {
logger.error("Error removing TabularResource: trId is null");
throw new TDGWTServiceException(
"Error removing TabularResource no parameters set");
}
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
TabularResourceId id = new TabularResourceId(Long.valueOf(trId
.getId()));
service.removeTabularResource(id);
return;
} catch (Exception e) {
logger.error(
"Error removing TabularResource: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException("Error removing TabularResource: "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public TabResource createTabularResource(TabResource tabResource)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
if (tabResource == null) {
logger.error("Error creating new TabularResource: tabResource is null");
throw new TDGWTServiceException(
"Error creating new TabularResource no parameters set");
}
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
TabularResource serviceTR = service.createTabularResource();
Table table = service.getLastTable(serviceTR.getId());
syncTRMetaData(serviceTR, tabResource);
TRId trId = new TRId(String.valueOf(serviceTR.getId().getValue()),
String.valueOf(table.getId().getValue()),
table.getTableType().getName());
tabResource.setTrId(trId);
return tabResource;
} catch (Exception e) {
logger.error(
"Error creating new TabularResource: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error creating new TabularResource: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public ArrayList<Codelist> getCodelists() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
return SessionUtil.retrieveCodelists(session);
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException("Error retrieving codelists: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public ArrayList<Dataset> getDatasets() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
return SessionUtil.retrieveDatasets(session);
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException("Error retrieving datasets: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public ArrayList<Agencies> getAgencies() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
return SessionUtil.retrieveAgencies(session);
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException("Error retrieving datasets: "
+ e.getLocalizedMessage());
}
}
/**
*
* @param sdmxImportSession
* @return
*/
protected Map<String, Object> retrieveOperationParameters(
SDMXImportSession sdmxImportSession) {
Map<String, Object> map = new HashMap<String, Object>();
Codelist codelist = sdmxImportSession.getSelectedCodelist();
map.put(Constants.PARAMETER_AGENCY, codelist.getAgencyId());
map.put(Constants.PARAMETER_ID, codelist.getId());
map.put(Constants.PARAMETER_VERSION, codelist.getVersion());
// TODO-GP: Get registry url from client
SDMXRegistryDescriptor descriptor = new GCubeSDMXRegistryDescriptor();
map.put(Constants.PARAMETER_REGISTRYBASEURL,
descriptor.getUrl(SDMXRegistryInterfaceType.RESTV2_1));
return map;
}
/**
* {@inheritDoc}
*/
public void startSDMXImport(SDMXImportSession sdmxImportSession)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
SessionUtil.setSDMXImportSession(session, sdmxImportSession);
ASLSession aslSession = SessionUtil.getAslSession(session);
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
OperationInterface oService = service;
TabularResourceInterface trService = service;
List<OperationDescriptor> capabilities = service.getCapabilities();
// Import SDMX Codelist takes id 200
OperationDescriptor importSDMXCodelistOperation = getOperationDescriptorWithId(
OperationsId.SDMXCodelistImport.toString(), capabilities);
TabResource importSDMXTabResource = sdmxImportSession
.getTabResource();
TabularResource serviceTR = trService.createTabularResource();
syncTRMetaData(serviceTR, importSDMXTabResource);
TRId trId = new TRId(String.valueOf(serviceTR.getId().getValue()));
importSDMXTabResource.setTrId(trId);
SessionUtil
.setSDMXImportTabResource(session, importSDMXTabResource);
Map<String, Object> parameterInstance = retrieveOperationParameters(sdmxImportSession);
InvocationCreator ic = InvocationCreator
.getCreator(importSDMXCodelistOperation);
OperationInvocation invocation = ic
.setParameters(parameterInstance).create();
logger.debug("OperationInvocation: \n" + invocation.toString());
Task trTask = oService.execute(invocation, serviceTR.getId());
logger.debug("Start Task on service: TaskId " + trTask.getId());
SessionUtil.setSDMXImportTask(session, trTask);
return;
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException("Error in Client Library Request: "
+ e.getLocalizedMessage());
}
}
/**
*
* @param op
* @param capabilities
* @return
* @throws TDGWTServiceException
*/
protected OperationDescriptor getOperationDescriptorWithId(String op,
List<OperationDescriptor> capabilities)
throws TDGWTServiceException {
for (OperationDescriptor operation : capabilities) {
if (Long.valueOf(op) == operation.getOperationId().getValue()) {
return operation;
}
}
throw new TDGWTServiceException("OperationDescriptor not found");
}
protected State matchTaskState(TaskStatus status) {
switch (status) {
case INITIALIZING:
return State.INITIALIZING;
case FAILED:
return State.FAILED;
case ABORTED:
return State.ABORTED;
case IN_PROGRESS:
return State.IN_PROGRESS;
case SUCCEDED:
return State.SUCCEDED;
case FALLBACK:
return State.FAILED;
default:
return State.FAILED;
}
}
/**
* {@inheritDoc}
*/
public SDMXImportMonitor getSDMXImportMonitor()
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
//ASLSession aslSession = SessionUtil.getAslSession(session);
Task task = SessionUtil.getSDMXImportTask(session);
TabResource sdmxImportTabResource = SessionUtil
.getSDMXImportTabResource(session);
TRId trId = sdmxImportTabResource.getTrId();
SDMXImportMonitor importMonitor = new SDMXImportMonitor();
if (trId == null) {
throw new TDGWTServiceException(
"Error in importSDMX TabularResource Id null");
} else {
if (task == null) {
throw new TDGWTServiceException(
"Error in importSDMX task null");
} else {
logger.debug("Service task: " + task.toString());
TaskStatus status = task.getStatus();
if (status == null) {
throw new TDGWTServiceException(
"Error in importSDMX Status null");
} else {
logger.debug("Service Task.getStatus(): "
+ task.getStatus());
importMonitor
.setStatus(matchTaskState(task.getStatus()));
switch (importMonitor.getStatus()) {
case SUCCEDED:
importMonitor.setProgress(task.getProgress());
logger.debug("Task Result: " + task.getResult());
Table table=task.getResult().getPrimaryTable();
trId.setTableId(String.valueOf(table.getId().getValue()));
trId.setTableType(table.getTableType().getName());
sdmxImportTabResource.setTrId(trId);
SessionUtil.setSDMXImportTabResource(session,
sdmxImportTabResource);
SessionUtil.setTabResource(session,
sdmxImportTabResource);
SessionUtil.setTRId(session, trId);
break;
case FAILED:
if (task.getResult() != null) {
logger.debug("Task exception:"
+ task.getErrorCause());
importMonitor.setError(task.getErrorCause());
} else {
logger.debug("Task exception: Error In Import");
importMonitor.setError(new Throwable(
"Error In Import"));
}
importMonitor.setProgress(task.getProgress());
break;
case ABORTED:
break;
case WAITING:
break;
case IN_PROGRESS:
importMonitor.setProgress(task.getProgress());
break;
case INITIALIZING:
break;
default:
break;
}
}
SessionUtil.setSDMXImportTask(session, task);
}
importMonitor.setTrId(trId);
}
logger.debug("getSDMXImportMonitor(): " + importMonitor);
return importMonitor;
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Error in importSDMX ImportMonitor: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public void setSDMXRegistrySource(SDMXRegistrySource sdmxRegistrySource)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
SessionUtil.setSDMXRegistrySource(session, sdmxRegistrySource);
return;
} catch (Exception e) {
logger.error(
"Error setting SDMXRegistrySource parameter: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error setting SDMXRegistrySource parameter: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public void setCSVSession(CSVImportSession importSession)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
SessionUtil.setCSVImportSession(session, importSession);
return;
} catch (Exception e) {
logger.error(
"Error setting SDMXImportSession parameter: "
+ e.getLocalizedMessage(), e);
throw new TDGWTServiceException(
"Error setting SDMXImportSession parameter: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public FileUploadMonitor getFileUploadMonitor()
throws TDGWTServiceException {
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
FileUploadSession fileUploadSession = SessionUtil
.getFileUploadSession(session);
if (fileUploadSession == null) {
throw new TDGWTServiceException(
"Error retrieving the fileUploadSession: null");
}
return fileUploadSession.getFileUploadMonitor();
}
/**
* {@inheritDoc}
*/
public AvailableCharsetList getAvailableCharset()
throws TDGWTServiceException {
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
String defaultEncoding = Charset.defaultCharset().displayName();
ArrayList<String> charsetList = new ArrayList<String>(Charset
.availableCharsets().keySet());
return new AvailableCharsetList(charsetList, defaultEncoding);
}
public ArrayList<String> configureCSVParser(String encoding,
HeaderPresence headerPresence, char delimiter, char comment)
throws TDGWTServiceException {
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
logger.info("configureCSVParser encoding: " + encoding
+ " headerPresence: " + headerPresence + " delimiter: "
+ delimiter + " comment: " + comment);
FileUploadSession fileUploadSession = SessionUtil
.getFileUploadSession(session);
if (fileUploadSession == null) {
throw new TDGWTServiceException(
"Error retrieving the fileUploadSession: null");
}
CSVParserConfiguration parserConfiguration = fileUploadSession
.getParserConfiguration();
if (parserConfiguration == null) {
parserConfiguration = new CSVParserConfiguration(
Charset.forName(encoding), delimiter, comment,
headerPresence);
fileUploadSession.setParserConfiguration(parserConfiguration);
} else {
parserConfiguration.update(encoding, delimiter, comment,
headerPresence);
}
SessionUtil.setFileUploadSession(session, fileUploadSession);
try {
return CSVFileUtil.getHeader(fileUploadSession.getCsvFile(),
fileUploadSession.getParserConfiguration());
} catch (Exception e) {
logger.error("Error retrieving the CSV header", e);
throw new TDGWTServiceException(
"Error calculating the CSV header: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public ArrayList<CSVRowError> checkCSV(long errorsLimit)
throws TDGWTServiceException {
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
FileUploadSession fileUploadSession = SessionUtil
.getFileUploadSession(session);
if (fileUploadSession == null) {
throw new TDGWTServiceException(
"Error retrieving the fileUploadSession: null");
}
try {
return CSVFileUtil.checkCSV(fileUploadSession.getCsvFile(),
fileUploadSession.getParserConfiguration(), errorsLimit);
} catch (Exception e) {
logger.error("Error checking the CSV file", e);
throw new TDGWTServiceException("Error checking the CSV file: "
+ e.getLocalizedMessage());
}
}
/**
* {@inheritDoc}
*/
public void startCSVImport(CSVImportSession csvImportSession)
throws TDGWTServiceException {
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
ASLSession aslSession = SessionUtil.getAslSession(session);
if (aslSession == null) {
throw new TDGWTServiceException(
"Error retrieving the asl session: null");
}
String user = aslSession.getUsername();
logger.info("Session User:" + user);
FileUploadSession fileUploadSession = SessionUtil
.getFileUploadSession(session);
if (fileUploadSession == null) {
throw new TDGWTServiceException(
"Error retrieving the fileUploadSession: null");
}
importCSVFileOnService(session,aslSession,user, fileUploadSession, csvImportSession);
}
/**
*
* @param fileUrlOnStorage
* @param fileUploadSession
* @param csvImportSession
* @return
*/
protected Map<String, Object> csvImportFileParameter(
String fileUrlOnStorage, FileUploadSession fileUploadSession,
CSVImportSession csvImportSession) {
Map<String, Object> parameterInstances = new HashMap<String, Object>();
parameterInstances.put(Constants.PARAMETER_URL, fileUrlOnStorage);
parameterInstances.put(Constants.PARAMETER_SEPARATOR, String
.valueOf(fileUploadSession.getParserConfiguration()
.getDelimiter()));// ','
parameterInstances.put(Constants.PARAMETER_ENCODING, fileUploadSession
.getParserConfiguration().getCharset().name());// "UTF-8"
boolean hasHeader = true;
if (fileUploadSession.getParserConfiguration().getHeaderPresence() == HeaderPresence.NONE) {
hasHeader = false;
}
parameterInstances.put(Constants.PARAMETER_HASHEADER, hasHeader);// true
return parameterInstances;
}
/**
*
* @param user
* @param fileUploadSession
* @param csvImportSession
* @throws TDGWTServiceException
*/
protected void importCSVFileOnService(HttpSession session,ASLSession aslSession,String user,
FileUploadSession fileUploadSession,
CSVImportSession csvImportSession) throws TDGWTServiceException {
logger.debug("File Storage Access");
FilesStorage filesStorage = new FilesStorage();
String fileUrlOnStorage = filesStorage.storageCSVTempFile(user,
fileUploadSession.getCsvFile());
logger.debug("File Url On Storage:" + fileUrlOnStorage);
Map<String, Object> parameterInstance = csvImportFileParameter(
fileUrlOnStorage, fileUploadSession, csvImportSession);
logger.debug("Tabular Data Service");
TabularDataService service = TabularDataServiceFactory
.getService(aslSession.getUsername());
List<OperationDescriptor> capabilities = service.getCapabilities();
// Import CSV file
OperationDescriptor importCSVFileOperation = getOperationDescriptorWithId(
OperationsId.CSVImport.toString(), capabilities);
InvocationCreator ic = InvocationCreator
.getCreator(importCSVFileOperation);
OperationInvocation invocation = ic.setParameters(parameterInstance)
.create();
logger.debug("OperationInvocation: \n" + invocation.toString());
TabularResource tabularResource = service.createTabularResource();
TabResource csvImportTabResource = csvImportSession.getTabResource();
syncTRMetaData(tabularResource, csvImportTabResource);
TRId trId = new TRId(String.valueOf(tabularResource.getId().getValue()));
csvImportTabResource.setTrId(trId);
SessionUtil.setCSVImportTabResource(session, csvImportTabResource);
Task trTask;
try {
trTask = service.execute(invocation, tabularResource.getId());
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Tabular Data Service error creating TabularResource: "
+ e.getLocalizedMessage());
}
logger.debug("Start Task on service: TaskId " + trTask.getId());
SessionUtil.setCSVImportFileTask(session, trTask);
}
/**
* {@inheritDoc}
*/
public CSVImportMonitor getCSVImportMonitor() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
//ASLSession aslSession = SessionUtil.getAslSession(session);
Task task = SessionUtil.getCSVImportFileTask(session);
TabResource csvImportTabResource = SessionUtil
.getCSVImportTabResource(session);
TRId trId = csvImportTabResource.getTrId();
CSVImportMonitor importMonitor = new CSVImportMonitor();
if (trId == null) {
throw new TDGWTServiceException(
"Error in importCSV TabularResource Id null");
} else {
if (task == null) {
logger.debug("Task null");
throw new TDGWTServiceException(
"Error in importCSV task null");
} else {
TaskStatus status = task.getStatus();
if (status == null) {
throw new TDGWTServiceException(
"Error in importCSV Status null");
} else {
logger.debug("Status: " + task.getStatus());
importMonitor
.setStatus(matchTaskState(task.getStatus()));
switch (importMonitor.getStatus()) {
case FAILED:
if (task.getResult() != null) {
logger.debug("Task exception:"
+ task.getErrorCause());
importMonitor.setError(task.getErrorCause());
} else {
logger.debug("Task exception: Error In Import");
importMonitor.setError(new Throwable(
"Error In Import"));
}
importMonitor.setProgress(task.getProgress());
break;
case SUCCEDED:
logger.debug("Task Result: " + task.getResult());
importMonitor.setProgress(task.getProgress());
Table table = task.getResult().getPrimaryTable();
logger.debug("Table retrived: " + table.toString());
trId.setTableId(String.valueOf(table.getId()
.getValue()));
trId.setTableType(table.getTableType().getName());
csvImportTabResource.setTrId(trId);
SessionUtil.setCSVImportTabResource(session,
csvImportTabResource);
SessionUtil.setTabResource(session,
csvImportTabResource);
SessionUtil.setTRId(session, trId);
break;
case IN_PROGRESS:
importMonitor.setProgress(task.getProgress());
break;
case ABORTED:
break;
case INITIALIZING:
break;
case WAITING:
break;
default:
break;
}
}
SessionUtil.setCSVImportFileTask(session, task);
}
importMonitor.setTrId(trId);
}
logger.info("getImportMonitor(): " + importMonitor);
return importMonitor;
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Error in importCSV CSVImportMonitor: "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public void getFileFromWorkspace(CSVImportSession csvImportSession)
throws TDGWTServiceException {
// TODO Auto-generated method stub
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
Workspace w = null;
WorkspaceItem wi = null;
try {
HomeManagerFactory factory = HomeLibrary.getHomeManagerFactory();
HomeManager manager = factory.getHomeManager();
Home home = manager.getHome(aslSession.getUsername());
w = home.getWorkspace();
wi = w.getItem(csvImportSession.getItemId());
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Error in importCSV getFileFromWorkspace accessing the workspace: "
+ e.getLocalizedMessage(), e);
}
if (wi == null) {
logger.error("Error retrieving the item on workspace"
+ csvImportSession.getItemId());
throw new TDGWTServiceException(
"Error retrieving the item on workspace"
+ csvImportSession.getItemId());
}
try {
logger.debug("WorkspaceItem [id:" + wi.getId() + " name:"
+ wi.getName() + " remotePath:" + wi.getRemotePath() + "]");
} catch (InternalErrorException e1) {
e1.printStackTrace();
throw new TDGWTServiceException(
"Error retrieving the item on workspace" + wi);
}
FileUploadSession fileUploadSession = new FileUploadSession();
CSVImportMonitor csvImportMonitor = new CSVImportMonitor();
FileUploadMonitor fileUploadMonitor = new FileUploadMonitor();
fileUploadSession.setId(session.getId());
fileUploadSession.setFileUploadState(FileUploadState.STARTED);
fileUploadSession.setCsvImportMonitor(csvImportMonitor);
fileUploadSession.setFileUploadMonitor(fileUploadMonitor);
SessionUtil.setFileUploadSession(session, fileUploadSession);
try {
FilesStorage filesStorage = new FilesStorage();
InputStream is = filesStorage.retriveImputStream(
aslSession.getUsername(), wi);
FileUtil.setImportFile(fileUploadSession, is, wi.getName(),
"text/csv");
} catch (Exception e) {
fileUploadSession.getFileUploadMonitor().setFailed(
"An error occured elaborating the file",
FileUtil.exceptionDetailMessage(e));
fileUploadSession.setFileUploadState(FileUploadState.FAILED);
SessionUtil.setFileUploadSession(session, fileUploadSession);
logger.error("Error elaborating the imput stream", e);
throw new TDGWTServiceException(
"Error in importCSV getFileFromWorkspace: "
+ e.getLocalizedMessage(), e);
}
logger.trace("changing state");
fileUploadSession.getFileUploadMonitor().setState(
FileUploadState.COMPLETED);
SessionUtil.setFileUploadSession(session, fileUploadSession);
}
/**
*
* {@inheritDoc}
*/
public ArrayList<TRMetadata> getTRMetadata(TRId trId)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
TabularResource tr = service
.getTabularResource(new TabularResourceId(Long.valueOf(trId
.getId())));
Collection<TabularResourceMetadata> trMetas = tr.getAllMetadata();
ArrayList<TRMetadata> listTRMetadata = new ArrayList<TRMetadata>();
for (TabularResourceMetadata trMetadata : trMetas) {
if (trMetadata instanceof org.gcube.data.analysis.tabulardata.service.tabular.metadata.DescriptionMetadata) {
TRDescriptionMetadata trDescriptionMetadata = new TRDescriptionMetadata();
trDescriptionMetadata
.setValue(((org.gcube.data.analysis.tabulardata.service.tabular.metadata.DescriptionMetadata) trMetadata)
.getValue());
listTRMetadata.add(trDescriptionMetadata);
} else {
if (trMetadata instanceof org.gcube.data.analysis.tabulardata.service.tabular.metadata.NameMetadata) {
TRNameMetadata trNameMetadata = new TRNameMetadata();
trNameMetadata
.setValue(((org.gcube.data.analysis.tabulardata.service.tabular.metadata.NameMetadata) trMetadata)
.getValue());
listTRMetadata.add(trNameMetadata);
} else {
if (trMetadata instanceof AgencyMetadata) {
TRAgencyMetadata trAgencyMetadata = new TRAgencyMetadata();
trAgencyMetadata
.setValue(((AgencyMetadata) trMetadata)
.getValue());
listTRMetadata.add(trAgencyMetadata);
} else {
if (trMetadata instanceof CreationDateMetadata) {
TRCreationDateMetadata trCreationDateMetadata = new TRCreationDateMetadata();
trCreationDateMetadata
.setDate(sdf
.format(((CreationDateMetadata) trMetadata)
.getValue()));
listTRMetadata.add(trCreationDateMetadata);
} else {
if (trMetadata instanceof RightsMetadata) {
TRRightsMetadata trRightsMetadata = new TRRightsMetadata();
trRightsMetadata
.setValue(((RightsMetadata) trMetadata)
.getValue());
listTRMetadata.add(trRightsMetadata);
} else {
}
}
}
}
}
}
return listTRMetadata;
} catch (Exception e) {
logger.error(
"Error in getTRMetadata(): " + e.getLocalizedMessage(), e);
throw new TDGWTServiceException("Error in getTableMetadata(): "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public ArrayList<TabMetadata> getTableMetadata(TRId trId)
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
TabularDataService service = TabularDataServiceFactory.getService(aslSession
.getUsername());
Table table = service.getTable(new TableId(Long.valueOf(trId
.getTableId())));
Collection<TableMetadata> cMeta = table.getAllMetadata();
ArrayList<TabMetadata> listTabMetadata = new ArrayList<TabMetadata>();
for (TableMetadata tMetadata : cMeta) {
if (tMetadata instanceof DescriptionsMetadata) {
TabDescriptionsMetadata trDescriptionsMetadata = new TabDescriptionsMetadata();
ArrayList<TRLocalizedText> listTRLocalizedText = new ArrayList<TRLocalizedText>();
List<LocalizedText> lLocalizedText = ((DescriptionsMetadata) tMetadata)
.getTexts();
int i = 0;
for (LocalizedText lt : lLocalizedText) {
TRLocalizedText trLocalizedText = new TRLocalizedText();
trLocalizedText.setId(i);
trLocalizedText.setValue(lt.getValue());
trLocalizedText.setLocaleCode(lt.getLocale());
listTRLocalizedText.add(trLocalizedText);
i++;
}
trDescriptionsMetadata
.setListTRLocalizedText(listTRLocalizedText);
listTabMetadata.add(trDescriptionsMetadata);
} else {
if (tMetadata instanceof NamesMetadata) {
TabNamesMetadata trNamesMetadata = new TabNamesMetadata();
ArrayList<TRLocalizedText> listTRLocalizedText = new ArrayList<TRLocalizedText>();
List<LocalizedText> lLocalizedText = ((NamesMetadata) tMetadata)
.getTexts();
int i = 0;
for (LocalizedText lt : lLocalizedText) {
TRLocalizedText trLocalizedText = new TRLocalizedText();
trLocalizedText.setId(i);
trLocalizedText.setValue(lt.getValue());
trLocalizedText.setLocaleCode(lt.getLocale());
listTRLocalizedText.add(trLocalizedText);
i++;
}
trNamesMetadata
.setListTRLocalizedText(listTRLocalizedText);
listTabMetadata.add(trNamesMetadata);
} else {
if (tMetadata instanceof VersionMetadata) {
TabVersionMetadata trVersionMetadata = new TabVersionMetadata();
trVersionMetadata
.setVersion(((VersionMetadata) tMetadata)
.getVersion());
listTabMetadata.add(trVersionMetadata);
} else {
if (tMetadata instanceof ExportMetadata) {
TabExportMetadata trExportMetadata = new TabExportMetadata();
trExportMetadata
.setDestinationType(((ExportMetadata) tMetadata)
.getDestinationType());
trExportMetadata.setExportDate(sdf
.format(((ExportMetadata) tMetadata)
.getExportDate()));
trExportMetadata
.setUrl(((ExportMetadata) tMetadata)
.getUri());
listTabMetadata.add(trExportMetadata);
} else {
if (tMetadata instanceof ImportMetadata) {
TabImportMetadata trImportMetadata = new TabImportMetadata();
trImportMetadata
.setSourceType(((ImportMetadata) tMetadata)
.getSourceType());
trImportMetadata
.setImportDate(sdf
.format(((ImportMetadata) tMetadata)
.getImportDate()));
trImportMetadata
.setUrl(((ImportMetadata) tMetadata)
.getUri());
listTabMetadata.add(trImportMetadata);
} else {
if (tMetadata instanceof GenericMapMetadata) {
TabGenericMapMetadata trGenericMapMetadata = new TabGenericMapMetadata();
trGenericMapMetadata
.setMetadataMap(((GenericMapMetadata) tMetadata)
.getMetadataMap());
listTabMetadata
.add(trGenericMapMetadata);
} else {
}
}
}
}
}
}
}
return listTabMetadata;
} catch (Exception e) {
logger.error(
"Error in getTableMetadata(): " + e.getLocalizedMessage(),
e);
throw new TDGWTServiceException("Error in getTableMetadata(): "
+ e.getLocalizedMessage());
}
}
/**
*
* @param exportSession
* @return
*/
protected Map<String, Object> csvExportFileParameter(
CSVExportSession exportSession) {
Map<String, Object> parameterInstances = new HashMap<String, Object>();
parameterInstances.put(Constants.PARAMETER_ENCODING,
exportSession.getEncoding());
parameterInstances.put(Constants.PARAMETER_SEPARATOR,
exportSession.getSeparator());
parameterInstances.put(Constants.PARAMETER_COLUMNS,
exportSession.getColumnsAsArrayOfString());
return parameterInstances;
}
/**
*
* @param exportSession
* @return
*/
protected Map<String, Object> sdmxExportParameter(
SDMXExportSession exportSession) {
Map<String, Object> parameterInstances = new HashMap<String, Object>();
parameterInstances.put(Constants.PARAMETER_REGISTRYBASEURL,
"http://pc-fortunati.isti.cnr.it:8080/FusionRegistry/ws/rest/");
parameterInstances.put(Constants.PARAMETER_AGENCY, "SDMX");
parameterInstances.put(Constants.PARAMETER_ID, "NEW_CL_DIVISION");
parameterInstances.put(Constants.PARAMETER_VERSION, "2.0");
return parameterInstances;
}
/**
*
* @param exportSession
* @return
*/
public void startSDMXExport(SDMXExportSession exportSession)
throws TDGWTServiceException {
logger.debug("Start SDMX Export");
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
ASLSession aslSession = SessionUtil.getAslSession(session);
if (aslSession == null) {
throw new TDGWTServiceException(
"Error retrieving the asl session: null");
}
String user = aslSession.getUsername();
logger.info("Session User:" + user);
TRId trId = SessionUtil.getTRId(session);
if (trId == null) {
throw new TDGWTServiceException(
"Error no tabular resource in session");
}
if (trId.getTableId() == null) {
throw new TDGWTServiceException("Error no table present in session");
}
SessionUtil.setSDMXExportSession(session, exportSession);
Map<String, Object> parameterInstance = sdmxExportParameter(exportSession);
logger.debug("Tabular Data Service");
TabularDataService service = TabularDataServiceFactory
.getService(aslSession.getUsername());
List<OperationDescriptor> capabilities = service.getCapabilities();
// Export SDMX Codelist
OperationDescriptor exportSDMXOperation = getOperationDescriptorWithId(
OperationsId.SDMXCodelistExport.toString(), capabilities);
InvocationCreator ic = InvocationCreator
.getCreator(exportSDMXOperation);
OperationInvocation invocation = ic
.setTargetTable(new TableId(Long.valueOf(trId.getTableId())))
.setParameters(parameterInstance).create();
logger.debug("OperationInvocation: \n" + invocation.toString());
Task trTask;
try {
trTask = service.execute(invocation,
new TabularResourceId(Long.valueOf(trId.getId())));
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Tabular Data Service error exporting TabularResource: "
+ e.getLocalizedMessage());
}
logger.debug("Start Task on service: TaskId " + trTask.getId());
SessionUtil.setSDMXExportTask(session, trTask);
}
/**
* {@inheritDoc}
*/
public SDMXExportMonitor getSDMXExportMonitor()
throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
//ASLSession aslSession = SessionUtil.getAslSession(session);
Task task = SessionUtil.getSDMXExportTask(session);
SDMXExportMonitor exportMonitor = new SDMXExportMonitor();
if (task == null) {
logger.debug("Task null");
throw new TDGWTServiceException("Error in exportSDMX task null");
} else {
TaskStatus status = task.getStatus();
if (status == null) {
throw new TDGWTServiceException(
"Error in exportSDMX Status null");
} else {
logger.debug("Status: " + task.getStatus());
exportMonitor.setStatus(matchTaskState(task.getStatus()));
switch (exportMonitor.getStatus()) {
case FAILED:
if (task.getResult() != null) {
logger.debug("Task exception:"
+ task.getErrorCause());
exportMonitor.setError(task
.getErrorCause());
} else {
logger.debug("Task exception: Error In Export");
exportMonitor.setError(new Throwable(
"Error In Export"));
}
exportMonitor.setProgress(task.getProgress());
break;
case SUCCEDED:
logger.debug("Task Result:" + task.getResult());
exportMonitor.setProgress(task.getProgress());
Table table = task.getResult().getPrimaryTable();
logger.debug("Table retrived: " + table.toString());
ExportMetadata exportMetadata = table
.getMetadata(ExportMetadata.class);
logger.debug("ExportMetadata: " + exportMetadata);
exportMonitor.setTrId(SessionUtil.getTRId(session));
TabExportMetadata tabExportMetadata = new TabExportMetadata();
tabExportMetadata.setUrl(exportMetadata.getUri());
tabExportMetadata.setDestinationType(exportMetadata
.getDestinationType());
tabExportMetadata.setExportDate(sdf
.format(exportMetadata.getExportDate()));
exportMonitor.setTabExportMetadata(tabExportMetadata);
break;
case IN_PROGRESS:
exportMonitor.setProgress(task.getProgress());
break;
case ABORTED:
break;
case INITIALIZING:
break;
case WAITING:
break;
default:
break;
}
}
SessionUtil.setSDMXExportTask(session, task);
}
logger.info("getExportMonitor(): " + exportMonitor);
return exportMonitor;
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Error in exportSDMX SDMXExportMonitor: "
+ e.getLocalizedMessage());
}
}
/**
*
* {@inheritDoc}
*/
public void startCSVExport(CSVExportSession exportSession)
throws TDGWTServiceException {
logger.debug("Start CSV Export");
HttpSession session = this.getThreadLocalRequest().getSession();
if (session == null) {
throw new TDGWTServiceException(
"Error retrieving the session: null");
}
logger.info("Session:" + session.getId());
ASLSession aslSession = SessionUtil.getAslSession(session);
if (aslSession == null) {
throw new TDGWTServiceException(
"Error retrieving the asl session: null");
}
String user = aslSession.getUsername();
logger.info("Session User:" + user);
TRId trId = SessionUtil.getTRId(session);
if (trId == null) {
throw new TDGWTServiceException(
"Error no tabular resource in session");
}
if (trId.getTableId() == null) {
throw new TDGWTServiceException("Error no table present in session");
}
SessionUtil.setCSVExportSession(session, exportSession);
Map<String, Object> parameterInstance = csvExportFileParameter(exportSession);
logger.debug("Tabular Data Service");
TabularDataService service = TabularDataServiceFactory
.getService(aslSession.getUsername());
List<OperationDescriptor> capabilities = service.getCapabilities();
// Export CSV file
OperationDescriptor exportCSVFileOperation = getOperationDescriptorWithId(
OperationsId.CSVExport.toString(), capabilities);
InvocationCreator ic = InvocationCreator
.getCreator(exportCSVFileOperation);
OperationInvocation invocation = ic
.setTargetTable(new TableId(Long.valueOf(trId.getTableId())))
.setParameters(parameterInstance).create();
logger.debug("OperationInvocation: \n" + invocation.toString());
Task trTask;
try {
trTask = service.execute(invocation,
new TabularResourceId(Long.valueOf(trId.getId())));
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Tabular Data Service error exporting TabularResource: "
+ e.getLocalizedMessage());
}
logger.debug("Start Task on service: TaskId " + trTask.getId());
SessionUtil.setCSVExportEnd(session, false);
SessionUtil.setCSVExportTask(session, trTask);
}
/**
* {@inheritDoc}
*/
public CSVExportMonitor getCSVExportMonitor() throws TDGWTServiceException {
try {
HttpSession session = this.getThreadLocalRequest().getSession();
ASLSession aslSession = SessionUtil.getAslSession(session);
CSVExportSession exportSession = SessionUtil
.getCSVExportSession(session);
Task task = SessionUtil.getCSVExportTask(session);
CSVExportMonitor exportMonitor = new CSVExportMonitor();
if (task == null) {
logger.debug("Task null");
throw new TDGWTServiceException("Error in exportCSV task null");
} else {
TaskStatus status = task.getStatus();
if (status == null) {
throw new TDGWTServiceException(
"Error in exportCSV Status null");
} else {
logger.debug("Status: " + task.getStatus());
exportMonitor.setStatus(matchTaskState(task.getStatus()));
switch (exportMonitor.getStatus()) {
case FAILED:
if (task.getResult() != null) {
logger.debug("Task exception:"
+ task.getErrorCause());
exportMonitor.setError(new Throwable(task
.getErrorCause()));
} else {
logger.debug("Task exception: Error In Export");
exportMonitor.setError(new Throwable(
"Error In Export"));
}
exportMonitor.setProgress(task.getProgress());
break;
case SUCCEDED:
SessionUtil.setCSVExportEnd(session, true);
logger.debug("Task Result:" + task.getResult());
exportMonitor.setProgress(task.getProgress());
Table table = task.getResult().getPrimaryTable();
logger.debug("Table retrived: " + table.toString());
ExportMetadata exportMetadata = table
.getMetadata(ExportMetadata.class);
logger.debug("ExportMetadata: " + exportMetadata);
exportMonitor.setTrId(SessionUtil.getTRId(session));
TabExportMetadata trExportMetadata = new TabExportMetadata();
trExportMetadata.setUrl(exportMetadata.getUri());
trExportMetadata.setDestinationType(exportMetadata
.getDestinationType());
trExportMetadata.setExportDate(sdf
.format(exportMetadata.getExportDate()));
exportMonitor.setTrExportMetadata(trExportMetadata);
saveInDestination(session,aslSession.getUsername(),
exportMetadata, exportSession);
break;
case IN_PROGRESS:
exportMonitor.setProgress(task.getProgress());
break;
case ABORTED:
break;
case INITIALIZING:
break;
case WAITING:
break;
default:
break;
}
}
SessionUtil.setCSVExportTask(session, task);
}
logger.info("getExportMonitor(): " + exportMonitor);
return exportMonitor;
} catch (Exception e) {
e.printStackTrace();
throw new TDGWTServiceException(
"Error in exportCSV CSVExportMonitor: "
+ e.getLocalizedMessage());
}
}
protected void saveInDestination(HttpSession session,String user,
ExportMetadata exportMetadata, CSVExportSession exportSession)
throws TDGWTServiceException {
if (exportSession.getDestination().getId().compareTo("Workspace") == 0) {
if (SessionUtil.getCSVExportEnd(session) == false) {
SessionUtil.setCSVExportEnd(session, true);
FilesStorage storage = new FilesStorage();
logger.debug("Create Item On Workspace: [ uri: "
+ exportMetadata.getUri() + " ,user: " + user
+ " ,fileName: " + exportSession.getFileName()
+ " ,fileDescription: "
+ exportSession.getFileDescription()
+ " ,mimetype: text/csv" + " ,folder: "
+ exportSession.getItemId() + "]");
storage.createItemOnWorkspace(exportMetadata.getUri(), user,
exportSession.getFileName(),
exportSession.getFileDescription(), "text/csv",
exportSession.getItemId());
}
} else {
}
}
}