Trying to use hibernate on local classes

This commit is contained in:
Fabio Sinibaldi 2020-11-23 18:31:20 +01:00
parent 6a4be82de5
commit 6b971e9997
22 changed files with 2551 additions and 36 deletions

21
pom.xml
View File

@ -83,18 +83,28 @@
<artifactId>geoportal-common</artifactId>
<version>[1.0.0-SNAPSHOT,2.0.0)</version>
</dependency>
<!-- javassist conflict -->
<dependency>
<groupId>org.gcube.application</groupId>
<artifactId>geoportal-logic</artifactId>
<version>[1.0.4-SNAPSHOT,2.0.0)</version>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- MONGO -->
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
@ -169,12 +179,7 @@
</dependency> -->
<!-- HIBERNATE -->
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency> -->
<!-- SIS -->

View File

@ -0,0 +1,288 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import org.gcube.application.geoportal.managers.DefatulEMFProvider;
import org.gcube.application.geoportal.managers.EMFProvider;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.db.DBConstants;
import org.gcube.application.geoportal.model.db.PostgisTable;
import org.gcube.application.geoportal.model.db.PostgisTable.Field;
import org.gcube.application.geoportal.model.db.PostgisTable.FieldType;
import org.gcube.application.geoportal.model.fault.ConfigurationException;
import org.gcube.application.geoportal.model.fault.PersistenceException;
import org.gcube.application.geoportal.model.fault.PublishException;
import org.gcube.application.geoportal.model.fault.SDIInteractionException;
import org.gcube.application.geoportal.model.fault.ValidationException;
import org.gcube.application.geoportal.model.report.PublicationReport;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.model.report.ValidationReport.ValidationStatus;
import org.gcube.application.geoportal.storage.PostgisDBManager;
import org.gcube.application.geoportal.storage.PostgisDBManagerI;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public abstract class AbstractRecordManager<T extends Record> {
public static void setDefaultProvider(EMFProvider provider) {
defaultProvider=provider;
}
private static EMFProvider defaultProvider=new FixedDefaultProvider();
@Synchronized
protected static EntityManagerFactory getEMF() {
return defaultProvider.getFactory();
}
@Synchronized
public static void shutdown() {
defaultProvider.shutdown();
}
public static Record getByID(long id) {
EntityManager em=getEMF().createEntityManager();
try {
log.debug("Looking for record by ID : "+id);
EntityTransaction tr=em.getTransaction();
tr.begin();
Record toReturn=em.find(Record.class, id);
log.debug("Loaded Record "+toReturn);
tr.commit();
return toReturn;
}finally {
if(em.isJoinedToTransaction())
em.flush();
em.close();
}
}
public static Collection<Record> getList(){
EntityManager em=getEMF().createEntityManager();
try {
log.debug("Getting entire list");
EntityTransaction tr=em.getTransaction();
tr.begin();
List<Record> toReturn=em.createQuery("select r from Record r ",
Record.class).getResultList();
log.debug("Loaded size "+toReturn.size());
tr.commit();
return toReturn;
}finally {
if(em.isJoinedToTransaction())
em.flush();
em.close();
}
}
public static <E extends Record> Collection<E> getListByClass(Class<E> clazz){
EntityManager em=getEMF().createEntityManager();
try {
log.debug("Getting entire list");
EntityTransaction tr=em.getTransaction();
tr.begin();
String simpleClassName=clazz.getName().substring(clazz.getName().lastIndexOf(".")+1);
List<E> toReturn=em.createQuery("select r from "+simpleClassName+" r",
clazz).getResultList();
log.debug("Loaded size "+toReturn.size());
tr.commit();
return toReturn;
}finally {
if(em.isJoinedToTransaction())
em.flush();
em.close();
}
}
// protected T storeInfo()
// {
// log.debug("Storing Record "+theRecord);
// entityManager.persist(theRecord);
// return theRecord;
// }
//Transaction management
EntityTransaction transaction=null;
EntityManager entityManager=null;
//************************ INSTANCE
private T theRecord;
private ContentHandler<T> contentHandler;
protected AbstractRecordManager(T theRecord){
entityManager=getEMF().createEntityManager();
transaction=entityManager.getTransaction();
transaction.begin();
this.theRecord=theRecord;
// log.debug("Storing Record "+theRecord);
if(theRecord.getId()==0) {
log.debug("Passed record ID = 0. Assuming new ..");
entityManager.persist(theRecord);
}else {
log.debug("Passed record ID = "+theRecord.getId()+". Mergeing..");
entityManager.merge(theRecord);
}
this.contentHandler=new ContentHandler<T>(theRecord);
}
protected ContentHandler<T> getContentHandler() {
return contentHandler;
}
public T getRecord() {
return theRecord;
};
/**
* Commit to storages
*
* @return
* @throws PersistenceException
* @throws PublishException
*/
public T commit(boolean publish) throws PersistenceException,ValidationException, PublishException {
log.trace("Committing record "+theRecord+" Publish is "+publish);
ValidationReport report=theRecord.validate();
log.debug("Validated Report is "+report);
if(publish && report.getStatus().equals(ValidationStatus.ERROR))
throw new ValidationException(report,"Cannot publish project. See validation report");
// storeInfo();
log.debug("Record is valid, storing changed content");
contentHandler.storeChanges(publish);
// storeInfo();
if(publish) {
log.debug("Registering centroid of "+theRecord);
registerCentroid();
// storeInfo();
}
transaction.commit();
return theRecord;
}
public PublicationReport commitSafely(boolean publish) {
log.debug("Safely publishing "+theRecord);
PublicationReport toReturn=new PublicationReport("Publication Report");
toReturn.setTheRecord(getRecord());
ValidationReport validation=theRecord.validate();
validation.setObjectName("Validation report for "+validation.getObjectName());
if(validation.getStatus().equals(ValidationStatus.ERROR)) {
toReturn.addMessage(publish?ValidationStatus.ERROR:ValidationStatus.WARNING, "Record not valid.");
}
toReturn.addChild(validation);
log.debug("Record is valid, storing changed content [Publish is :"+publish+"]");
try {
toReturn.addChild(contentHandler.storeChanges(publish));
if(publish) {
log.debug("Registering centroid of "+theRecord);
registerCentroid();
toReturn.addMessage(ValidationStatus.PASSED, "Inserito centroide per record "+theRecord.getId());
}
transaction.commit();
} catch (PersistenceException e) {
toReturn.addChild(e.getReport());
log.warn("Unexpected internal exception ",e);
} catch (PublishException e) {
toReturn.addMessage(ValidationStatus.WARNING, "Centroide non registrato");
log.warn("Unexpected internal exception ",e);
}
try {
log.info("Report is "+toReturn.prettyPrint());
}catch (Exception e) {
log.warn("Unable to pretty print report "+toReturn,e);
}
return toReturn;
}
@Override
protected void finalize() throws Throwable {
if(transaction.isActive()) {
transaction.rollback();
}
entityManager.flush();
entityManager.close();
shutdown();
}
private void registerCentroid() throws PublishException{
try {
log.debug("Evaluating Centroid");
Map<String,String> centroidRow=evaluateCentroid();
log.debug("Contacting postgis DB .. ");
PostgisDBManagerI db=PostgisDBManager.get();
PostgisTable centroidsTable=getCentroidsTable();
log.debug("Inserting / updated centroid Row {} ",centroidRow);
PreparedStatement ps = db.prepareInsertStatement(centroidsTable, true, true);
log.debug("Deleting centroid if present. ID is "+theRecord.getId());
db.deleteByFieldValue(centroidsTable, new Field(DBConstants.Concessioni.PRODUCT_ID,FieldType.TEXT), theRecord.getId()+"");
centroidsTable.fillCSVPreparedStatament(centroidRow, ps, false);
ps.executeUpdate();
db.commit();
initCentroidLayer();
}catch(SQLException e) {
log.warn("Unable to publish Centroid for record "+theRecord,e);
throw new PublishException("Unable to publish centroid.",e, null);
}catch(SDIInteractionException e) {
log.warn("Unable to publish Centroid Layer for record type "+getRecord().getRecordType(),e);
throw new PublishException("Unable to publish centroid.",e, null);
} catch (ConfigurationException e) {
log.warn("Unable to contact centroids db "+getRecord().getRecordType(),e);
throw new PublishException("Unable to publish centroid.",e, null);
}
}
protected abstract PostgisTable getCentroidsTable();
protected abstract void initCentroidLayer() throws SDIInteractionException;
protected abstract Map<String,String> evaluateCentroid();
//*********** PERSISTENCE
}

View File

@ -0,0 +1,172 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.gcube.application.geoportal.model.InputStreamDescriptor;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.fault.PersistenceException;
import org.gcube.application.geoportal.model.fault.SDIInteractionException;
import org.gcube.application.geoportal.model.report.PublicationReport;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.model.report.ValidationReport.ValidationStatus;
import org.gcube.application.geoportal.service.model.legacy.concessioni.AssociatedContent;
import org.gcube.application.geoportal.service.model.legacy.concessioni.GeoServerContent;
import org.gcube.application.geoportal.service.model.legacy.concessioni.LayerConcessione;
import org.gcube.application.geoportal.service.model.legacy.concessioni.OtherContent;
import org.gcube.application.geoportal.service.model.legacy.concessioni.PersistedContent;
import org.gcube.application.geoportal.service.model.legacy.concessioni.RelazioneScavo;
import org.gcube.application.geoportal.service.model.legacy.concessioni.SDILayerDescriptor;
import org.gcube.application.geoportal.service.model.legacy.concessioni.UploadedImage;
import org.gcube.application.geoportal.service.model.legacy.concessioni.WorkspaceContent;
import org.gcube.application.geoportal.utils.Files;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ContentHandler<T extends Record> {
private Map<AssociatedContent,ArrayList<TempFile>> uploadedResources=new HashMap<AssociatedContent, ArrayList<TempFile>>();
private Map<AssociatedContent,ArrayList<TempFile>> toDeleteResources=new HashMap<AssociatedContent, ArrayList<TempFile>>();
private ArrayList<TempFile> toDeleteTemps=new ArrayList<TempFile>();
private T record;
public ContentHandler(T record) {
this.record=record;
}
/**
* Register files as to be associated with content
*
* @param content
* @param files
* @throws IOException
*/
public void register(AssociatedContent content, InputStreamDescriptor...iss) throws IOException {
ArrayList<TempFile> tempFiles=new ArrayList<TempFile>();
for(InputStreamDescriptor is:iss)
tempFiles.add(new TempFile(Files.copyToTemp(is.getStream()),is.getFilename()));
toDeleteTemps.addAll(tempFiles);
uploadedResources.put(content, tempFiles);
}
/**
* Unregisters files from current operation set *
*
*/
public void unregister(AssociatedContent content, InputStreamDescriptor...iss) {
}
public void dispose(AssociatedContent content) {
}
public PublicationReport storeChanges(Boolean publish) throws PersistenceException {
//
log.debug("Starting to persist "+uploadedResources.size()+" resources "+record.getNome());
PublicationReport toReturn=new PublicationReport("Storage report");
try {
WorkspaceManager wsManager=new WorkspaceManager(record);
SDIManager sdiManager=null;
if(publish)
sdiManager=new SDIManager();
for(Entry<AssociatedContent,ArrayList<TempFile>> entry:uploadedResources.entrySet()) {
AssociatedContent content=entry.getKey();
ArrayList<PersistedContent> persisted=new ArrayList<PersistedContent>();
FolderContainer destination=null;
String description=null;
String workspace=null;
log.debug("Storing "+content);
if(content instanceof RelazioneScavo) {
destination= wsManager.getSubFolder("relazione");
description="Relazione di scavo : "+content.getTitolo();
}else if (content instanceof UploadedImage) {
destination= wsManager.getSubFolder("imgs");
description="Immagine significativa : "+content.getTitolo();
}else if (content instanceof SDILayerDescriptor) {
//SDI Section
if(content instanceof LayerConcessione) {
destination= wsManager.getSubFolder("layers/"+content.getTitolo());
description="Layer concessione : "+content.getTitolo();
if(publish) {
try {
//if not present create workspace for current project
if(workspace==null)
workspace=sdiManager.createWorkspace("gna_conc_"+record.getId());
GeoServerContent geoserverPersisted=sdiManager.pushShapeLayerFileSet((SDILayerDescriptor)content, entry.getValue(),workspace);
geoserverPersisted.setAssociated(content);
persisted.add(geoserverPersisted);
}catch(SDIInteractionException e) {
log.warn("Unable to publish layers.",e);
toReturn.addMessage(ValidationStatus.WARNING, "Layer "+content.getTitolo()+" non pubblicato.");
}
toReturn.addMessage(ValidationStatus.PASSED, "Pubblicato layer "+content.getTitolo());
}
}else throw new Exception("Invalid SDI Content "+content);
}else if (content instanceof OtherContent ) {
destination= wsManager.getSubFolder("other/"+content.getTitolo());
description= "Other content : "+content.getTitolo();
}else throw new Exception ("Invalid content "+content);
log.debug("Actually Storing files to WS folder "+destination.getId());
for(TempFile theFile : entry.getValue()) {
WorkspaceContent wsContent=wsManager.storeToWS(theFile.getTheFile(), destination, theFile.getOriginalFileName(), description);
wsContent.setAssociated(content);
persisted.add(wsContent);
}
toReturn.addMessage(ValidationStatus.PASSED, "Registrati "+entry.getValue().size()+" elementi in archivio per : "+content.getTitolo());
content.setActualContent(persisted);
}
return toReturn;
}catch(StorageHubException e) {
toReturn.addMessage(ValidationStatus.ERROR, "Impossibile archiviare.");
log.error("Unexpected SGHUB Exception",e);
throw new PersistenceException("Unexpected Exception",e,toReturn);
}catch(Throwable t) {
toReturn.addMessage(ValidationStatus.ERROR, "Errore inatteso.");
throw new PersistenceException("Unexpected Exception",t,toReturn);
}
}
@Override
protected void finalize() throws Throwable {
for(TempFile f:toDeleteTemps)
java.nio.file.Files.deleteIfExists(f.getTheFile().toPath());
}
public ValidationReport validateContent() {
return null;
}
}

View File

@ -0,0 +1,192 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.gcube.application.geoportal.managers.DefatulEMFProvider;
import org.gcube.application.geoportal.managers.EMFProvider;
import org.gcube.application.geoportal.model.db.DatabaseConnection;
import org.gcube.application.geoportal.model.fault.ConfigurationException;
import org.gcube.application.geoportal.utils.ISUtils;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider;
import jersey.repackaged.com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FixedDefaultProvider implements EMFProvider{
private static EntityManagerFactory emf=null;
@Override
public EntityManagerFactory getFactory() {
if(emf==null) {
try {
DatabaseConnection conn=ISUtils.queryForDB("postgresql", "internal-db");
log.debug("Found Internal Database : "+conn);
emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
archiverPersistenceUnitInfo(),
ImmutableMap.<String, Object>builder()
.put(AvailableSettings.JPA_JDBC_DRIVER, "org.postgresql.Driver")
.put(AvailableSettings.JPA_JDBC_URL, conn.getUrl())
.put(AvailableSettings.DIALECT, org.hibernate.dialect.PostgreSQLDialect.class)
.put(AvailableSettings.HBM2DDL_AUTO, org.hibernate.tool.schema.Action.UPDATE)
.put(AvailableSettings.SHOW_SQL, true)
.put(AvailableSettings.QUERY_STARTUP_CHECKING, false)
.put(AvailableSettings.GENERATE_STATISTICS, false)
.put(AvailableSettings.USE_REFLECTION_OPTIMIZER, false)
.put(AvailableSettings.USE_SECOND_LEVEL_CACHE, false)
.put(AvailableSettings.USE_QUERY_CACHE, false)
.put(AvailableSettings.USE_STRUCTURED_CACHE, false)
.put(AvailableSettings.STATEMENT_BATCH_SIZE, 20)
.put(AvailableSettings.JPA_JDBC_USER, conn.getUser())
.put(AvailableSettings.JPA_JDBC_PASSWORD, conn.getPwd())
.build());
}catch(ConfigurationException e) {
throw new RuntimeException("Unable to init EMF",e);
}
}
return emf;
}
private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
final List<String> MANAGED_CLASSES=Arrays.asList(new String[] {
"org.gcube.application.geoportal.model.Record",
"org.gcube.application.geoportal.service.model.legacy.concessioni.Concessione",
"org.gcube.application.geoportal.service.model.legacy.concessioni.LayerConcessione",
"org.gcube.application.geoportal.service.model.legacy.concessioni.RelazioneScavo",
"org.gcube.application.geoportal.service.model.legacy.concessioni.AssociatedContent",
"org.gcube.application.geoportal.service.model.legacy.concessioni.GeoServerContent",
"org.gcube.application.geoportal.service.model.legacy.concessioni.OtherContent",
"org.gcube.application.geoportal.service.model.legacy.concessioni.PersistedContent",
"org.gcube.application.geoportal.service.model.legacy.concessioni.UploadedImage",
"org.gcube.application.geoportal.service.model.legacy.concessioni.WorkspaceContent",
"org.gcube.application.geoportal.service.model.legacy.concessioni.ShapeFileLayerDescriptor",
"org.gcube.application.geoportal.service.model.legacy.concessioni.SDILayerDescriptor"});
return new PersistenceUnitInfo() {
@Override
public String getPersistenceUnitName() {
return "ApplicationPersistenceUnit";
}
@Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
@Override
public DataSource getJtaDataSource() {
return null;
}
@Override
public DataSource getNonJtaDataSource() {
return null;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return MANAGED_CLASSES;
}
@Override
public boolean excludeUnlistedClasses() {
return true;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
return new Properties();
}
@Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public void addTransformer(ClassTransformer transformer) {
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
@Override
public void shutdown() {
if(emf!=null) {
if(emf.isOpen()) emf.close();
emf=null;
}
}
}

View File

@ -0,0 +1,139 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.gcube.application.geoportal.model.InputStreamDescriptor;
import org.gcube.application.geoportal.model.db.DBConstants;
import org.gcube.application.geoportal.model.db.PostgisTable;
import org.gcube.application.geoportal.model.fault.SDIInteractionException;
import org.gcube.application.geoportal.service.model.legacy.concessioni.Concessione;
import org.gcube.application.geoportal.service.model.legacy.concessioni.LayerConcessione;
import org.gcube.application.geoportal.service.model.legacy.concessioni.RelazioneScavo;
import org.gcube.application.geoportal.service.model.legacy.concessioni.UploadedImage;
import org.gcube.application.geoportal.service.utils.Serialization;
import org.gcube.application.geoportal.storage.SDIManager;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LegacyConcessioniManager extends AbstractRecordManager<Concessione> {
public LegacyConcessioniManager(Concessione theRecord) {
super(theRecord);
}
@Override
protected PostgisTable getCentroidsTable() {
return DBConstants.Concessioni.CENTROIDS;
}
@Override
protected void initCentroidLayer() throws SDIInteractionException {
log.debug("Checking for centroid layer configuration.. ");
SDIManager sdiManager=new SDIManager();
sdiManager.configureCentroidLayer("centroids_concessioni", "gna", "gna_postgis");
}
public Concessione setRelazioneScavo(RelazioneScavo rel, InputStreamDescriptor theFile) throws IOException {
ContentHandler handler=getContentHandler();
//Check if already stored content
Concessione record=getRecord();
if(record.getRelazioneScavo()!=null && !record.getRelazioneScavo().getActualContent().isEmpty()) {
handler.dispose(record.getRelazioneScavo());
}
rel.setRecord(record);
//Register relazione
record.setRelazioneScavo(rel);
handler.register(rel, theFile);
return record;
}
public Concessione addImmagineRappresentativa(UploadedImage img, InputStreamDescriptor theFile) throws IOException {
ContentHandler handler=getContentHandler();
Concessione record=getRecord();
//Add immagine
img.setRecord(record);
record.getImmaginiRappresentative().add(img);
handler.register(img, theFile);
return record;
}
// public Concessione disposeImmagineRappresentativa(UploadedImage img, InputStream theFile) {
// if(concessione.)
// }
public Concessione setPosizionamento(LayerConcessione layer, InputStreamDescriptor...inputStreams ) throws IOException {
ContentHandler handler=getContentHandler();
//Check if already stored content
Concessione record=getRecord();
if(record.getPosizionamentoScavo()!=null && !record.getPosizionamentoScavo().getActualContent().isEmpty())
handler.dispose(record.getPosizionamentoScavo());
layer.setRecord(record);
//Register posizionamneot
record.setPosizionamentoScavo(layer);
handler.register(layer, inputStreams);
return record;
}
public Concessione addPiantaFineScavo(LayerConcessione layer, InputStreamDescriptor...inputStreams ) throws IOException {
ContentHandler handler=getContentHandler();
Concessione record=getRecord();
//Add pianta
layer.setRecord(record);
record.getPianteFineScavo().add(layer);
handler.register(layer, inputStreams);
return record;
}
@Override
protected Map<String,String> evaluateCentroid(){
Concessione record=getRecord();
// CENTROID
Map<String,String> centroidsRow=new HashMap<String, String>();
centroidsRow.put(DBConstants.Concessioni.PRODUCT_ID, record.getId()+"");
centroidsRow.put(DBConstants.Concessioni.ANNO, record.getDataInizioProgetto().getYear()+"");
centroidsRow.put(DBConstants.Concessioni.NOME, record.getNome());
centroidsRow.put(DBConstants.Concessioni.REGIONE, ""); //TODO
centroidsRow.put(DBConstants.Defaults.XCOORD_FIELD, record.getCentroidLong()+"");
centroidsRow.put(DBConstants.Defaults.YCOORD_FIELD, record.getCentroidLat()+"");
//Updated Schema
centroidsRow.put(DBConstants.Concessioni.DESCRIZIONE,record.getIntroduzione());
centroidsRow.put(DBConstants.Concessioni.CONTENUTO,record.getDescrizioneContenuto());
centroidsRow.put(DBConstants.Concessioni.AUTORE,Serialization.asString(record.getAuthors()));
centroidsRow.put(DBConstants.Concessioni.CONTRIBUTORE,record.getContributore());
centroidsRow.put(DBConstants.Concessioni.TITOLARE,Serialization.asString(record.getTitolari()));
centroidsRow.put(DBConstants.Concessioni.RESPONSABILE,record.getResponsabile());
centroidsRow.put(DBConstants.Concessioni.EDITORE,record.getEditore());
centroidsRow.put(DBConstants.Concessioni.FINANZIAMENTO,Serialization.asString(record.getFontiFinanziamento()));
centroidsRow.put(DBConstants.Concessioni.SOGGETTO,Serialization.asString(record.getSoggetto()));
centroidsRow.put(DBConstants.Concessioni.RISORSE,Serialization.asString(record.getRisorseCorrelate()));
centroidsRow.put(DBConstants.Concessioni.DATE_SCAVO,Serialization.FULL_FORMATTER.format(record.getDataFineProgetto()));
centroidsRow.put(DBConstants.Concessioni.DATA_ARCHIVIAZIONE,Serialization.FULL_FORMATTER.format(record.getLastUpdateTime()));
centroidsRow.put(DBConstants.Concessioni.VERSIONE,record.getVersion());
centroidsRow.put(DBConstants.Concessioni.LICENZA,record.getLicenzaID());
centroidsRow.put(DBConstants.Concessioni.TITOLARE_LICENZA,record.getTitolareLicenza());
centroidsRow.put(DBConstants.Concessioni.ACCESSO,record.getPolicy().toString());
centroidsRow.put(DBConstants.Concessioni.PAROLE_CHIAVE,Serialization.asString(record.getParoleChiaveLibere()));
return centroidsRow;
}
}

View File

@ -0,0 +1,212 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.gcube.application.geoportal.model.fault.SDIInteractionException;
import org.gcube.application.geoportal.service.model.legacy.concessioni.GeoServerContent;
import org.gcube.application.geoportal.service.model.legacy.concessioni.SDILayerDescriptor;
import org.gcube.application.geoportal.utils.Files;
import org.gcube.data.transfer.library.DataTransferClient;
import org.gcube.data.transfer.library.TransferResult;
import org.gcube.data.transfer.library.faults.DestinationNotSetException;
import org.gcube.data.transfer.library.faults.FailedTransferException;
import org.gcube.data.transfer.library.faults.InitializationException;
import org.gcube.data.transfer.library.faults.InvalidDestinationException;
import org.gcube.data.transfer.library.faults.InvalidSourceException;
import org.gcube.data.transfer.library.faults.SourceNotSetException;
import org.gcube.data.transfer.model.Destination;
import org.gcube.data.transfer.model.DestinationClashPolicy;
import org.gcube.spatial.data.gis.GISInterface;
import org.gcube.spatial.data.gis.is.AbstractGeoServerDescriptor;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.UploadMethod;
import it.geosolutions.geoserver.rest.encoder.GSLayerEncoder;
import it.geosolutions.geoserver.rest.encoder.datastore.GSPostGISDatastoreEncoder;
import it.geosolutions.geoserver.rest.encoder.feature.GSFeatureTypeEncoder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SDIManager {
static private String DEFAULT_CRS="EPSG:4326";
private GISInterface gis;
private DataTransferClient dtGeoServer;
private String geoserverHostName;
public SDIManager() throws SDIInteractionException {
try{
log.debug("Initializing GIS Interface..");
gis=GISInterface.get();
AbstractGeoServerDescriptor geoserver=gis.getCurrentGeoServer();
if(geoserver==null)
throw new Exception("Unable to contact data transfer for geoserver ");
log.debug("Found geoserver descriptor "+geoserver);
geoserverHostName=new URL(gis.getCurrentGeoServer().getUrl()).getHost();
log.debug("Contacting Data Transfer from geoserver {} ",geoserverHostName);
dtGeoServer=DataTransferClient.getInstanceByEndpoint("http://"+geoserverHostName);
}catch(Exception e) {
throw new SDIInteractionException("Unable to initialize SDI Manager",e);
}
}
public String createWorkspace(String toCreate) throws SDIInteractionException {
try {
if(!gis.getCurrentGeoServer().getPublisher().createWorkspace(toCreate))
log.warn("Unable to create workspace "+toCreate+". Assuming already exisintg..");
return toCreate;
} catch (IllegalArgumentException | MalformedURLException e) {
throw new SDIInteractionException("Unable to create workspace "+toCreate,e);
}
}
// GEOSERVER-PERSISTENCE-ID / GNA / PROJECT-ID /LAYER-ID/ FILENAME
public GeoServerContent pushShapeLayerFileSet(SDILayerDescriptor currentElement,List<TempFile> files,String workspace) throws SDIInteractionException{
try {
String remoteFolder=null;
String fileName=null;
log.debug("Transferring "+files.size()+" files to geoserver @ "+geoserverHostName);
GeoServerContent content=new GeoServerContent();
content.setGeoserverHostName(geoserverHostName);
content.setWorkspace(workspace);
for(TempFile f:files) {
Destination destination=new Destination(f.getOriginalFileName());
destination.setCreateSubfolders(true);
destination.setOnExistingFileName(DestinationClashPolicy.REWRITE);
destination.setOnExistingSubFolder(DestinationClashPolicy.ADD_SUFFIX);
destination.setPersistenceId("geoserver");
destination.setSubFolder("GNA/"+currentElement.getRecord().getId()+"/"+currentElement.getLayerName());
TransferResult result=dtGeoServer.localFile(f.getTheFile(), destination);
content.getFileNames().add(f.getOriginalFileName());
remoteFolder=result.getRemotePath().substring(0,result.getRemotePath().lastIndexOf("/"));
fileName=f.getOriginalFileName();
content.setGeoserverPath(remoteFolder);
}
String toSetLayerName=fileName.substring(0,fileName.lastIndexOf("."));
content.setStore(toSetLayerName+"_store");
content.setFeatureType(toSetLayerName);
GeoServerRESTPublisher publisher=gis.getCurrentGeoServer().getPublisher();
log.debug("Trying to create remote workspace : "+workspace);
gis.getCurrentGeoServer().getPublisher().createWorkspace(workspace);
log.debug("Publishing remote folder "+remoteFolder);
URL directoryPath=new URL("file:"+remoteFolder);
//TODO Evaluate SRS
boolean published=publisher.publishShp(
workspace,
toSetLayerName+"_store",
null,
toSetLayerName,
// UploadMethod.FILE, // neeeds zip
UploadMethod.EXTERNAL, // needs shp
directoryPath.toURI(),
DEFAULT_CRS, //SRS
""); // default style
if(!published) {
throw new SDIInteractionException("Unable to publish layer "+toSetLayerName+" under "+workspace+". Unknown Geoserver fault.");
}
currentElement.setLayerName(toSetLayerName);
// TODO Metadata
return content;
} catch (InvalidSourceException | SourceNotSetException | FailedTransferException | InitializationException
| InvalidDestinationException | DestinationNotSetException e) {
throw new SDIInteractionException("Unable to transfer fileSet for content "+currentElement,e);
} catch (SDIInteractionException e) {
throw e;
} catch (Throwable t) {
throw new SDIInteractionException("Unexpected internal fault while interacting with SDI.",t);
}
}
private String createStoreFromPostgisDB(String workspace,String storeName) throws SDIInteractionException {
//SET BY PROVISIONING
GSPostGISDatastoreEncoder encoder=new GSPostGISDatastoreEncoder(storeName);
encoder.setJndiReferenceName("java:comp/env/jdbc/postgres");
encoder.setLooseBBox(true);
encoder.setDatabaseType("postgis");
encoder.setEnabled(true);
encoder.setFetchSize(1000);
encoder.setValidateConnections(true);
try {
if(!gis.getCurrentGeoServer().getDataStoreManager().create(workspace, encoder))
log.warn("Unable to create workspace "+storeName+". Assuming already exisintg..");
return storeName;
} catch (IllegalArgumentException | MalformedURLException e) {
throw new SDIInteractionException("Unable to create store "+storeName,e);
}
}
private String publishLayer(File sldFile,String name) throws SDIInteractionException {
try {
if(!gis.getCurrentGeoServer().getPublisher().publishStyle(sldFile, name))
log.warn("Unable to create style "+name+". Assuming already exisintg..");
return name;
} catch (IllegalArgumentException | MalformedURLException e) {
throw new SDIInteractionException("Unable to create style "+name,e);
}
}
public String configureCentroidLayer(String name,String workspace,String storeName) throws SDIInteractionException {
GSFeatureTypeEncoder fte=new GSFeatureTypeEncoder();
fte.setAbstract("Centroid layer for "+name);
fte.setEnabled(true);
fte.setNativeCRS(DEFAULT_CRS);
fte.setTitle(name);
String style="clustered_centroids";
GSLayerEncoder layerEncoder=new GSLayerEncoder();
layerEncoder.setDefaultStyle(style);
layerEncoder.setEnabled(true);
layerEncoder.setQueryable(true);
try {
//Checking workspace
createWorkspace(workspace);
//Checking store
createStoreFromPostgisDB(workspace, storeName);
//Checkig layer
publishLayer(Files.getFileFromResources("styles/clustered_points.sld"),style);
if(!gis.getCurrentGeoServer().getPublisher().publishDBLayer(workspace, storeName, fte, layerEncoder))
log.warn("Unable to create layer "+name+". Assuming already exisintg..");
return name;
} catch (IllegalArgumentException | MalformedURLException e) {
throw new SDIInteractionException("Unable to create layer "+name,e);
}
}
}

View File

@ -0,0 +1,13 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.File;
import lombok.Data;
import lombok.NonNull;
@Data class TempFile{
@NonNull
File theFile;
@NonNull
String originalFileName;
}

View File

@ -0,0 +1,110 @@
package org.gcube.application.geoportal.service.engine.legacy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.LocalDateTime;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.service.model.legacy.concessioni.WorkspaceContent;
import org.gcube.application.geoportal.utils.Serialization;
import org.gcube.application.geoportal.utils.Workspace;
import org.gcube.common.storagehub.client.dsl.FileContainer;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WorkspaceManager {
private Record record;
public WorkspaceManager(Record record) {
this.record=record;
}
private StorageHubClient sgClient=null;
private FolderContainer wsBase=null;
private FolderContainer appBase=null;
private static final String APP_FOLDER=".GNA_RECORDS";
private StorageHubClient getSGClient() {
if(sgClient==null)
sgClient=Workspace.getClient();
return sgClient;
}
public FolderContainer getApplicationBaseFolder() throws StorageHubException {
if(appBase==null) {
StorageHubClient client=getSGClient();
FolderContainer vre=client.openVREFolder();
try {
appBase = vre.openByRelativePath(APP_FOLDER).asFolder();
}catch(StorageHubException e) {
log.debug("APP Fodler missing. Initializing..");
appBase = vre.newFolder(APP_FOLDER, "Base folder for GNA records");
appBase.setHidden();
}
}
return appBase;
}
private FolderContainer getWSBase() throws StorageHubException {
if(wsBase==null) {
log.debug("WSBASE not set");
if(record.getFolderId()==null) {
//init folder
log.debug("Initializing record folder..");
String creationTime=Serialization.FULL_FORMATTER.format(LocalDateTime.now());
String folderName=record.getRecordType()+"_"+record.getNome()+"_"+creationTime;
log.debug("Folder name will be "+folderName);
wsBase=getApplicationBaseFolder().newFolder(folderName, "Base folder del record "+record.getNome());
record.setFolderId(wsBase.getId());
}
log.debug("Opening folder");
wsBase=getSGClient().open(record.getFolderId()).asFolder();
}
return wsBase;
}
public FolderContainer getSubFolder(String path) throws StorageHubException {
return getSubFolder(getWSBase(),path);
}
private FolderContainer getSubFolder(FolderContainer parentFolder,String path) throws StorageHubException {
try{
return parentFolder.openByRelativePath(path).asFolder();
}catch(StorageHubException e) {
log.debug("Missing subPath "+path);
FolderContainer targetParent=parentFolder;
String targetName=path;
if(path.contains("/")) {
String parent=path.substring(0, path.lastIndexOf("/"));
log.debug("Checking intermediate "+parent);
targetParent=getSubFolder(parentFolder,parent);
targetName=path.substring(path.lastIndexOf("/")+1);
}
log.debug("Creating "+targetName);
return targetParent.newFolder(targetName, "");
}
}
public WorkspaceContent storeToWS(File f,FolderContainer destination,String name,String description) throws FileNotFoundException, StorageHubException {
FileContainer item=destination.uploadFile(new FileInputStream(f), name, description);
item=getSGClient().open(item.getId()).asFile();
WorkspaceContent content=new WorkspaceContent();
content.setLink(item.getPublicLink().toString());
content.setMimetype(item.get().getContent().getMimeType());
content.setStorageID(item.getId());
return content;
}
}

View File

@ -0,0 +1,175 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import org.gcube.application.geoportal.model.AccessPolicy;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.utils.CollectionsUtils;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = OtherContent.class),
@Type(value = RelazioneScavo.class),
@Type(value = SDILayerDescriptor.class),
@Type(value = LayerConcessione.class),
@Type(value = UploadedImage.class),
})
public abstract class AssociatedContent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@XmlElement
private AccessPolicy policy;
private String licenseID;
private String titolo;
private LocalDateTime creationTime;
public ValidationReport validateForInsertion() {
ValidationReport toReturn=new ValidationReport("Associated Content");
toReturn.checkMandatory(policy, "Politica di accesso");
toReturn.checkMandatory(licenseID, "Licenza");
toReturn.checkMandatory(titolo,"Titolo");
toReturn.checkMandatory(creationTime, "Creation time");
return toReturn;
}
public abstract void setRecord(Record r);
public abstract Record getRecord();
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "associated", cascade = CascadeType.ALL)
@XmlElements({
@XmlElement(type=GeoServerContent.class),
@XmlElement(type=WorkspaceContent.class),
})
private List<PersistedContent> actualContent=new ArrayList<>();
public void detachContent() {
if(actualContent!=null)
for(PersistedContent p:actualContent)
p.setAssociated(null);
}
public void reattachContent() {
if(actualContent!=null)
for(PersistedContent p:actualContent)
p.setAssociated(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
// result = prime * result + ((actualContent == null) ? 0 : actualContent.hashCode());
result = prime * result + CollectionsUtils.hashCode(actualContent);
result = prime * result + ((creationTime == null) ? 0 : creationTime.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((licenseID == null) ? 0 : licenseID.hashCode());
result = prime * result + ((policy == null) ? 0 : policy.hashCode());
result = prime * result + ((titolo == null) ? 0 : titolo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AssociatedContent other = (AssociatedContent) obj;
// if (actualContent == null) {
// if (other.actualContent != null)
// return false;
// } else if (!actualContent.equals(other.actualContent))
// return false;
if(!CollectionsUtils.equalsCollections(actualContent, other.actualContent)) return false;
if (creationTime == null) {
if (other.creationTime != null)
return false;
} else if (!creationTime.equals(other.creationTime))
return false;
if (id != other.id)
return false;
if (licenseID == null) {
if (other.licenseID != null)
return false;
} else if (!licenseID.equals(other.licenseID))
return false;
if (policy != other.policy)
return false;
if (titolo == null) {
if (other.titolo != null)
return false;
} else if (!titolo.equals(other.titolo))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AssociatedContent [id=");
builder.append(id);
builder.append(", policy=");
builder.append(policy);
builder.append(", licenseID=");
builder.append(licenseID);
builder.append(", titolo=");
builder.append(titolo);
builder.append(", creationTime=");
builder.append(creationTime);
builder.append(", actualContent=");
builder.append(actualContent);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,36 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.io.Serializable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
@RequiredArgsConstructor
@Getter
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class BBOX implements Serializable{
/**
*
*/
private static final long serialVersionUID = -159414992596542946L;
public static BBOX WORLD_EXTENT=new BBOX(90d,180d,-90d,-180d);
@NonNull
private Double maxLat;
@NonNull
private Double maxLong;
@NonNull
private Double minLat;
@NonNull
private Double minLong;
}

View File

@ -0,0 +1,533 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.gcube.application.geoportal.model.AccessPolicy;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.RecordType;
import org.gcube.application.geoportal.model.report.Check;
import org.gcube.application.geoportal.model.report.ConstraintCheck;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.model.report.ValidationReport.ValidationStatus;
import org.gcube.application.geoportal.utils.CollectionsUtils;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString(callSuper=true)
@Entity
@DiscriminatorValue("CONCESSIONE")
public class Concessione extends Record{
//Introduzione (descrizione del progetto)
private String introduzione;
//Descrizione del contenuto
private String descrizioneContenuto;
//Autori
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> authors;
//Soggetto che materialmente invia i dati.
private String contributore;
//Indicare il nome del titolare/i dei dati contenuti nel dataset e/o per sue specifiche parti.
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> titolari;
private String responsabile;
private String editore;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> fontiFinanziamento;
//Research Excavation; Archaeology (valori di default)
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> soggetto;
//Referenze bibliografiche, DOI (se esistenti) di risorse correlate allindagine in oggetto
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> risorseCorrelate;
private LocalDateTime dataInizioProgetto;
private LocalDateTime dataFineProgetto;
private String titolareLicenza;
private String titolareCopyright;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> paroleChiaveLibere;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> paroleChiaveICCD;
private Double centroidLat;
private Double centroidLong;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToOne(cascade = CascadeType.ALL)
private RelazioneScavo relazioneScavo;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "record", cascade = CascadeType.ALL)
private List<UploadedImage> immaginiRappresentative=new ArrayList<UploadedImage>();
@LazyCollection(LazyCollectionOption.FALSE)
@OneToOne(cascade = CascadeType.ALL)
private LayerConcessione posizionamentoScavo;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "record", cascade = CascadeType.ALL)
private List<LayerConcessione> pianteFineScavo=new ArrayList<>();
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "record", cascade = CascadeType.ALL)
private List<OtherContent> genericContent=new ArrayList<>();
public Concessione() {
super();
setRecordType(RecordType.CONCESSIONE);
}
@Override
public String asJson() throws JsonProcessingException {
// Detaching Content ...
if(relazioneScavo!=null) {
relazioneScavo.setRecord(null);
relazioneScavo.detachContent();
}
if(immaginiRappresentative!=null)
for(UploadedImage img:immaginiRappresentative) {
img.setRecord(null);
img.detachContent();
}
if(posizionamentoScavo!=null) {
posizionamentoScavo.setRecord(null);
posizionamentoScavo.detachContent();
}
if(pianteFineScavo!=null)
for(LayerConcessione l:pianteFineScavo) {
l.setRecord(null);
l.detachContent();
}
if(genericContent!=null)
for(OtherContent o:genericContent) {
o.setRecord(null);
o.detachContent();
}
try {
return super.asJson();
}finally {
//Reattaching content
if(relazioneScavo!=null) {
relazioneScavo.setRecord(this);
relazioneScavo.reattachContent();
}
if(immaginiRappresentative!=null)
for(UploadedImage img:immaginiRappresentative) {
img.setRecord(this);
img.reattachContent();
}
if(posizionamentoScavo!=null) {
posizionamentoScavo.setRecord(this);
posizionamentoScavo.reattachContent();
}
if(pianteFineScavo!=null)
for(LayerConcessione l:pianteFineScavo) {
l.setRecord(this);
l.reattachContent();
}
if(genericContent!=null)
for(OtherContent o:genericContent) {
o.setRecord(this);
o.reattachContent();
}
}
}
@Override
public ValidationReport validate() {
ValidationReport validator= super.validate();
validator.setObjectName("Concessione");
setPolicy(AccessPolicy.OPEN);
validator.checkMandatory(authors, "Lista Autori");
if(validator.checkMandatory(centroidLat, "Latitudine"))
if(centroidLat>90||centroidLat<-90) validator.addMessage(ValidationStatus.ERROR, "Latitudine non valida : "+centroidLat);
if(validator.checkMandatory(centroidLong, "Longitudine"))
if(centroidLong>180||centroidLong<-180) validator.addMessage(ValidationStatus.ERROR, "Longitudine non valida : "+centroidLong);
validator.checkMandatory(contributore, "Contributore");
if(validator.checkMandatory(dataFineProgetto, "Data Fine Progetto") &&
validator.checkMandatory(dataInizioProgetto, "Data Inizio Progetto"))
if(dataFineProgetto.isBefore(dataInizioProgetto)) validator.addMessage(ValidationStatus.ERROR, "Data Fine Progetto non può esser prima di Data Inizio Progetto.");
validator.checkMandatory(descrizioneContenuto, "Descrizione contenuto");
validator.checkMandatory(editore, "Editore");
validator.checkMandatory(fontiFinanziamento, "Fonti Finanaziamento");
validator.checkMandatory(introduzione, "Introduzione");
validator.checkMandatory(paroleChiaveICCD, "Parole chiave ICCD");
validator.checkMandatory(paroleChiaveLibere, "Parole chiave libere");
validator.checkMandatory(responsabile,"Responsabile");
validator.checkMandatory(titolareCopyright, "Titolare Copyright");
validator.checkMandatory(titolareLicenza,"Titolare licenza");
validator.checkMandatory(titolari, "Titolari");
if(validator.checkMandatory(relazioneScavo, "Relazione scavo")) {
validator.addChild(relazioneScavo.validateForInsertion());
}
// if(immaginiRappresentative!=null)
//
// for(UploadedImage img : immaginiRappresentative) {
// validator.setDefault(img.getSoggetto(),getSoggetto());
// validator.setDefault(img.getCreationTime(),getCreationTime());
// validator.setDefault(img.getPolicy(), getPolicy());
// validator.setDefault(img.getLicenzaID(), getLicenzaID());
//
// validator.addChild(img.validateForInsertion());
// }
//
if(validator.checkMandatory(posizionamentoScavo, "Posizionamento scavo")) {
ValidationReport posReport=posizionamentoScavo.validateForInsertion();
posReport.setObjectName("Posizionamento scavo");
validator.addChild(posReport);
}
if(genericContent!=null)
for(OtherContent content:genericContent)
validator.addChild(content.validateForInsertion());
if(validator.checkMandatory(pianteFineScavo,"Piante fine scavo"))
for(LayerConcessione l:pianteFineScavo) {
validator.addChild(l.validateForInsertion());
}
return validator;
}
@Override
public void setDefaults() {
super.setDefaults();
setSoggetto(ConstraintCheck.defaultFor(soggetto, Arrays.asList(new String[] {"Research Excavation","Archaeology"}))
.addChecks(Check.collectionSizeMin(2)).evaluate());
if(relazioneScavo!=null) {
relazioneScavo.setTitolo(ConstraintCheck.defaultFor(relazioneScavo.getTitolo(),getNome()+" relazione di scavo").evaluate());
relazioneScavo.setSoggetto(ConstraintCheck.defaultFor(relazioneScavo.getSoggetto(),getSoggetto()).evaluate());
relazioneScavo.setCreationTime(ConstraintCheck.defaultFor(relazioneScavo.getCreationTime(),getCreationTime()).evaluate());
relazioneScavo.setLicenseID(getLicenzaID());
relazioneScavo.setPolicy(getPolicy());
}
if(immaginiRappresentative!=null)
for(UploadedImage img : immaginiRappresentative) {
img.setSoggetto(ConstraintCheck.defaultFor(img.getSoggetto(),getSoggetto()).evaluate());
img.setCreationTime(ConstraintCheck.defaultFor(img.getCreationTime(),getCreationTime()).evaluate());
img.setPolicy(ConstraintCheck.defaultFor(img.getPolicy(),getPolicy()).evaluate());
img.setLicenseID(ConstraintCheck.defaultFor(img.getLicenseID(),getLicenzaID()).evaluate());
}
if(posizionamentoScavo!=null) {
posizionamentoScavo.setTitolo(ConstraintCheck.defaultFor(posizionamentoScavo.getTitolo(), getNome()+" posizionamento scavo").evaluate());
posizionamentoScavo.setAbstractSection(
ConstraintCheck.defaultFor(posizionamentoScavo.getAbstractSection(),"Posizionamento topografico georeferenziato dellarea interessata dalle indagini").evaluate());
posizionamentoScavo.setTopicCategory(ConstraintCheck.defaultFor(posizionamentoScavo.getTopicCategory(), "Society").evaluate());
posizionamentoScavo.setSubTopic(ConstraintCheck.defaultFor(posizionamentoScavo.getSubTopic(), "Archeology").evaluate());
posizionamentoScavo.setParoleChiaveLibere(ConstraintCheck.defaultFor(posizionamentoScavo.getParoleChiaveLibere(),getParoleChiaveLibere()).evaluate());
posizionamentoScavo.setParoleChiaveICCD(ConstraintCheck.defaultFor(posizionamentoScavo.getParoleChiaveICCD(),getParoleChiaveICCD()).evaluate());
//TODO Evaluate
posizionamentoScavo.setBbox(ConstraintCheck.defaultFor(posizionamentoScavo.getBbox(), BBOX.WORLD_EXTENT).evaluate());
posizionamentoScavo.setPolicy(ConstraintCheck.defaultFor(posizionamentoScavo.getPolicy(),getPolicy()).evaluate());;
posizionamentoScavo.setLicenseID("CC-BY");
posizionamentoScavo.setResponsabile(getResponsabile());
posizionamentoScavo.setCreationTime(ConstraintCheck.defaultFor(posizionamentoScavo.getCreationTime(), getCreationTime()).evaluate());
}
if(pianteFineScavo!=null)
for(LayerConcessione l:pianteFineScavo) {
l.setTitolo(ConstraintCheck.defaultFor(l.getTitolo(), getNome()+" pianta fine scavo").evaluate());
l.setAbstractSection(
ConstraintCheck.defaultFor(l.getAbstractSection(),"Planimetria georeferenziata dell'area indagata al termine delle attività").evaluate());
l.setTopicCategory(ConstraintCheck.defaultFor(l.getTopicCategory(), "Society").evaluate());
l.setSubTopic(ConstraintCheck.defaultFor(l.getSubTopic(), "Archeology").evaluate());
l.setParoleChiaveLibere(ConstraintCheck.defaultFor(l.getParoleChiaveLibere(),getParoleChiaveLibere()).evaluate());
l.setParoleChiaveICCD(ConstraintCheck.defaultFor(l.getParoleChiaveICCD(),getParoleChiaveICCD()).evaluate());
//TODO Evaluate
l.setBbox(ConstraintCheck.defaultFor(l.getBbox(), BBOX.WORLD_EXTENT).evaluate());
l.setPolicy(ConstraintCheck.defaultFor(l.getPolicy(),getPolicy()).evaluate());;
l.setLicenseID(ConstraintCheck.defaultFor(l.getLicenseID(), "CC-BY").evaluate());
l.setResponsabile(getResponsabile());
l.setCreationTime(ConstraintCheck.defaultFor(l.getCreationTime(), getCreationTime()).evaluate());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
// result = prime * result + ((authors == null) ? 0 : authors.hashCode());
result = prime * result + CollectionsUtils.hashCode(authors);
// result = prime * result + ((fontiFinanaziamento == null) ? 0 : fontiFinanaziamento.hashCode());
result = prime * result + CollectionsUtils.hashCode(fontiFinanziamento);
// result = prime * result + ((immaginiRappresentative == null) ? 0 : immaginiRappresentative.hashCode());
result = prime * result + CollectionsUtils.hashCode(immaginiRappresentative);
// result = prime * result + ((paroleChiaveICCD == null) ? 0 : paroleChiaveICCD.hashCode());
result = prime * result + CollectionsUtils.hashCode(paroleChiaveICCD);
// result = prime * result + ((paroleChiaveLibere == null) ? 0 : paroleChiaveLibere.hashCode());
result = prime * result + CollectionsUtils.hashCode(paroleChiaveLibere);
// result = prime * result + ((pianteFineScavo == null) ? 0 : pianteFineScavo.hashCode());
result = prime * result + CollectionsUtils.hashCode(pianteFineScavo);
// result = prime * result + ((risorseCorrelate == null) ? 0 : risorseCorrelate.hashCode());
result = prime * result + CollectionsUtils.hashCode(risorseCorrelate);
// result = prime * result + ((soggetto == null) ? 0 : soggetto.hashCode());
result = prime * result + CollectionsUtils.hashCode(soggetto);
// result = prime * result + ((titolari == null) ? 0 : titolari.hashCode());
result = prime * result + CollectionsUtils.hashCode(titolari);
result = prime * result + ((centroidLat == null) ? 0 : centroidLat.hashCode());
result = prime * result + ((centroidLong == null) ? 0 : centroidLong.hashCode());
result = prime * result + ((contributore == null) ? 0 : contributore.hashCode());
result = prime * result + ((dataFineProgetto == null) ? 0 : dataFineProgetto.hashCode());
result = prime * result + ((dataInizioProgetto == null) ? 0 : dataInizioProgetto.hashCode());
result = prime * result + ((descrizioneContenuto == null) ? 0 : descrizioneContenuto.hashCode());
result = prime * result + ((editore == null) ? 0 : editore.hashCode());
result = prime * result + ((genericContent == null) ? 0 : genericContent.hashCode());
result = prime * result + ((introduzione == null) ? 0 : introduzione.hashCode());
result = prime * result + ((posizionamentoScavo == null) ? 0 : posizionamentoScavo.hashCode());
result = prime * result + ((relazioneScavo == null) ? 0 : relazioneScavo.hashCode());
result = prime * result + ((responsabile == null) ? 0 : responsabile.hashCode());
result = prime * result + ((titolareCopyright == null) ? 0 : titolareCopyright.hashCode());
result = prime * result + ((titolareLicenza == null) ? 0 : titolareLicenza.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Concessione other = (Concessione) obj;
// if (authors == null) {
// if (other.authors != null)
// return false;
// } else if (!authors.equals(other.authors))
// return false;
if(!CollectionsUtils.equalsCollections(authors, other.authors)) return false;
// if (fontiFinanaziamento == null) {
// if (other.fontiFinanaziamento != null)
// return false;
// } else if (!fontiFinanaziamento.equals(other.fontiFinanaziamento))
// return false;
if (!CollectionsUtils.equalsCollections(fontiFinanziamento, other.fontiFinanziamento)) return false;
// if (immaginiRappresentative == null) {
// if (other.immaginiRappresentative != null)
// return false;
// } else if (!immaginiRappresentative.equals(other.immaginiRappresentative))
// return false;
if (!CollectionsUtils.equalsCollections(immaginiRappresentative, other.immaginiRappresentative)) return false;
// if (paroleChiaveICCD == null) {
// if (other.paroleChiaveICCD != null)
// return false;
// } else if (!paroleChiaveICCD.equals(other.paroleChiaveICCD))
// return false;
if (!CollectionsUtils.equalsCollections(paroleChiaveICCD, other.paroleChiaveICCD)) return false;
// if (paroleChiaveLibere == null) {
// if (other.paroleChiaveLibere != null)
// return false;
// } else if (!paroleChiaveLibere.equals(other.paroleChiaveLibere))
// return false;
if (!CollectionsUtils.equalsCollections(paroleChiaveLibere, other.paroleChiaveLibere)) return false;
// if (piantaFineScavo == null) {
// if (other.piantaFineScavo != null)
// return false;
// } else if (!piantaFineScavo.equals(other.piantaFineScavo))
// return false;
if (!CollectionsUtils.equalsCollections(pianteFineScavo, other.pianteFineScavo)) return false;
// if (risorseCorrelate == null) {
// if (other.risorseCorrelate != null)
// return false;
// } else if (!risorseCorrelate.equals(other.risorseCorrelate))
// return false;
if (!CollectionsUtils.equalsCollections(risorseCorrelate, other.risorseCorrelate)) return false;
// if (soggetto == null) {
// if (other.soggetto != null)
// return false;
// } else if (!soggetto.equals(other.soggetto))
// return false;
if (!CollectionsUtils.equalsCollections(soggetto, other.soggetto)) return false;
// if (titolari == null) {
// if (other.titolari != null)
// return false;
// } else if (!titolari.equals(other.titolari))
// return false;
if (!CollectionsUtils.equalsCollections(titolari, other.titolari)) return false;
if (centroidLat == null) {
if (other.centroidLat != null)
return false;
} else if (!centroidLat.equals(other.centroidLat))
return false;
if (centroidLong == null) {
if (other.centroidLong != null)
return false;
} else if (!centroidLong.equals(other.centroidLong))
return false;
if (contributore == null) {
if (other.contributore != null)
return false;
} else if (!contributore.equals(other.contributore))
return false;
if (dataFineProgetto == null) {
if (other.dataFineProgetto != null)
return false;
} else if (!dataFineProgetto.equals(other.dataFineProgetto))
return false;
if (dataInizioProgetto == null) {
if (other.dataInizioProgetto != null)
return false;
} else if (!dataInizioProgetto.equals(other.dataInizioProgetto))
return false;
if (descrizioneContenuto == null) {
if (other.descrizioneContenuto != null)
return false;
} else if (!descrizioneContenuto.equals(other.descrizioneContenuto))
return false;
if (editore == null) {
if (other.editore != null)
return false;
} else if (!editore.equals(other.editore))
return false;
if (genericContent == null) {
if (other.genericContent != null)
return false;
} else if (!genericContent.equals(other.genericContent))
return false;
if (introduzione == null) {
if (other.introduzione != null)
return false;
} else if (!introduzione.equals(other.introduzione))
return false;
if (posizionamentoScavo == null) {
if (other.posizionamentoScavo != null)
return false;
} else if (!posizionamentoScavo.equals(other.posizionamentoScavo))
return false;
if (relazioneScavo == null) {
if (other.relazioneScavo != null)
return false;
} else if (!relazioneScavo.equals(other.relazioneScavo))
return false;
if (responsabile == null) {
if (other.responsabile != null)
return false;
} else if (!responsabile.equals(other.responsabile))
return false;
if (titolareCopyright == null) {
if (other.titolareCopyright != null)
return false;
} else if (!titolareCopyright.equals(other.titolareCopyright))
return false;
if (titolareLicenza == null) {
if (other.titolareLicenza != null)
return false;
} else if (!titolareLicenza.equals(other.titolareLicenza))
return false;
return true;
}
}

View File

@ -0,0 +1,35 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString(callSuper=true)
@Entity
@DiscriminatorValue("GEOSERVER")
@EqualsAndHashCode(callSuper=true)
public class GeoServerContent extends PersistedContent{
//GeoServer Details
private String geoserverHostName;
private String geoserverPath;
@ElementCollection(targetClass=String.class)
private List<String> fileNames=new ArrayList<String>();
private String workspace;
private String store;
private String featureType;
}

View File

@ -0,0 +1,199 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.utils.CollectionsUtils;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString(callSuper=true)
@Entity
@DiscriminatorValue("LAYER_CONCESSIONE")
public class LayerConcessione extends SDILayerDescriptor{
//1.Identificazione
private String abstractSection;
//2.Classificazione
private String topicCategory;
//3.Keyword
private String subTopic;
//4. Delimitazione geographica
private BBOX bbox;
//5. Temporal
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> paroleChiaveLibere;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> paroleChiaveICCD;
//6. Quality
private String valutazioneQualita;
private String metodoRaccoltaDati;
private String scalaAcquisizione;
//8. Responsabili
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> authors;
private String responsabile;
@ManyToOne
@JoinColumn(name="record_id", nullable=false)
private Record record;
@Override
public ValidationReport validateForInsertion() {
ValidationReport toReturn=super.validateForInsertion();
toReturn.setObjectName("Layer Concessione");
toReturn.checkMandatory(abstractSection, "Abstract");
toReturn.checkMandatory(subTopic, "Categoria (Topic)");
//TODO
// toReturn.checkMandatory(bbox, "Bounding Box");
toReturn.checkMandatory(valutazioneQualita, "Valutazione della qualita");
toReturn.checkMandatory(metodoRaccoltaDati, "Metodo raccolta dati");
toReturn.checkMandatory(scalaAcquisizione, "Scala acquisizione");
toReturn.checkMandatory(authors, "Autori");
return toReturn;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((abstractSection == null) ? 0 : abstractSection.hashCode());
// result = prime * result + ((authors == null) ? 0 : authors.hashCode());
result = prime * result + CollectionsUtils.hashCode(authors);
result = prime * result + ((bbox == null) ? 0 : bbox.hashCode());
result = prime * result + ((metodoRaccoltaDati == null) ? 0 : metodoRaccoltaDati.hashCode());
result = prime * result + ((scalaAcquisizione == null) ? 0 : scalaAcquisizione.hashCode());
result = prime * result + ((subTopic == null) ? 0 : subTopic.hashCode());
result = prime * result + ((topicCategory == null) ? 0 : topicCategory.hashCode());
result = prime * result + ((valutazioneQualita == null) ? 0 : valutazioneQualita.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
LayerConcessione other = (LayerConcessione) obj;
if (abstractSection == null) {
if (other.abstractSection != null)
return false;
} else if (!abstractSection.equals(other.abstractSection))
return false;
// if (authors == null) {
// if (other.authors != null)
// return false;
// } else if (!authors.equals(other.authors))
// return false;
if(!CollectionsUtils.equalsCollections(authors, other.authors)) return false;
if (bbox == null) {
if (other.bbox != null)
return false;
} else if (!bbox.equals(other.bbox))
return false;
if (metodoRaccoltaDati == null) {
if (other.metodoRaccoltaDati != null)
return false;
} else if (!metodoRaccoltaDati.equals(other.metodoRaccoltaDati))
return false;
if (scalaAcquisizione == null) {
if (other.scalaAcquisizione != null)
return false;
} else if (!scalaAcquisizione.equals(other.scalaAcquisizione))
return false;
if (subTopic == null) {
if (other.subTopic != null)
return false;
} else if (!subTopic.equals(other.subTopic))
return false;
if (topicCategory == null) {
if (other.topicCategory != null)
return false;
} else if (!topicCategory.equals(other.topicCategory))
return false;
if (valutazioneQualita == null) {
if (other.valutazioneQualita != null)
return false;
} else if (!valutazioneQualita.equals(other.valutazioneQualita))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("LayerConcessione [abstractSection=");
builder.append(abstractSection);
builder.append(", topicCategory=");
builder.append(topicCategory);
builder.append(", subTopic=");
builder.append(subTopic);
builder.append(", bbox=");
builder.append(bbox);
builder.append(", paroleChiaveLibere=");
builder.append(paroleChiaveLibere);
builder.append(", paroleChiaveICCD=");
builder.append(paroleChiaveICCD);
builder.append(", valutazioneQualita=");
builder.append(valutazioneQualita);
builder.append(", metodoRaccoltaDati=");
builder.append(metodoRaccoltaDati);
builder.append(", scalaAcquisizione=");
builder.append(scalaAcquisizione);
builder.append(", authors=");
builder.append(authors);
builder.append(", responsabile=");
builder.append(responsabile);
if(record!=null) {
builder.append(", owner-record-id=");
builder.append(record.getId());
}else {
builder.append(", record=");
builder.append(record);
}
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,47 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.gcube.application.geoportal.model.Record;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@DiscriminatorValue("OTHER")
public class OtherContent extends AssociatedContent {
@ManyToOne
@JoinColumn(name="record_id", nullable=false)
public Record record;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("OtherContent [");
if(record!=null) {
builder.append(", owner-record-id=");
builder.append(record.getId());
}else {
builder.append(", record=");
builder.append(record);
}
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,58 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@EqualsAndHashCode
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = GeoServerContent.class),
@Type(value = WorkspaceContent.class),
})
public abstract class PersistedContent {
//Generic Info
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name="content_id", nullable=false)
private AssociatedContent associated;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PersistedContent [id=");
builder.append(id);
if(associated==null) {
builder.append(", associated=");
builder.append(associated);
}else {
builder.append(", OWNER-associated-id=");
builder.append(associated.getId());
}
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,119 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.model.report.ValidationReport;
import org.gcube.application.geoportal.utils.CollectionsUtils;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@DiscriminatorValue("RELAZIONE")
public class RelazioneScavo extends AssociatedContent {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RelazioneScavo [abstractSection=");
builder.append(abstractSection);
if(record!=null) {
builder.append(", owner-record-id=");
builder.append(record.getId());
}else {
builder.append(", record=");
builder.append(record);
}
builder.append(", responsabili=");
builder.append(responsabili);
builder.append(", soggetto=");
builder.append(soggetto);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
private String abstractSection;
@ManyToOne
@JoinColumn(name="record_id", nullable=false)
private Record record;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> responsabili;
@LazyCollection(LazyCollectionOption.FALSE)
@ElementCollection(targetClass=String.class)
private List<String> soggetto;
@Override
public ValidationReport validateForInsertion() {
ValidationReport toReturn=super.validateForInsertion();
toReturn.setObjectName("Relazione Scavo");
toReturn.checkMandatory(responsabili, "Responsabili");
toReturn.checkMandatory(soggetto, "Soggetto");
return toReturn;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((abstractSection == null) ? 0 : abstractSection.hashCode());
// result = prime * result + ((responsabili == null) ? 0 : responsabili.hashCode());
result = prime * result + CollectionsUtils.hashCode(responsabili);
// result = prime * result + ((soggetto == null) ? 0 : soggetto.hashCode());
result = prime * result + CollectionsUtils.hashCode(soggetto);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
RelazioneScavo other = (RelazioneScavo) obj;
if (abstractSection == null) {
if (other.abstractSection != null)
return false;
} else if (!abstractSection.equals(other.abstractSection))
return false;
// if (responsabili == null) {
// if (other.responsabili != null)
// return false;
// } else if (!responsabili.equals(other.responsabili))
// return false;
if(!CollectionsUtils.equalsCollections(responsabili, other.responsabili)) return false;
// if (soggetto == null) {
// if (other.soggetto != null)
// return false;
// } else if (!soggetto.equals(other.soggetto))
// return false;
if(!CollectionsUtils.equalsCollections(soggetto, other.soggetto)) return false;
return true;
}
}

View File

@ -0,0 +1,29 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class SDILayerDescriptor extends AssociatedContent{
//meta
private String layerUUID;
private Long layerID;
//layer
private String layerName;
private String wmsLink;
}

View File

@ -0,0 +1,112 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import java.util.List;
import javax.persistence.DiscriminatorValue;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.gcube.application.geoportal.model.Record;
import org.gcube.application.geoportal.utils.CollectionsUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Entity
@DiscriminatorValue("IMAGE")
public class UploadedImage extends AssociatedContent {
private String didascalia;
private String format;
@ElementCollection(targetClass=String.class)
private List<String> responsabili;
@ElementCollection(targetClass=String.class)
private List<String> soggetto;
@ManyToOne
@JoinColumn(name="record_id", nullable=false)
private Record record;
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((didascalia == null) ? 0 : didascalia.hashCode());
result = prime * result + ((format == null) ? 0 : format.hashCode());
// result = prime * result + ((responsabili == null) ? 0 : responsabili.hashCode());
result = prime * result + CollectionsUtils.hashCode(responsabili);
// result = prime * result + ((soggetto == null) ? 0 : soggetto.hashCode());
result = prime * result + CollectionsUtils.hashCode(soggetto);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
UploadedImage other = (UploadedImage) obj;
if (didascalia == null) {
if (other.didascalia != null)
return false;
} else if (!didascalia.equals(other.didascalia))
return false;
if (format == null) {
if (other.format != null)
return false;
} else if (!format.equals(other.format))
return false;
// if (responsabili == null) {
// if (other.responsabili != null)
// return false;
// } else if (!responsabili.equals(other.responsabili))
// return false;
if(!CollectionsUtils.equalsCollections(responsabili, other.responsabili)) return false;
// if (soggetto == null) {
// if (other.soggetto != null)
// return false;
// } else if (!soggetto.equals(other.soggetto))
// return false;
if(!CollectionsUtils.equalsCollections(soggetto, other.soggetto)) return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UploadedImage [didascalia=");
builder.append(didascalia);
builder.append(", format=");
builder.append(format);
builder.append(", responsabili=");
builder.append(responsabili);
builder.append(", soggetto=");
builder.append(soggetto);
if(record!=null) {
builder.append(", owner-record-id=");
builder.append(record.getId());
}else {
builder.append(", record=");
builder.append(record);
}
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,23 @@
package org.gcube.application.geoportal.service.model.legacy.concessioni;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString(callSuper=true)
@Entity
@DiscriminatorValue("WORKSPACE")
@EqualsAndHashCode(callSuper=true)
public class WorkspaceContent extends PersistedContent{
private String mimetype;
private String storageID;
private String link;
}

View File

@ -11,19 +11,20 @@ import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.application.geoportal.managers.ConcessioneManager;
import org.gcube.application.geoportal.managers.ManagerFactory;
import org.gcube.application.geoportal.model.InputStreamDescriptor;
import org.gcube.application.geoportal.model.concessioni.Concessione;
import org.gcube.application.geoportal.model.concessioni.LayerConcessione;
import org.gcube.application.geoportal.model.concessioni.RelazioneScavo;
import org.gcube.application.geoportal.model.content.UploadedImage;
import org.gcube.application.geoportal.model.report.PublicationReport;
import org.gcube.application.geoportal.service.engine.ImplementationProvider;
import org.gcube.application.geoportal.service.engine.StorageClientProvider;
import org.gcube.application.geoportal.service.engine.legacy.LegacyConcessioniManager;
import org.gcube.application.geoportal.service.model.internal.rest.AddSectionToConcessioneRequest;
import org.gcube.application.geoportal.service.model.internal.rest.AddSectionToConcessioneRequest.SHUBFileDescriptor;
import org.gcube.application.geoportal.service.model.legacy.concessioni.Concessione;
import org.gcube.application.geoportal.service.model.legacy.concessioni.LayerConcessione;
import org.gcube.application.geoportal.service.model.legacy.concessioni.RelazioneScavo;
import org.gcube.application.geoportal.service.model.legacy.concessioni.UploadedImage;
import org.gcube.application.geoportal.service.utils.Serialization;
import org.json.JSONArray;
@ -42,8 +43,8 @@ public class Concessioni {
public String publish(@PathParam(InterfaceConstants.Parameters.PROJECT_ID) String id) {
try {
log.info("Publishing Concessione by id {} ",id);
Concessione conc=(Concessione) ConcessioneManager.getByID(Long.parseLong(id));
ConcessioneManager manager=ManagerFactory.getByRecord(conc);
Concessione conc=(Concessione) LegacyConcessioniManager.getByID(Long.parseLong(id));
LegacyConcessioniManager manager=new LegacyConcessioniManager(conc);
log.debug("Loaded object {} ",conc);
PublicationReport rep=manager.commitSafely(true);
@ -66,7 +67,7 @@ public class Concessioni {
public String getById(@PathParam(InterfaceConstants.Parameters.PROJECT_ID) String id) {
try {
log.info("Loading Concessione by id {} ",id);
Concessione toReturn=(Concessione) ConcessioneManager.getByID(Long.parseLong(id));
Concessione toReturn=(Concessione) LegacyConcessioniManager.getByID(Long.parseLong(id));
log.debug("Loaded object {} ",toReturn);
return toReturn.asJson();
}catch(WebApplicationException e){
@ -85,7 +86,7 @@ public class Concessioni {
try {
log.info("Registering new Concessione "+toRegister);
Concessione conc=Serialization.read(toRegister, Concessione.class);
ConcessioneManager manager=ManagerFactory.registerNew(conc);
LegacyConcessioniManager manager=new LegacyConcessioniManager(conc);
manager.commitSafely(false);
return manager.getRecord().asJson();
}catch(WebApplicationException e){
@ -105,8 +106,8 @@ public class Concessioni {
AddSectionToConcessioneRequest request) {
try {
log.info("Adding section to Concessione {} ",id);
Concessione toReturn=(Concessione) ConcessioneManager.getByID(Long.parseLong(id));
ConcessioneManager manager=ManagerFactory.getByRecord(toReturn);
Concessione toReturn=(Concessione) LegacyConcessioniManager.getByID(Long.parseLong(id));
LegacyConcessioniManager manager=new LegacyConcessioniManager(toReturn);
log.debug("Loaded object {} ",toReturn);
log.debug("Request is {}",request);
@ -120,18 +121,18 @@ public class Concessioni {
}
switch(request.getSection()) {
case PIANTA :manager.addPiantaFineScavo((LayerConcessione) request.getToRegister(),streams);
break;
case POSIZIONAMENTO : manager.setPosizionamento((LayerConcessione) request.getToRegister(),streams);
break;
case RELAZIONE : manager.setRelazioneScavo((RelazioneScavo)request.getToRegister(), streams[0]);
break;
case UPLOADED_IMG : manager.addImmagineRappresentativa((UploadedImage)request.getToRegister(), streams[0]);
break;
default : throw new Exception("Unrecognized section");
}
// switch(request.getSection()) {
// case PIANTA :manager.addPiantaFineScavo((LayerConcessione) request.getToRegister(),streams);
// break;
// case POSIZIONAMENTO : manager.setPosizionamento((LayerConcessione) request.getToRegister(),streams);
// break;
// case RELAZIONE : manager.setRelazioneScavo((RelazioneScavo)request.getToRegister(), streams[0]);
// break;
// case UPLOADED_IMG : manager.addImmagineRappresentativa((UploadedImage)request.getToRegister(), streams[0]);
// break;
// default : throw new Exception("Unrecognized section");
// }
//
// PublicationReport report=manager.commitSafely(false);
Concessione c=manager.commit(false);
log.debug("Published "+c.asJson());
@ -152,7 +153,7 @@ public class Concessioni {
@Produces(MediaType.APPLICATION_JSON)
public String getList(){
try {
Collection<Concessione> toReturn=ManagerFactory.getList(Concessione.class);
Collection<Concessione> toReturn=LegacyConcessioniManager.getListByClass(Concessione.class);
log.debug("Found "+toReturn.size()+" elements..");
JSONArray array=new JSONArray();
for(Concessione found:toReturn) {

View File

@ -1,6 +1,8 @@
package org.gcube.application.geoportal.service.utils;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@ -23,4 +25,19 @@ public class Serialization {
public static String write(Object toWrite) throws JsonProcessingException {
return mapper.writeValueAsString(toWrite);
}
// As DB String
public static String asString(Collection<?> coll) {
if(coll==null||coll.isEmpty()) return "";
StringBuilder builder=new StringBuilder();
for(Object t : coll) {
builder.append(t.toString() +",");
}
return builder.substring(0, builder.lastIndexOf(","));
}
public static final DateTimeFormatter FULL_FORMATTER=DateTimeFormatter.ofPattern("uuuuMMdd_HH-mm-ss");
}

View File

@ -17,8 +17,6 @@ import javax.ws.rs.core.Response;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.application.geoportal.common.utils.Files;
import org.gcube.application.geoportal.managers.AbstractRecordManager;
import org.gcube.application.geoportal.managers.DefatulEMFProvider;
import org.gcube.application.geoportal.model.concessioni.Concessione;
import org.gcube.application.geoportal.model.concessioni.LayerConcessione;
import org.gcube.application.geoportal.model.content.AssociatedContent;
@ -29,6 +27,8 @@ import org.gcube.application.geoportal.model.report.ValidationReport.ValidationS
import org.gcube.application.geoportal.service.GeoPortalService;
import org.gcube.application.geoportal.service.engine.ImplementationProvider;
import org.gcube.application.geoportal.service.engine.StorageClientProvider;
import org.gcube.application.geoportal.service.engine.legacy.AbstractRecordManager;
import org.gcube.application.geoportal.service.engine.legacy.FixedDefaultProvider;
import org.gcube.application.geoportal.service.model.internal.rest.AddSectionToConcessioneRequest;
import org.gcube.application.geoportal.service.model.internal.rest.AddSectionToConcessioneRequest.SHUBFileDescriptor;
import org.gcube.application.geoportal.service.model.internal.rest.AddSectionToConcessioneRequest.Section;
@ -56,7 +56,7 @@ public class ConcessioniTest extends JerseyTest {
@BeforeClass
public static void init() {
String scope="/gcube/devNext/NextNext";
AbstractRecordManager.setDefaultProvider(new DefatulEMFProvider(){
AbstractRecordManager.setDefaultProvider(new FixedDefaultProvider(){
@Override
public EntityManagerFactory getFactory() {