Compare commits
14 Commits
task_20728
...
master
Author | SHA1 | Date |
---|---|---|
Francesco Mangiacrapa | 5c8e230e70 | |
Francesco Mangiacrapa | e47733cae8 | |
Francesco Mangiacrapa | a883893490 | |
Francesco Mangiacrapa | 8d9e63b560 | |
Francesco Mangiacrapa | 12c1a42138 | |
Francesco Mangiacrapa | 72fd24fc61 | |
Francesco Mangiacrapa | 0335ac8b9c | |
Francesco Mangiacrapa | e17a1cb46d | |
Francesco Mangiacrapa | 1a3a3d6b14 | |
Francesco Mangiacrapa | 478a4c157e | |
Francesco Mangiacrapa | 4b51eacb24 | |
Francesco Mangiacrapa | 50c4829911 | |
Francesco Mangiacrapa | 80e52b7c31 | |
Francesco Mangiacrapa | 666238fc41 |
14
.classpath
14
.classpath
|
@ -11,13 +11,6 @@
|
|||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="test" value="true"/>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
|
||||
<attributes>
|
||||
<attribute name="test" value="true"/>
|
||||
|
@ -34,5 +27,12 @@
|
|||
<attribute name="maven.pomderived" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
|
||||
<attributes>
|
||||
<attribute name="optional" value="true"/>
|
||||
<attribute name="maven.pomderived" value="true"/>
|
||||
<attribute name="test" value="true"/>
|
||||
</attributes>
|
||||
</classpathentry>
|
||||
<classpathentry kind="output" path="target/classes"/>
|
||||
</classpath>
|
||||
|
|
|
@ -1,13 +1,26 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
|
||||
|
||||
<wb-module deploy-name="grsf-manage-widget">
|
||||
|
||||
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
|
||||
|
||||
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
|
||||
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
|
||||
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
|
||||
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/java"/>
|
||||
|
||||
<dependent-module archiveName="grsf-common-library-1.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/grsf-common-library/grsf-common-library">
|
||||
|
||||
<dependency-type>uses</dependency-type>
|
||||
|
||||
</dependent-module>
|
||||
|
||||
<property name="context-root" value="grsf-manage-widget"/>
|
||||
|
||||
<property name="java-output-path" value="/grsf-manage-widget/target/grsf-manage-widget-1.0.0-SNAPSHOT/WEB-INF/classes"/>
|
||||
|
||||
</wb-module>
|
||||
|
||||
</project-modules>
|
||||
|
|
27
CHANGELOG.md
27
CHANGELOG.md
|
@ -4,8 +4,33 @@
|
|||
All notable changes to this project will be documented in this file.
|
||||
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [v1.5.0-SNAPSHOT] - 2021-02-17
|
||||
## [v1.7.0] - 2022-09-27
|
||||
|
||||
#### Enhancements
|
||||
|
||||
- [#23809] Passed to grsf-common-library.2.0.0[-SNAPSHOT]
|
||||
- [#23811#note-6] Passed to GWT_2.9
|
||||
|
||||
## [v1.6.1] - 2022-06-22
|
||||
|
||||
#### Bug fixes
|
||||
|
||||
- [#23549] Fixed serialization issue on the GRSFRecordAlreadyManagedStatusException
|
||||
- [#23561] Fixed Merging Request throws a Null Pointer exception
|
||||
|
||||
## [v1.6.0] - 2022-05-25
|
||||
|
||||
#### Bug fixes
|
||||
|
||||
- [#23408] GRSF Manage widget is buggy
|
||||
|
||||
#### Enhancements
|
||||
|
||||
- [#23407] Social Post: replace the BR tags with new lines
|
||||
|
||||
## [v1.5.0] - 2021-04-12
|
||||
|
||||
[#21153] Upgrade the maven-portal-bom to 3.6.1 version
|
||||
[#20728] Migrate to catalogue-util-library
|
||||
|
||||
|
||||
|
|
10
pom.xml
10
pom.xml
|
@ -13,7 +13,7 @@
|
|||
|
||||
<groupId>org.gcube.portlets.widgets</groupId>
|
||||
<artifactId>grsf-manage-widget</artifactId>
|
||||
<version>1.5.0-SNAPSHOT</version>
|
||||
<version>1.7.0</version>
|
||||
<name>gCube GRSF Manage widget</name>
|
||||
|
||||
<scm>
|
||||
|
@ -24,12 +24,12 @@
|
|||
|
||||
<properties>
|
||||
<!-- Convenience property to set the GWT version -->
|
||||
<gwtVersion>2.7.0</gwtVersion>
|
||||
<gwtVersion>2.9.0</gwtVersion>
|
||||
<!-- <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory> -->
|
||||
<distroDirectory>distro</distroDirectory>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<maven.compiler.source>1.7</maven.compiler.source>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
|
@ -38,7 +38,7 @@
|
|||
<dependency>
|
||||
<groupId>org.gcube.distribution</groupId>
|
||||
<artifactId>maven-portal-bom</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<version>3.6.4</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
@ -78,7 +78,7 @@
|
|||
<dependency>
|
||||
<groupId>org.gcube.data-catalogue</groupId>
|
||||
<artifactId>grsf-common-library</artifactId>
|
||||
<version>[1-0-0, 2-0-0-SNAPSHOT)</version>
|
||||
<version>[2-0-0-SNAPSHOT, 3-0-0-SNAPSHOT)</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
|
|
@ -673,7 +673,7 @@ public class ManageProductWidget extends Composite{
|
|||
for(SimilarGRSFRecord sR: bean.getSimilarGrsfRecords()){
|
||||
if(sR.isSuggestedMerge()){
|
||||
bean.setMergesInvolved(true);
|
||||
report += "\n\t - merge the current record with record '" + sR.getTitle() + " ;";
|
||||
report += "\n\t - merge the current record with record '" + sR.getTitle() + "' ;";
|
||||
report += "\n\t \t- GRSF Name '" + sR.getTitle() + "' ;";
|
||||
report += "\n\t \t- Short Name '" + sR.getShortName() + "' ;";
|
||||
report += "\n\t \t- URL '" + sR.getUrl() + "' ;";
|
||||
|
|
|
@ -44,29 +44,34 @@ import com.liferay.portal.kernel.log.LogFactoryUtil;
|
|||
|
||||
/**
|
||||
* Endpoint for sending update records information to GRSF KnowledgeBase.
|
||||
*
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
*/
|
||||
public class GRSFNotificationService extends RemoteServiceServlet implements GRSFManageWidgetService{
|
||||
public class GRSFNotificationService extends RemoteServiceServlet implements GRSFManageWidgetService {
|
||||
|
||||
private static final long serialVersionUID = -4534905087994875893L;
|
||||
private static final Log logger = LogFactoryUtil.getLog(GRSFNotificationService.class);
|
||||
//private static final Logger logger = LoggerFactory.getLogger(GRSFNotificationService.class);
|
||||
// private static final Logger logger =
|
||||
// LoggerFactory.getLogger(GRSFNotificationService.class);
|
||||
|
||||
/**
|
||||
* Instanciate the ckan util library.
|
||||
* Since it needs the scope, we need to check if it is null or not
|
||||
* @param discoverScope if you want to the discover the utils library in this specified scope
|
||||
* Instanciate the ckan util library. Since it needs the scope, we need to check
|
||||
* if it is null or not
|
||||
*
|
||||
* @param discoverScope if you want to the discover the utils library in this
|
||||
* specified scope
|
||||
* @return DataCatalogue object
|
||||
* @throws Exception
|
||||
*/
|
||||
public DataCatalogue getCatalogue(String discoverScope) throws Exception{
|
||||
public DataCatalogue getCatalogue(String discoverScope) throws Exception {
|
||||
String currentScope = Utils.getCurrentContext(getThreadLocalRequest(), true);
|
||||
DataCatalogue instance = null;
|
||||
try{
|
||||
String scopeInWhichDiscover = discoverScope != null && !discoverScope.isEmpty() ? discoverScope : currentScope;
|
||||
try {
|
||||
String scopeInWhichDiscover = discoverScope != null && !discoverScope.isEmpty() ? discoverScope
|
||||
: currentScope;
|
||||
logger.debug("Discovering ckan utils library into scope " + scopeInWhichDiscover);
|
||||
instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover);
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Unable to retrieve ckan utils. Error was ", e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -74,241 +79,258 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
}
|
||||
|
||||
@Override
|
||||
public ManageProductBean getProductBeanById(String productIdentifier, boolean requestForRevertingMerge) throws Exception {
|
||||
public ManageProductBean getProductBeanById(String productIdentifier, boolean requestForRevertingMerge)
|
||||
throws Exception {
|
||||
|
||||
ManageProductBean toReturn = null;
|
||||
|
||||
// check into user's session first
|
||||
HttpSession httpSession = getThreadLocalRequest().getSession();
|
||||
|
||||
// testing case...
|
||||
if(!Utils.isIntoPortal()){
|
||||
// // testing case...
|
||||
// if(!Utils.isIntoPortal()){
|
||||
//
|
||||
// Thread.sleep(2000);
|
||||
//
|
||||
// toReturn = new ManageProductBean();
|
||||
// toReturn.setCatalogueIdentifier(UUID.randomUUID().toString());
|
||||
// List<ConnectedBean> connectTo = new ArrayList<>();
|
||||
// // these are the records alread connected
|
||||
// connectTo.add(new ConnectedBean(
|
||||
// "uuid-of-a-connected-bean",
|
||||
// "Random description",
|
||||
// "Random shortName",
|
||||
// "Random Title",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-of-a-connected-bean",
|
||||
// "semantic identifier of the record",
|
||||
// "Fishery"
|
||||
// ));
|
||||
// toReturn.setCurrentConnections(connectTo);
|
||||
//
|
||||
// // these are the "suggested connections"
|
||||
// List<ConnectedBean> suggestionsForConnections = new ArrayList<>();
|
||||
// suggestionsForConnections.add(new ConnectedBean(
|
||||
// "uuid-of-a-connected-bean-suggested",
|
||||
// "Random description",
|
||||
// "Random shortName",
|
||||
// "Random Title",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-of-a-connected-bean-suggested",
|
||||
// "semantic identifier of the record suggested for connection",
|
||||
// "Fishery"
|
||||
// ));
|
||||
// toReturn.setSuggestedByKnowledgeBaseConnections(suggestionsForConnections);
|
||||
// toReturn.setDomain("Stock");
|
||||
// toReturn.setCurrentGrsfType("Assessment Unit");
|
||||
// toReturn.setKnowledgeBaseId("91f1e413-dc9f-3b4e-b1c5-0e8560177253");
|
||||
// toReturn.setShortName("Widow rockfish - US West Coast");
|
||||
// toReturn.setShortNameUpdated("Widow rockfish - US West Coast");
|
||||
// toReturn.setTitle("sebastes entomelas FAO 77 FAO 67");
|
||||
// toReturn.setTraceabilityFlag(true);
|
||||
// toReturn.setCurrentStatus(Status.Pending);
|
||||
// toReturn.setSemanticIdentifier("asfis:WRO+fao:67;FAO");
|
||||
// ArrayList<SourceRecord> sources = new ArrayList<SourceRecord>();
|
||||
// sources.add(new SourceRecord("RAM", "http://www.google.it"));
|
||||
// sources.add(new SourceRecord("FIRMS", "http://www.google.it"));
|
||||
// sources.add(new SourceRecord("FishSource", "http://www.google.it"));
|
||||
// toReturn.setSources(sources);
|
||||
// List<SimilarGRSFRecord> similarGrsfRecords = new ArrayList<SimilarGRSFRecord>();
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-1",
|
||||
// "description similar record",
|
||||
// "short name similar record 1",
|
||||
// "title similar record 1",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-1",
|
||||
// "semantic identifier record 1",
|
||||
// "Stock 1"
|
||||
// ));
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-2",
|
||||
// "description similar record",
|
||||
// "short name similar record 2",
|
||||
// "title similar record 2",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-2",
|
||||
// "semantic identifier record 2",
|
||||
// "Stock 2"
|
||||
// ));
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-3",
|
||||
// "description similar record",
|
||||
// "short name similar record 3",
|
||||
// "title similar record 3",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-3",
|
||||
// "semantic identifier record 3",
|
||||
// "Stock 3"
|
||||
// ));
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-4",
|
||||
// "description similar record",
|
||||
// "short name similar record 4",
|
||||
// "title similar record 4",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-4",
|
||||
// "semantic identifier record 4",
|
||||
// "Stock 4"
|
||||
// ));
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-5",
|
||||
// "description similar record",
|
||||
// "short name similar record 5",
|
||||
// "title similar record 5",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-5",
|
||||
// "semantic identifier record 5",
|
||||
// "Stock 5"
|
||||
// ));
|
||||
// similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
// "uuid-similar-record-6",
|
||||
// "description similar record",
|
||||
// "short name similar record 6",
|
||||
// "title similar record 6",
|
||||
// "http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-6",
|
||||
// "semantic identifier record 6",
|
||||
// "Stock 6"
|
||||
// ));
|
||||
// toReturn.setSimilarGrsfRecords(similarGrsfRecords);
|
||||
//
|
||||
// }else{
|
||||
|
||||
Thread.sleep(2000);
|
||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
CkanDataset record = catalogue.getDataset(productIdentifier, username);
|
||||
|
||||
toReturn = new ManageProductBean();
|
||||
toReturn.setCatalogueIdentifier(UUID.randomUUID().toString());
|
||||
List<ConnectedBean> connectTo = new ArrayList<>();
|
||||
// these are the records alread connected
|
||||
connectTo.add(new ConnectedBean(
|
||||
"uuid-of-a-connected-bean",
|
||||
"Random description",
|
||||
"Random shortName",
|
||||
"Random Title",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-of-a-connected-bean",
|
||||
"semantic identifier of the record",
|
||||
"Fishery"
|
||||
));
|
||||
toReturn.setCurrentConnections(connectTo);
|
||||
// it cannot be enabled in this case ...
|
||||
if (record == null)
|
||||
throw new Exception("Unable to retrieve information for the selected record, sorry");
|
||||
else {
|
||||
|
||||
// these are the "suggested connections"
|
||||
List<ConnectedBean> suggestionsForConnections = new ArrayList<>();
|
||||
suggestionsForConnections.add(new ConnectedBean(
|
||||
"uuid-of-a-connected-bean-suggested",
|
||||
"Random description",
|
||||
"Random shortName",
|
||||
"Random Title",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-of-a-connected-bean-suggested",
|
||||
"semantic identifier of the record suggested for connection",
|
||||
"Fishery"
|
||||
));
|
||||
toReturn.setSuggestedByKnowledgeBaseConnections(suggestionsForConnections);
|
||||
toReturn.setDomain("Stock");
|
||||
toReturn.setCurrentGrsfType("Assessment Unit");
|
||||
toReturn.setKnowledgeBaseId("91f1e413-dc9f-3b4e-b1c5-0e8560177253");
|
||||
toReturn.setShortName("Widow rockfish - US West Coast");
|
||||
toReturn.setShortNameUpdated("Widow rockfish - US West Coast");
|
||||
toReturn.setTitle("sebastes entomelas FAO 77 FAO 67");
|
||||
toReturn.setTraceabilityFlag(true);
|
||||
toReturn.setCurrentStatus(Status.Pending);
|
||||
toReturn.setSemanticIdentifier("asfis:WRO+fao:67;FAO");
|
||||
ArrayList<SourceRecord> sources = new ArrayList<SourceRecord>();
|
||||
sources.add(new SourceRecord("RAM", "http://www.google.it"));
|
||||
sources.add(new SourceRecord("FIRMS", "http://www.google.it"));
|
||||
sources.add(new SourceRecord("FishSource", "http://www.google.it"));
|
||||
toReturn.setSources(sources);
|
||||
List<SimilarGRSFRecord> similarGrsfRecords = new ArrayList<SimilarGRSFRecord>();
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-1",
|
||||
"description similar record",
|
||||
"short name similar record 1",
|
||||
"title similar record 1",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-1",
|
||||
"semantic identifier record 1",
|
||||
"Stock 1"
|
||||
));
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-2",
|
||||
"description similar record",
|
||||
"short name similar record 2",
|
||||
"title similar record 2",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-2",
|
||||
"semantic identifier record 2",
|
||||
"Stock 2"
|
||||
));
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-3",
|
||||
"description similar record",
|
||||
"short name similar record 3",
|
||||
"title similar record 3",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-3",
|
||||
"semantic identifier record 3",
|
||||
"Stock 3"
|
||||
));
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-4",
|
||||
"description similar record",
|
||||
"short name similar record 4",
|
||||
"title similar record 4",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-4",
|
||||
"semantic identifier record 4",
|
||||
"Stock 4"
|
||||
));
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-5",
|
||||
"description similar record",
|
||||
"short name similar record 5",
|
||||
"title similar record 5",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-5",
|
||||
"semantic identifier record 5",
|
||||
"Stock 5"
|
||||
));
|
||||
similarGrsfRecords.add(new SimilarGRSFRecord(
|
||||
"uuid-similar-record-6",
|
||||
"description similar record",
|
||||
"short name similar record 6",
|
||||
"title similar record 6",
|
||||
"http://data.d4science.org/ctlg/GRSF_Admin/uuid-similar-record-6",
|
||||
"semantic identifier record 6",
|
||||
"Stock 6"
|
||||
));
|
||||
toReturn.setSimilarGrsfRecords(similarGrsfRecords);
|
||||
logger.debug("Trying to fetch the record....");
|
||||
|
||||
}else{
|
||||
// check it is a grsf record (Source records have a different System Type)
|
||||
Map<String, String> extrasAsMap = record.getExtrasAsHashMap();
|
||||
|
||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
CkanDataset record = catalogue.getDataset(productIdentifier,username);
|
||||
String systemType = extrasAsMap.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
||||
if (systemType == null || systemType.isEmpty() || systemType.equals(Constants.SYSTEM_TYPE_LEGACY_RECORD))
|
||||
throw new NoGRSFRecordException("This is not a GRSF Record");
|
||||
|
||||
// it cannot be enabled in this case ...
|
||||
if(record == null)
|
||||
throw new Exception("Unable to retrieve information for the selected record, sorry");
|
||||
else{
|
||||
boolean isStock = record.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||
.contains(Product_Type.STOCK.getOrigName());
|
||||
|
||||
logger.debug("Trying to fetch the record....");
|
||||
// fetch map for namespaces
|
||||
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
|
||||
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
|
||||
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
|
||||
// check it is a grsf record (Source records have a different System Type)
|
||||
Map<String, String> extrasAsMap = record.getExtrasAsHashMap();
|
||||
// get extras as pairs
|
||||
List<CkanPair> extrasAsPairs = record.getExtras();
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(extrasAsPairs,
|
||||
fieldsNamespacesMap);
|
||||
String catalogueIdentifier = record.getId();
|
||||
String description = record.getNotes();
|
||||
Status status = Status
|
||||
.fromString(extrasWithoutNamespaces.get(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY).get(0));
|
||||
|
||||
String systemType = extrasAsMap.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
||||
if(systemType == null || systemType.isEmpty() || systemType.equals(Constants.SYSTEM_TYPE_FOR_SOURCES_VALUE))
|
||||
throw new NoGRSFRecordException("This is not a GRSF Record");
|
||||
if (status.equals(Status.To_be_Merged) && !requestForRevertingMerge)
|
||||
throw new GRSFRecordAlreadyManagedStatusException(Status.To_be_Merged,
|
||||
"The record is locked due to a merge request in progress!");
|
||||
|
||||
boolean isStock = record.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
|
||||
String uuidKB = extrasWithoutNamespaces.get(Constants.UUID_KB_CUSTOM_KEY).get(0);
|
||||
String grsfDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0);
|
||||
String semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
|
||||
String shortName = extrasWithoutNamespaces.get(Constants.SHORT_NAME_CUSTOM_KEY).get(0);
|
||||
String grsfType = extrasWithoutNamespaces.get(Constants.GRSF_TYPE_CUSTOM_KEY).get(0);
|
||||
String recordUrl = extrasWithoutNamespaces.get(Constants.ITEM_URL_FIELD).get(0);
|
||||
String grsfName = extrasWithoutNamespaces
|
||||
.get(grsfDomain.contains(Product_Type.STOCK.getOrigName()) ? Constants.STOCK_NAME_CUSTOM_KEY
|
||||
: Constants.FISHERY_NAME_CUSTOM_KEY)
|
||||
.get(0);
|
||||
boolean traceabilityFlag = false;
|
||||
try {
|
||||
traceabilityFlag = extrasWithoutNamespaces.get(Constants.TRACEABILITY_FLAG_CUSTOM_KEY).get(0)
|
||||
.equalsIgnoreCase("true");
|
||||
} catch (Exception e) {
|
||||
logger.warn("Unable to fetch traceability flag. Setting it to false", e);
|
||||
}
|
||||
|
||||
// fetch map for namespaces
|
||||
Map<String, String> fieldsNamespacesMap =
|
||||
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
|
||||
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
boolean sdgFlag = false;
|
||||
try {
|
||||
sdgFlag = extrasWithoutNamespaces.get(Constants.SDG_FLAG_CUSTOM_KEY).get(0).equalsIgnoreCase("true");
|
||||
} catch (Exception e) {
|
||||
logger.warn("Unable to fetch sdg flag. Setting it to false", e);
|
||||
}
|
||||
|
||||
// get extras as pairs
|
||||
List<CkanPair> extrasAsPairs = record.getExtras();
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(extrasAsPairs, fieldsNamespacesMap);
|
||||
String catalogueIdentifier = record.getId();
|
||||
String description = record.getNotes();
|
||||
Status status = Status.fromString(extrasWithoutNamespaces.get(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY).get(0));
|
||||
// Get similar GRSF records, if any (each of which should have name,
|
||||
// description, url and id(i.e semantic identifier))
|
||||
List<String> similarGrsfRecordsAsStrings = extrasWithoutNamespaces
|
||||
.containsKey(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY)
|
||||
? extrasWithoutNamespaces.get(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY)
|
||||
: null;
|
||||
|
||||
if(status.equals(Status.To_be_Merged) && !requestForRevertingMerge)
|
||||
throw new GRSFRecordAlreadyManagedStatusException(Status.To_be_Merged, "The record is locked due to a merge request in progress!");
|
||||
|
||||
String uuidKB = extrasWithoutNamespaces.get(Constants.UUID_KB_CUSTOM_KEY).get(0);
|
||||
String grsfDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0);
|
||||
String semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
|
||||
String shortName = extrasWithoutNamespaces.get(Constants.SHORT_NAME_CUSTOM_KEY).get(0);
|
||||
String grsfType = extrasWithoutNamespaces.get(Constants.GRSF_TYPE_CUSTOM_KEY).get(0);
|
||||
String recordUrl = extrasWithoutNamespaces.get(Constants.ITEM_URL_FIELD).get(0);
|
||||
String grsfName = extrasWithoutNamespaces.get(grsfDomain.contains(Product_Type.STOCK.getOrigName()) ? Constants.STOCK_NAME_CUSTOM_KEY : Constants.FISHERY_NAME_CUSTOM_KEY).get(0);
|
||||
boolean traceabilityFlag = false;
|
||||
try{
|
||||
traceabilityFlag = extrasWithoutNamespaces.get(Constants.TRACEABILITY_FLAG_CUSTOM_KEY).get(0).equalsIgnoreCase("true");
|
||||
}catch(Exception e){
|
||||
logger.warn("Unable to fetch traceability flag. Setting it to false", e);
|
||||
}
|
||||
|
||||
boolean sdgFlag = false;
|
||||
try{
|
||||
sdgFlag = extrasWithoutNamespaces.get(Constants.SDG_FLAG_CUSTOM_KEY).get(0).equalsIgnoreCase("true");
|
||||
}catch(Exception e){
|
||||
logger.warn("Unable to fetch sdg flag. Setting it to false", e);
|
||||
}
|
||||
|
||||
// Get similar GRSF records, if any (each of which should have name, description, url and id(i.e semantic identifier))
|
||||
List<String> similarGrsfRecordsAsStrings = extrasWithoutNamespaces.containsKey(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY) ? extrasWithoutNamespaces.get(Constants.SIMILAR_GRSF_RECORDS_CUSTOM_KEY): null;
|
||||
|
||||
List<SimilarGRSFRecord> similarRecords = new ArrayList<SimilarGRSFRecord>(0);
|
||||
if(similarGrsfRecordsAsStrings != null && !similarGrsfRecordsAsStrings.isEmpty()){
|
||||
if(!similarGrsfRecordsAsStrings.get(0).equals(Constants.NO_SIMILAR_GRSF_RECORDS)){
|
||||
for (String similarGRSFRecord : similarGrsfRecordsAsStrings) {
|
||||
similarRecords.add(Utils.similarGRSFRecordFromJson(similarGRSFRecord, catalogue, username, httpSession));
|
||||
}
|
||||
List<SimilarGRSFRecord> similarRecords = new ArrayList<SimilarGRSFRecord>(0);
|
||||
if (similarGrsfRecordsAsStrings != null && !similarGrsfRecordsAsStrings.isEmpty()) {
|
||||
if (!similarGrsfRecordsAsStrings.get(0).equals(Constants.NO_SIMILAR_GRSF_RECORDS)) {
|
||||
for (String similarGRSFRecord : similarGrsfRecordsAsStrings) {
|
||||
similarRecords.add(
|
||||
Utils.similarGRSFRecordFromJson(similarGRSFRecord, catalogue, username, httpSession));
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("SimilarGRSFRecords are " + similarRecords);
|
||||
|
||||
// get connected records (and the proposed ones)
|
||||
List<String> connectedBeanUrls =
|
||||
extrasWithoutNamespaces.containsKey(Constants.CONNECTED_CUSTOM_KEY) ? extrasWithoutNamespaces.get(Constants.CONNECTED_CUSTOM_KEY): null;
|
||||
|
||||
List<ConnectedBean> connectedBeans = new ArrayList<ConnectedBean>(0);
|
||||
if(connectedBeanUrls != null && !connectedBeanUrls.isEmpty()){
|
||||
if(!connectedBeanUrls.get(0).equals(Constants.NO_CONNECTED_RECORDS)){
|
||||
for (String connectedBean : connectedBeanUrls) {
|
||||
ConnectedBean builtBean = Utils.connectedBeanRecordFromUrl(connectedBean, catalogue, username, httpSession);
|
||||
if(builtBean != null)
|
||||
connectedBeans.add(builtBean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Already connected records are " + connectedBeans);
|
||||
|
||||
// get the connections the knowledge base suggests
|
||||
List<ConnectedBean> suggestedConnectionsByKnowledgeBase = new ArrayList<ConnectedBean>(0);
|
||||
List<String> exploitedResourcesUrls = isStock ?
|
||||
extrasWithoutNamespaces.containsKey(Constants.EXPLOITING_FISHERY_CUSTOM_KEY) ?
|
||||
extrasWithoutNamespaces.get(Constants.EXPLOITING_FISHERY_CUSTOM_KEY) : null:
|
||||
extrasWithoutNamespaces.containsKey(Constants.RESOURCES_EXPLOITED_CUSTOM_KEY) ?
|
||||
extrasWithoutNamespaces.get(Constants.RESOURCES_EXPLOITED_CUSTOM_KEY) : null;
|
||||
|
||||
if(exploitedResourcesUrls != null && !exploitedResourcesUrls.isEmpty()){
|
||||
for (String exploited : exploitedResourcesUrls) {
|
||||
ConnectedBean builtBean = Utils.connectedBeanRecordFromUrl(exploited, catalogue, username, httpSession);
|
||||
if(builtBean != null)
|
||||
suggestedConnectionsByKnowledgeBase.add(builtBean);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Knowledge base suggests " + suggestedConnectionsByKnowledgeBase);
|
||||
|
||||
// Get sources
|
||||
List<CkanResource> resources = record.getResources();
|
||||
List<SourceRecord> sources = new ArrayList<SourceRecord>(3);
|
||||
for (CkanResource ckanResource : resources) {
|
||||
if(Sources.getListNames().contains(ckanResource.getName()))
|
||||
sources.add(new SourceRecord(ckanResource.getName(), ckanResource.getUrl()));
|
||||
}
|
||||
|
||||
// set the values
|
||||
toReturn = new ManageProductBean(
|
||||
semanticId, catalogueIdentifier, uuidKB, grsfType,
|
||||
grsfDomain, shortName, description, grsfName,traceabilityFlag, sdgFlag,
|
||||
status, recordUrl, sources, similarRecords,
|
||||
connectedBeans, suggestedConnectionsByKnowledgeBase);
|
||||
|
||||
}
|
||||
|
||||
logger.debug("SimilarGRSFRecords are " + similarRecords);
|
||||
|
||||
// get connected records (and the proposed ones)
|
||||
List<String> connectedBeanUrls = extrasWithoutNamespaces.containsKey(Constants.CONNECTED_CUSTOM_KEY)
|
||||
? extrasWithoutNamespaces.get(Constants.CONNECTED_CUSTOM_KEY)
|
||||
: null;
|
||||
|
||||
List<ConnectedBean> connectedBeans = new ArrayList<ConnectedBean>(0);
|
||||
if (connectedBeanUrls != null && !connectedBeanUrls.isEmpty()) {
|
||||
if (!connectedBeanUrls.get(0).equals(Constants.NO_CONNECTED_RECORDS)) {
|
||||
for (String connectedBean : connectedBeanUrls) {
|
||||
ConnectedBean builtBean = Utils.connectedBeanRecordFromUrl(connectedBean, catalogue, username,
|
||||
httpSession);
|
||||
if (builtBean != null)
|
||||
connectedBeans.add(builtBean);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Already connected records are " + connectedBeans);
|
||||
|
||||
// get the connections the knowledge base suggests
|
||||
List<ConnectedBean> suggestedConnectionsByKnowledgeBase = new ArrayList<ConnectedBean>(0);
|
||||
List<String> exploitedResourcesUrls = isStock
|
||||
? extrasWithoutNamespaces.containsKey(Constants.EXPLOITING_FISHERY_CUSTOM_KEY)
|
||||
? extrasWithoutNamespaces.get(Constants.EXPLOITING_FISHERY_CUSTOM_KEY)
|
||||
: null
|
||||
: extrasWithoutNamespaces.containsKey(Constants.RESOURCES_EXPLOITED_CUSTOM_KEY)
|
||||
? extrasWithoutNamespaces.get(Constants.RESOURCES_EXPLOITED_CUSTOM_KEY)
|
||||
: null;
|
||||
|
||||
if (exploitedResourcesUrls != null && !exploitedResourcesUrls.isEmpty()) {
|
||||
for (String exploited : exploitedResourcesUrls) {
|
||||
ConnectedBean builtBean = Utils.connectedBeanRecordFromUrl(exploited, catalogue, username,
|
||||
httpSession);
|
||||
if (builtBean != null)
|
||||
suggestedConnectionsByKnowledgeBase.add(builtBean);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Knowledge base suggests " + suggestedConnectionsByKnowledgeBase);
|
||||
|
||||
// Get sources
|
||||
List<CkanResource> resources = record.getResources();
|
||||
List<SourceRecord> sources = new ArrayList<SourceRecord>(3);
|
||||
for (CkanResource ckanResource : resources) {
|
||||
if (Sources.listNames().contains(ckanResource.getName()))
|
||||
sources.add(new SourceRecord(ckanResource.getName(), ckanResource.getUrl()));
|
||||
}
|
||||
|
||||
// set the values
|
||||
toReturn = new ManageProductBean(semanticId, catalogueIdentifier, uuidKB, grsfType, grsfDomain, shortName,
|
||||
description, grsfName, traceabilityFlag, sdgFlag, status, recordUrl, sources, similarRecords,
|
||||
connectedBeans, suggestedConnectionsByKnowledgeBase);
|
||||
|
||||
}
|
||||
// }
|
||||
|
||||
logger.debug("Returning item bean " + toReturn);
|
||||
return toReturn;
|
||||
|
@ -316,19 +338,20 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
|
||||
@Override
|
||||
public boolean isAdminUser() {
|
||||
try{
|
||||
Boolean inSession = (Boolean)getThreadLocalRequest().getSession().getAttribute(Constants.GRSF_ADMIN_SESSION_KEY);
|
||||
if(inSession != null)
|
||||
try {
|
||||
Boolean inSession = (Boolean) getThreadLocalRequest().getSession()
|
||||
.getAttribute(Constants.GRSF_ADMIN_SESSION_KEY);
|
||||
if (inSession != null)
|
||||
return inSession;
|
||||
else{
|
||||
else {
|
||||
|
||||
boolean toSetInSession = false;
|
||||
if(!Utils.isIntoPortal()){
|
||||
if (!Utils.isIntoPortal()) {
|
||||
toSetInSession = true;
|
||||
}else{
|
||||
} else {
|
||||
PortalContext pContext = PortalContext.getConfiguration();
|
||||
RoleManager roleManager = new LiferayRoleManager();
|
||||
String username = pContext.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
String username = pContext.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
||||
long groupId = pContext.getCurrentGroupId(getThreadLocalRequest());
|
||||
List<GCubeTeam> teamRolesByUser = roleManager.listTeamsByUserAndGroup(userId, groupId);
|
||||
|
@ -337,21 +360,22 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
getThreadLocalRequest().getSession().setAttribute(Constants.GRSF_ADMIN_SESSION_KEY, toSetInSession);
|
||||
return toSetInSession;
|
||||
}
|
||||
}catch(Exception e){
|
||||
logger.error("Failed to check if the user belongs to team " + Constants.GRSF_CATALOGUE_EDITOR_ROLE + " or " + Constants.GRSF_CATALOGUE_REVIEWER_ROLE +"!", e);
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to check if the user belongs to team " + Constants.GRSF_CATALOGUE_EDITOR_ROLE + " or "
|
||||
+ Constants.GRSF_CATALOGUE_REVIEWER_ROLE + "!", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void notifyProductUpdate(ManageProductBean bean) throws Exception{
|
||||
public void notifyProductUpdate(ManageProductBean bean) throws Exception {
|
||||
|
||||
logger.info("Creating notification for the bean " + bean + " to send to the knowledge base");
|
||||
if(!Utils.isIntoPortal()){
|
||||
if (!Utils.isIntoPortal()) {
|
||||
Thread.sleep(2500);
|
||||
return;
|
||||
}
|
||||
try{
|
||||
try {
|
||||
|
||||
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
String token = SecurityTokenProvider.instance.get();
|
||||
|
@ -360,10 +384,11 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
|
||||
// check if the base url of the service is in session
|
||||
String keyPerContext = CatalogueUtilMethods.concatenateSessionKeyScope(Constants.GRSF_UPDATER_SERVICE, context);
|
||||
String keyPerContext = CatalogueUtilMethods.concatenateSessionKeyScope(Constants.GRSF_UPDATER_SERVICE,
|
||||
context);
|
||||
HttpServletRequest threadRequest = getThreadLocalRequest();
|
||||
String baseUrl = (String)threadRequest.getSession().getAttribute(keyPerContext);
|
||||
if(baseUrl == null || baseUrl.isEmpty()){
|
||||
String baseUrl = (String) threadRequest.getSession().getAttribute(keyPerContext);
|
||||
if (baseUrl == null || baseUrl.isEmpty()) {
|
||||
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
||||
threadRequest.getSession().setAttribute(keyPerContext, baseUrl);
|
||||
}
|
||||
|
@ -375,7 +400,7 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
Utils.updateRecord(baseUrl, bean, catalogue, username, administratorFullName, threadRequest,
|
||||
PortalContext.getConfiguration().getCurrentGroupId(threadRequest), context, token);
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Unable to update the product", e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -384,13 +409,13 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
@Override
|
||||
public RevertableOperationInfo validateRevertOperation(String encryptedUrl) throws Exception {
|
||||
|
||||
if(!Utils.isIntoPortal()){
|
||||
if (!Utils.isIntoPortal()) {
|
||||
Thread.sleep(2000);
|
||||
|
||||
// random result
|
||||
boolean throwException = Math.random() > 0.5;
|
||||
|
||||
if(throwException)
|
||||
if (throwException)
|
||||
throw new Exception("Unable to parse the inserted url");
|
||||
|
||||
String baseUrl = "url of the record here";
|
||||
|
@ -399,15 +424,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
String uuid = UUID.randomUUID().toString();
|
||||
String adminInUrl = "costantino.perciante";
|
||||
String adminInUrlFullName = "Costantino Perciante";
|
||||
long timestamp = System.currentTimeMillis() - 1000 * (long)(Math.random() * 10 * 60 * 60);
|
||||
return new RevertableOperationInfo(
|
||||
baseUrl, fullName, usernameCurrent, uuid, adminInUrlFullName, adminInUrl, timestamp, RevertableOperations.MERGE);
|
||||
long timestamp = System.currentTimeMillis() - 1000 * (long) (Math.random() * 10 * 60 * 60);
|
||||
return new RevertableOperationInfo(baseUrl, fullName, usernameCurrent, uuid, adminInUrlFullName, adminInUrl,
|
||||
timestamp, RevertableOperations.MERGE);
|
||||
}
|
||||
|
||||
PortalContext pContext = PortalContext.getConfiguration();
|
||||
String context = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
RoleManager roleManager = new LiferayRoleManager();
|
||||
GCubeUser user = pContext.getCurrentUser(getThreadLocalRequest());
|
||||
GCubeUser user = pContext.getCurrentUser(getThreadLocalRequest());
|
||||
String username = user.getUsername();
|
||||
String fullName = user.getFullname();
|
||||
long userId = pContext.getCurrentUser(getThreadLocalRequest()).getUserId();
|
||||
|
@ -417,21 +442,25 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
boolean isEditor = isEditor(username, teamRolesByUser);
|
||||
boolean isReviewer = isReviewer(username, teamRolesByUser);
|
||||
|
||||
if(!(isEditor | isReviewer))
|
||||
if (!(isEditor | isReviewer))
|
||||
throw new Exception("You are not allowed to perform this operation. You must be an editor or a reviewer!");
|
||||
|
||||
// decrypt the url
|
||||
RevertOperationUrl decryptedUrl = new RevertOperationUrl(encryptedUrl);
|
||||
String userNameadminInUrl = decryptedUrl.getAdmin(); // this is the username
|
||||
String fullNameadminInUrl = new LiferayUserManager().getUserByUsername(userNameadminInUrl).getFullname(); // this is the fullname
|
||||
String fullNameadminInUrl = new LiferayUserManager().getUserByUsername(userNameadminInUrl).getFullname(); // this
|
||||
// is
|
||||
// the
|
||||
// fullname
|
||||
String uuid = decryptedUrl.getUuid();
|
||||
|
||||
logger.info("User " + username + " has requested to invert an operation on record with id " + uuid + " and admin in url is " + userNameadminInUrl);
|
||||
logger.info("User " + username + " has requested to invert an operation on record with id " + uuid
|
||||
+ " and admin in url is " + userNameadminInUrl);
|
||||
|
||||
// we need to check the timestamp (it has 24h validity)
|
||||
boolean isValidTimestamp = decryptedUrl.isTimestampValid();
|
||||
|
||||
if(!isValidTimestamp)
|
||||
if (!isValidTimestamp)
|
||||
throw new Exception("This operation can no longer be reverted (link expired)!");
|
||||
|
||||
DataCatalogue catalogue = getCatalogue(context);
|
||||
|
@ -441,36 +470,36 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
String currentStatus = extras.get(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY);
|
||||
|
||||
// check current record status
|
||||
if(!currentStatus.equals(Status.To_be_Merged.getOrigName()))
|
||||
throw new Exception("Record '" + dataset.getTitle() + "' (" + recordUrl + ") is no longer involved in a merge operation!");
|
||||
if (!currentStatus.equals(Status.To_be_Merged.getOrigName()))
|
||||
throw new Exception("Record '" + dataset.getTitle() + "' (" + recordUrl
|
||||
+ ") is no longer involved in a merge operation!");
|
||||
|
||||
// check if it is a reviewer, than he can do what he wants (no matter the admin)
|
||||
if(isReviewer){
|
||||
return new RevertableOperationInfo(recordUrl,
|
||||
fullName, username, uuid, fullNameadminInUrl, userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||
}else{
|
||||
if (isReviewer) {
|
||||
return new RevertableOperationInfo(recordUrl, fullName, username, uuid, fullNameadminInUrl,
|
||||
userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||
} else {
|
||||
|
||||
if(!username.equals(userNameadminInUrl))
|
||||
if (!username.equals(userNameadminInUrl))
|
||||
throw new Exception("You are not the editor allowed to perform this operation!");
|
||||
else
|
||||
return new RevertableOperationInfo(recordUrl,
|
||||
fullName, username, uuid, fullNameadminInUrl, userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||
return new RevertableOperationInfo(recordUrl, fullName, username, uuid, fullNameadminInUrl,
|
||||
userNameadminInUrl, decryptedUrl.getTimestamp(), decryptedUrl.getOperation());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean performRevertOperation(RevertableOperationInfo rInfo)
|
||||
throws Exception {
|
||||
public Boolean performRevertOperation(RevertableOperationInfo rInfo) throws Exception {
|
||||
|
||||
if(!Utils.isIntoPortal()){
|
||||
if (!Utils.isIntoPortal()) {
|
||||
// random result
|
||||
boolean toReturn = Math.random() > 0.5;
|
||||
|
||||
if(toReturn){
|
||||
if (toReturn) {
|
||||
|
||||
boolean throwException = Math.random() > 0.5;
|
||||
if(throwException)
|
||||
if (throwException)
|
||||
throw new Exception("Unable to execute request for XYZ");
|
||||
|
||||
}
|
||||
|
@ -481,23 +510,23 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
String context = Utils.getScopeFromClientUrl(threadRequest);
|
||||
String token = SecurityTokenProvider.instance.get();
|
||||
|
||||
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build();){
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
|
||||
|
||||
String keyPerContext = CatalogueUtilMethods.concatenateSessionKeyScope(Constants.GRSF_UPDATER_SERVICE, context);
|
||||
String baseUrl = (String)getThreadLocalRequest().getSession().getAttribute(keyPerContext);
|
||||
if(baseUrl == null || baseUrl.isEmpty()){
|
||||
String keyPerContext = CatalogueUtilMethods.concatenateSessionKeyScope(Constants.GRSF_UPDATER_SERVICE,
|
||||
context);
|
||||
String baseUrl = (String) getThreadLocalRequest().getSession().getAttribute(keyPerContext);
|
||||
if (baseUrl == null || baseUrl.isEmpty()) {
|
||||
baseUrl = GRSFUpdaterServiceClient.discoverEndPoint(context);
|
||||
getThreadLocalRequest().getSession().setAttribute(keyPerContext, baseUrl);
|
||||
}
|
||||
|
||||
if(baseUrl == null || baseUrl.isEmpty())
|
||||
if (baseUrl == null || baseUrl.isEmpty())
|
||||
throw new Exception("Unable to discover grsf-updater service!");
|
||||
|
||||
Utils.revertOperation(httpClient, baseUrl, threadRequest, rInfo, token, context,
|
||||
PortalContext.getConfiguration().getCurrentGroupId(threadRequest));
|
||||
|
||||
}
|
||||
catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Unable to revert operation ", e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -506,14 +535,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
|
||||
/**
|
||||
* Check if the current user is an editor
|
||||
*
|
||||
* @param username
|
||||
* @param teamRoles
|
||||
* @return true if he/she is an editor, false otherwise
|
||||
*/
|
||||
private boolean isEditor(String username, List<GCubeTeam> teamRolesByUser){
|
||||
private boolean isEditor(String username, List<GCubeTeam> teamRolesByUser) {
|
||||
|
||||
for (GCubeTeam team : teamRolesByUser) {
|
||||
if(team.getTeamName().equals(Constants.GRSF_CATALOGUE_EDITOR_ROLE)){
|
||||
if (team.getTeamName().equals(Constants.GRSF_CATALOGUE_EDITOR_ROLE)) {
|
||||
logger.info("User " + username + " is allowed to modify GRSF records as editor");
|
||||
return true;
|
||||
}
|
||||
|
@ -523,14 +553,15 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
|
||||
/**
|
||||
* Check if the current user is a reviewer
|
||||
*
|
||||
* @param username
|
||||
* @param teamRoles
|
||||
* @return true if he/she is an reviewer, false otherwise
|
||||
*/
|
||||
private boolean isReviewer(String username, List<GCubeTeam> teamRolesByUser){
|
||||
private boolean isReviewer(String username, List<GCubeTeam> teamRolesByUser) {
|
||||
|
||||
for (GCubeTeam team : teamRolesByUser) {
|
||||
if(team.getTeamName().equals(Constants.GRSF_CATALOGUE_REVIEWER_ROLE)){
|
||||
if (team.getTeamName().equals(Constants.GRSF_CATALOGUE_REVIEWER_ROLE)) {
|
||||
logger.info("User " + username + " is allowed to modify GRSF records as reviewer");
|
||||
return true;
|
||||
}
|
||||
|
@ -539,55 +570,54 @@ public class GRSFNotificationService extends RemoteServiceServlet implements GRS
|
|||
}
|
||||
|
||||
@Override
|
||||
public String checkIdentifierExists(String id)
|
||||
throws Exception {
|
||||
public String checkIdentifierExists(String id) throws Exception {
|
||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
CkanDataset dataset = catalogue.getDataset(id,username);
|
||||
if(dataset == null)
|
||||
throw new Exception("A GRSF record with id " + id + " doesn't exist");
|
||||
CkanDataset dataset = catalogue.getDataset(id, username);
|
||||
if (dataset == null)
|
||||
throw new Exception("A GRSF record with id " + id + " doesn't exist");
|
||||
|
||||
if(!dataset.getOrganization().getName().equals(Constants.GRSF_ADMIN_ORGANIZATION_NAME))
|
||||
if (!dataset.getOrganization().getName().equals(Constants.GRSF_ADMIN_ORGANIZATION_NAME))
|
||||
throw new Exception("The suggested record is not a GRSF record");
|
||||
|
||||
return dataset.getExtrasAsHashMap().get(Constants.ITEM_URL_FIELD);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String checkIdentifierExistsInDomain(String id,
|
||||
String acceptedDomain) throws Exception {
|
||||
public String checkIdentifierExistsInDomain(String id, String acceptedDomain) throws Exception {
|
||||
|
||||
if(!Utils.isIntoPortal()){
|
||||
boolean throwException = Math.random() > 0.5;
|
||||
|
||||
// simulate some delay...
|
||||
Thread.sleep(2500);
|
||||
|
||||
if(throwException)
|
||||
throw new Exception("The suggested record is not a GRSF record");
|
||||
|
||||
return "http://data.d4science.org/catalogue/grsf_admin/" + id;
|
||||
}
|
||||
// if (!Utils.isIntoPortal()) {
|
||||
// boolean throwException = Math.random() > 0.5;
|
||||
//
|
||||
// // simulate some delay...
|
||||
// Thread.sleep(2500);
|
||||
//
|
||||
// if (throwException)
|
||||
// throw new Exception("The suggested record is not a GRSF record");
|
||||
//
|
||||
// return "http://data.d4science.org/catalogue/grsf_admin/" + id;
|
||||
// }
|
||||
|
||||
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest());
|
||||
DataCatalogue catalogue = getCatalogue(scopePerCurrentUrl);
|
||||
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername();
|
||||
CkanDataset dataset = catalogue.getDataset(id, username);
|
||||
|
||||
if(dataset == null)
|
||||
throw new Exception("A record with id " + id + " doesn't exist");
|
||||
if (dataset == null)
|
||||
throw new Exception("A record with id " + id + " doesn't exist");
|
||||
|
||||
Map<String, String> extras = dataset.getExtrasAsHashMap();
|
||||
String systemType = extras.get(Constants.SYSTEM_TYPE_CUSTOM_KEY);
|
||||
String domain = extras.get(Constants.DOMAIN_CUSTOM_KEY);
|
||||
String url = extras.get(Constants.ITEM_URL_FIELD);
|
||||
|
||||
if(systemType.equals(Constants.SYSTEM_TYPE_FOR_SOURCES_VALUE))
|
||||
if (systemType.equals(Constants.SYSTEM_TYPE_LEGACY_RECORD))
|
||||
throw new Exception("This record is not a GRSF record!");
|
||||
|
||||
if(!acceptedDomain.equalsIgnoreCase(domain))
|
||||
throw new Exception("You are suggesting a " + domain + " record instead of a " + acceptedDomain + " record!");
|
||||
if (!acceptedDomain.equalsIgnoreCase(domain))
|
||||
throw new Exception(
|
||||
"You are suggesting a " + domain + " record instead of a " + acceptedDomain + " record!");
|
||||
|
||||
return url;
|
||||
}
|
||||
|
|
|
@ -41,9 +41,10 @@ import org.json.simple.JSONObject;
|
|||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
/**
|
||||
* For managing the different interactions with social channels (posts and mails)
|
||||
* For managing the different interactions with social channels (posts and
|
||||
* mails)
|
||||
*
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
*/
|
||||
public class SocialCommunications {
|
||||
|
@ -64,9 +65,10 @@ public class SocialCommunications {
|
|||
private static final String MEDIATYPE_JSON = "application/json";
|
||||
|
||||
// for writing a post in the GRSF admin context
|
||||
private static final String APPLICATION_ID_CATALOGUE_MANAGER = "org.gcube.datacatalogue.GRSFNotifier";
|
||||
private static final String APPLICATION_ID_CATALOGUE_MANAGER = "org.gcube.datacatalogue.GRSFNotifier";
|
||||
|
||||
// emails to be sent to editors and reviewers and post to be written into the grsf admin vre
|
||||
// emails to be sent to editors and reviewers and post to be written into the
|
||||
// grsf admin vre
|
||||
private static final String POST_MESSAGE = "Dear members,"
|
||||
+ "\nThe record 'PRODUCT_TITLE' has been just updated by USER_FULLNAME."
|
||||
+ "\nYou can inspect it here: LINK_RECORD.";
|
||||
|
@ -81,7 +83,7 @@ public class SocialCommunications {
|
|||
|
||||
private static final String ADD_REPORT = "<br> <br>This is a summary of the actions proposed: <br>REPORT_UPDATE<br>";
|
||||
|
||||
// revert link
|
||||
// revert link
|
||||
private static final String REVERT_LINK_PIECE = "<br>The request involves a merge operation. You can reject the merge by exploiting this link LINK in the following 24 hours.";
|
||||
|
||||
// on revert operation
|
||||
|
@ -89,7 +91,7 @@ public class SocialCommunications {
|
|||
+ "<br>a revert operation (undo merge) has been requested on record RECORD_URL, by ADMIN_WHO_CHANGED.";
|
||||
|
||||
private static final String EMAIL_EDITOR_REVERT = "Dear ORIGINAL_USER,"
|
||||
+"<br>a revert operation (undo merge) has been requested on this RECORD_URL you managed by ADMIN_WHO_CHANGED.";
|
||||
+ "<br>a revert operation (undo merge) has been requested on this RECORD_URL you managed by ADMIN_WHO_CHANGED.";
|
||||
|
||||
// post on revert
|
||||
private static final String POST_ON_REVERT = "Dear members,"
|
||||
|
@ -99,39 +101,42 @@ public class SocialCommunications {
|
|||
|
||||
/**
|
||||
*
|
||||
* @param httpServletRequest
|
||||
* @param httpServletRequest
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest){
|
||||
public static String getBaseUrlSocialService(HttpServletRequest httpServletRequest) {
|
||||
|
||||
String context = ScopeProvider.instance.get();
|
||||
|
||||
String keyPerContext = SOCIAL_NETWORKING_BASE_URL_SESSION_KEY + context;
|
||||
String keyPerContext = SOCIAL_NETWORKING_BASE_URL_SESSION_KEY + context;
|
||||
String basePath = (String) httpServletRequest.getSession().getAttribute(keyPerContext);
|
||||
|
||||
if(basePath == null){
|
||||
try{
|
||||
if (basePath == null) {
|
||||
try {
|
||||
|
||||
SimpleQuery query = queryFor(GCoreEndpoint.class);
|
||||
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'",serviceClass));
|
||||
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'", serviceClass));
|
||||
query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
|
||||
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName));
|
||||
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+resource+"\"]/text()");
|
||||
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", serviceName));
|
||||
query.setResult(
|
||||
"$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""
|
||||
+ resource + "\"]/text()");
|
||||
|
||||
DiscoveryClient<String> client = client();
|
||||
List<String> endpoints = client.submit(query);
|
||||
if (endpoints == null || endpoints.isEmpty())
|
||||
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
|
||||
|
||||
if (endpoints == null || endpoints.isEmpty())
|
||||
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: " + serviceName
|
||||
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
|
||||
|
||||
basePath = endpoints.get(0);
|
||||
if(basePath==null)
|
||||
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+context);
|
||||
if (basePath == null)
|
||||
throw new Exception("Endpoint:" + resource + ", is null for serviceName: " + serviceName
|
||||
+ ", serviceClass: " + serviceClass + ", in scope: " + context);
|
||||
|
||||
httpServletRequest.getSession().setAttribute(keyPerContext, basePath);
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Unable to retrieve such service endpoint information!", e);
|
||||
}
|
||||
}
|
||||
|
@ -141,31 +146,35 @@ public class SocialCommunications {
|
|||
|
||||
/**
|
||||
* Require a proper application token for writing a post and send messages.
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static String requireApplicationToken(String serviceUrl) throws Exception{
|
||||
private static String requireApplicationToken(String serviceUrl) throws Exception {
|
||||
|
||||
String currentScope = ScopeProvider.instance.get();
|
||||
String tokenUser = SecurityTokenProvider.instance.get();
|
||||
|
||||
logger.info("Current scope for requireApplicationToken is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
|
||||
logger.info("Current scope for requireApplicationToken is " + currentScope + " and token is "
|
||||
+ tokenUser.substring(0, 10) + "***************");
|
||||
String basePath = serviceUrl;
|
||||
|
||||
if(basePath == null){
|
||||
if (basePath == null) {
|
||||
|
||||
logger.error("Unable to write a post because there is no social networking service available");
|
||||
throw new Exception("Unable to discover the social networking service");
|
||||
|
||||
}else{
|
||||
} else {
|
||||
|
||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
|
||||
.build();) {
|
||||
|
||||
// ask token application
|
||||
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_APPLICATION_TOKEN + "?gcube-token=" + tokenUser);
|
||||
HttpPost postRequest = new HttpPost(
|
||||
basePath + SOCIAL_SERVICE_APPLICATION_TOKEN + "?gcube-token=" + tokenUser);
|
||||
JSONObject requestToken = new JSONObject();
|
||||
requestToken.put("app_id", APPLICATION_ID_CATALOGUE_MANAGER);
|
||||
StringEntity input = new StringEntity(requestToken.toJSONString());
|
||||
|
@ -178,21 +187,21 @@ public class SocialCommunications {
|
|||
if (response.getStatusLine().getStatusCode() != 201) {
|
||||
throw new RuntimeException("Failed to retrieve application token : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode());
|
||||
}else{
|
||||
} else {
|
||||
|
||||
Map<String, Object> mapResponseGeneratedToken = getResponseEntityAsJSON(response);
|
||||
boolean successGeneratedToken = (boolean)mapResponseGeneratedToken.get("success");
|
||||
if(!successGeneratedToken){
|
||||
boolean successGeneratedToken = (boolean) mapResponseGeneratedToken.get("success");
|
||||
if (!successGeneratedToken) {
|
||||
|
||||
throw new RuntimeException("Failed to generate the token for the application!"
|
||||
+ " Error message is " + mapResponseGeneratedToken.get("message"));
|
||||
|
||||
}else{
|
||||
return (String)mapResponseGeneratedToken.get("result");
|
||||
} else {
|
||||
return (String) mapResponseGeneratedToken.get("result");
|
||||
}
|
||||
|
||||
}
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to create a post", e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -201,63 +210,76 @@ public class SocialCommunications {
|
|||
|
||||
/**
|
||||
* Notify the users about the required changes.
|
||||
*
|
||||
* @param bean
|
||||
* @param url
|
||||
* @param username
|
||||
* @param fullName
|
||||
* @param hashtags
|
||||
* @param enablePostNotification
|
||||
* @throws Exception
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void writePostOnRevert(String serviceUrl, RevertableOperationInfo rInfo, boolean enablePostNotification, String userCurrentUrl) throws Exception{
|
||||
public static void writePostOnRevert(String serviceUrl, RevertableOperationInfo rInfo,
|
||||
boolean enablePostNotification, String userCurrentUrl) throws Exception {
|
||||
|
||||
// discover service endpoint for the social networking library
|
||||
String currentScope = ScopeProvider.instance.get();
|
||||
String tokenUser = SecurityTokenProvider.instance.get();
|
||||
|
||||
logger.info("Current scope for writePostOnRevert is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
|
||||
logger.info("Current scope for writePostOnRevert is " + currentScope + " and token is "
|
||||
+ tokenUser.substring(0, 10) + "***************");
|
||||
String basePath = serviceUrl;
|
||||
|
||||
if(basePath == null){
|
||||
if (basePath == null) {
|
||||
|
||||
logger.error("Unable to write a post because there is no social networking service available");
|
||||
throw new Exception("Unable to discover the social networking service");
|
||||
|
||||
}else{
|
||||
} else {
|
||||
|
||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
|
||||
.build();) {
|
||||
|
||||
// require url
|
||||
String applicationToken = requireApplicationToken(serviceUrl);
|
||||
|
||||
//see Feature #17576 updated by Francesco
|
||||
/*final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL + extractOrgFriendlyURL(userCurrentUrl) + GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
|
||||
String userFullNameHighlightedCurrent = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes())+"\">"+rInfo.getFullNameCurrentAdmin()+
|
||||
"</a> ";
|
||||
*/
|
||||
|
||||
String userFullNameHighlightedCurrent = "@"+rInfo.getUserNameCurrentAdmin();
|
||||
// see Feature #17576 updated by Francesco
|
||||
/*
|
||||
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
|
||||
* extractOrgFriendlyURL(userCurrentUrl) +
|
||||
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
|
||||
* userFullNameHighlightedCurrent = "<a class=\"link\" href=\"" + profilePageURL
|
||||
* + "?"+ Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
* Base64.getEncoder().encodeToString(rInfo.getUserNameCurrentAdmin().getBytes()
|
||||
* )+"\">"+rInfo.getFullNameCurrentAdmin()+ "</a> ";
|
||||
*/
|
||||
|
||||
/*String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes())+"\">"+rInfo.getFullNameOriginalAdmin()+
|
||||
"</a> ";*/
|
||||
|
||||
String userFullNameHighlightedOriginal = "@"+rInfo.getUserNameOriginalAdmin();
|
||||
String userFullNameHighlightedCurrent = "@" + rInfo.getUserNameCurrentAdmin();
|
||||
|
||||
/*
|
||||
* String userFullNameHighlightedOriginal = "<a class=\"link\" href=\"" +
|
||||
* profilePageURL + "?"+
|
||||
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
* Base64.getEncoder().encodeToString(rInfo.getUserNameOriginalAdmin().getBytes(
|
||||
* ))+"\">"+rInfo.getFullNameOriginalAdmin()+ "</a> ";
|
||||
*/
|
||||
|
||||
String userFullNameHighlightedOriginal = "@" + rInfo.getUserNameOriginalAdmin();
|
||||
// replace
|
||||
String message = POST_ON_REVERT.replace("RECORD_URL", rInfo.getRecordUrl()).replace("ADMIN_WHO_CHANGED", userFullNameHighlightedCurrent).replace("ORIGINAL_USER",userFullNameHighlightedOriginal);
|
||||
String message = POST_ON_REVERT.replace("RECORD_URL", rInfo.getRecordUrl())
|
||||
.replace("ADMIN_WHO_CHANGED", userFullNameHighlightedCurrent)
|
||||
.replace("ORIGINAL_USER", userFullNameHighlightedOriginal);
|
||||
|
||||
// add hashtag
|
||||
message +="\n\n";
|
||||
message += "\n\n";
|
||||
message += " #" + HashTagsOnUpdate.REVERTED_MERGE.getString();
|
||||
|
||||
logger.info("The post that is going to be written is -> " + message);
|
||||
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
|
||||
HttpPost postRequest = new HttpPost(
|
||||
basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
|
||||
JSONObject object = new JSONObject();
|
||||
object.put("text", message);
|
||||
object.put("enable_notification", enablePostNotification);
|
||||
|
@ -272,7 +294,7 @@ public class SocialCommunications {
|
|||
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to create a post", e);
|
||||
}
|
||||
}
|
||||
|
@ -280,69 +302,77 @@ public class SocialCommunications {
|
|||
|
||||
/**
|
||||
* Notify the users about the required changes.
|
||||
*
|
||||
* @param bean
|
||||
* @param url
|
||||
* @param username
|
||||
* @param fullName
|
||||
* @param hashtags
|
||||
* @param enablePostNotification
|
||||
* @throws Exception
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void writeProductPost(String serviceUrl, ManageProductBean bean, String username, String fullName, boolean enablePostNotification, String userCurrentUrl) throws Exception{
|
||||
public static void writeProductPost(String serviceUrl, ManageProductBean bean, String username, String fullName,
|
||||
boolean enablePostNotification, String userCurrentUrl) throws Exception {
|
||||
|
||||
// discover service endpoint for the social networking library
|
||||
String currentScope = ScopeProvider.instance.get();
|
||||
String tokenUser = SecurityTokenProvider.instance.get();
|
||||
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
|
||||
+ tokenUser.substring(0, 10) + "***************");
|
||||
String basePath = serviceUrl;
|
||||
|
||||
if(basePath == null){
|
||||
if (basePath == null) {
|
||||
|
||||
logger.error("Unable to write a post because there is no social networking service available");
|
||||
throw new Exception("Unable to discover the social networking service");
|
||||
|
||||
}else{
|
||||
} else {
|
||||
|
||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
|
||||
.build();) {
|
||||
|
||||
// require url
|
||||
String applicationToken = requireApplicationToken(serviceUrl);
|
||||
|
||||
//see Feature #17576 Updated by Francesco
|
||||
/*final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL + extractOrgFriendlyURL(userCurrentUrl) + GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
|
||||
String userFullNameHighlighted = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
||||
Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
|
||||
"</a> ";
|
||||
*/
|
||||
|
||||
String userFullNameHighlighted = "@"+username;
|
||||
|
||||
// see Feature #17576 Updated by Francesco
|
||||
/*
|
||||
* final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL +
|
||||
* extractOrgFriendlyURL(userCurrentUrl) +
|
||||
* GCubePortalConstants.USER_PROFILE_FRIENDLY_URL; String
|
||||
* userFullNameHighlighted = "<a class=\"link\" href=\"" + profilePageURL + "?"+
|
||||
* Base64.getEncoder().encodeToString(USER_PROFILE_OID.getBytes())+"="+
|
||||
* Base64.getEncoder().encodeToString(username.getBytes())+"\">"+fullName+
|
||||
* "</a> ";
|
||||
*/
|
||||
|
||||
String userFullNameHighlighted = "@" + username;
|
||||
|
||||
// replace
|
||||
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle()).replace("LINK_RECORD", bean.getUrl()).
|
||||
replace("USER_FULLNAME", userFullNameHighlighted);
|
||||
String message = POST_MESSAGE.replace("PRODUCT_TITLE", bean.getTitle())
|
||||
.replace("LINK_RECORD", bean.getUrl()).replace("USER_FULLNAME", userFullNameHighlighted);
|
||||
|
||||
if(bean.getReport() != null && !bean.getReport().isEmpty())
|
||||
message += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
||||
if (bean.getReport() != null && !bean.getReport().isEmpty())
|
||||
message += ADD_REPORT.replace("<br>", "").replace("REPORT_UPDATE", bean.getReport());
|
||||
|
||||
Set<String> hashtags = bean.getHashtags();
|
||||
logger.debug("Hashtags are " + hashtags);
|
||||
if(hashtags != null && !hashtags.isEmpty()){
|
||||
message +="\n\n";
|
||||
if (hashtags != null && !hashtags.isEmpty()) {
|
||||
message += "\n\n";
|
||||
for (String hashtag : hashtags) {
|
||||
message += " #" + hashtag;
|
||||
}
|
||||
//Added by Francesco Mangiacrapa see at Feature #16312
|
||||
// Added by Francesco Mangiacrapa see at Feature #16312
|
||||
String normalizedFullName = fullName.trim().replace(" ", "_");
|
||||
message += " #" + normalizedFullName;
|
||||
}
|
||||
|
||||
logger.info("The post that is going to be written is -> " + message);
|
||||
HttpPost postRequest = new HttpPost(basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
|
||||
HttpPost postRequest = new HttpPost(
|
||||
basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + applicationToken);
|
||||
JSONObject object = new JSONObject();
|
||||
object.put("text", message);
|
||||
object.put("enable_notification", enablePostNotification);
|
||||
|
@ -356,7 +386,7 @@ public class SocialCommunications {
|
|||
if (response.getStatusLine().getStatusCode() != 201)
|
||||
throw new RuntimeException("Failed to write application post : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to create a post", e);
|
||||
}
|
||||
}
|
||||
|
@ -372,31 +402,26 @@ public class SocialCommunications {
|
|||
} else {
|
||||
friendlyURL = friendlyURL.split("\\?")[0].split("\\#")[0];
|
||||
}
|
||||
return "/"+friendlyURL;
|
||||
return "/" + friendlyURL;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an email to the administrator as well as the
|
||||
* Send an email to the administrator as well as the
|
||||
*
|
||||
* @param bean
|
||||
* @param catalogue
|
||||
* @param username
|
||||
* @param fullName
|
||||
* @param isMergeInvolved
|
||||
* @param httpSession
|
||||
* @throws Exceptio
|
||||
* @param isMergeInvolved
|
||||
* @param httpSession
|
||||
* @throws Exceptio
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void sendEmailAdministrators(
|
||||
String serviceUrl,
|
||||
ManageProductBean bean,
|
||||
DataCatalogue catalogue,
|
||||
String username,
|
||||
String fullName,
|
||||
long groupId,
|
||||
String clientCurrenturl,
|
||||
boolean isMergeInvolved) throws Exception {
|
||||
public static void sendEmailAdministrators(String serviceUrl, ManageProductBean bean, DataCatalogue catalogue,
|
||||
String username, String fullName, long groupId, String clientCurrenturl, boolean isMergeInvolved)
|
||||
throws Exception {
|
||||
|
||||
// get the list of GRSF Reviewers to alert them as well
|
||||
RoleManager roleManager = new LiferayRoleManager();
|
||||
|
@ -406,54 +431,56 @@ public class SocialCommunications {
|
|||
|
||||
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
|
||||
|
||||
for(GCubeUser gU: reviewersGcube){
|
||||
for (GCubeUser gU : reviewersGcube) {
|
||||
// if the user is a reviewer, then send the email just once
|
||||
if(!gU.getUsername().equals(username))
|
||||
if (!gU.getUsername().equals(username))
|
||||
reviewers.add(gU.getUsername());
|
||||
}
|
||||
|
||||
logger.info("List of " + Constants.GRSF_CATALOGUE_REVIEWER_ROLE + " is " + reviewers);
|
||||
|
||||
// build the url that allows to revert the operation
|
||||
// build the url that allows to revert the operation
|
||||
RevertableOperations operation = RevertableOperations.MERGE;
|
||||
|
||||
// discover service endpoint for the social networking library
|
||||
String currentScope = ScopeProvider.instance.get();
|
||||
String tokenUser = SecurityTokenProvider.instance.get();
|
||||
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
|
||||
+ tokenUser.substring(0, 10) + "***************");
|
||||
String basePath = serviceUrl;
|
||||
|
||||
if(basePath == null){
|
||||
if (basePath == null) {
|
||||
|
||||
logger.error("Unable to write a post because there is no social networking service available");
|
||||
throw new Exception("Unable to discover the social networking service");
|
||||
|
||||
}else{
|
||||
} else {
|
||||
|
||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
|
||||
.build();) {
|
||||
|
||||
/// require url
|
||||
String applicationToken = requireApplicationToken(serviceUrl);
|
||||
|
||||
String revertUrl = "";
|
||||
if(isMergeInvolved)
|
||||
revertUrl = getEncodedUrlManage(operation, username, System.currentTimeMillis(), bean.getKnowledgeBaseId(), clientCurrenturl);
|
||||
|
||||
String messageToEditor = (EMAIL_MESSAGE_EDITOR +
|
||||
(isMergeInvolved? REVERT_LINK_PIECE : "")).replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle()).
|
||||
replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
|
||||
String messageToReviewer = (EMAIL_MESSAGE_REVIEWER+
|
||||
(isMergeInvolved? REVERT_LINK_PIECE : "")).replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle()).
|
||||
replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
|
||||
if (isMergeInvolved)
|
||||
revertUrl = getEncodedUrlManage(operation, username, System.currentTimeMillis(),
|
||||
bean.getKnowledgeBaseId(), clientCurrenturl);
|
||||
|
||||
String messageToEditor = (EMAIL_MESSAGE_EDITOR + (isMergeInvolved ? REVERT_LINK_PIECE : ""))
|
||||
.replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle())
|
||||
.replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
|
||||
String messageToReviewer = (EMAIL_MESSAGE_REVIEWER + (isMergeInvolved ? REVERT_LINK_PIECE : ""))
|
||||
.replace("USER_FULLNAME", fullName).replace("PRODUCT_TITLE", bean.getTitle())
|
||||
.replace("LINK_RECORD", bean.getUrl()).replace("LINK", revertUrl);
|
||||
|
||||
String subject = "Update request on GRSF Record";
|
||||
|
||||
// append report
|
||||
if(bean.getReport() != null){
|
||||
if (bean.getReport() != null) {
|
||||
messageToEditor += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
||||
messageToReviewer += ADD_REPORT.replace("REPORT_UPDATE", bean.getReport());
|
||||
}
|
||||
|
@ -482,7 +509,7 @@ public class SocialCommunications {
|
|||
|
||||
Map<String, Object> mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||
|
||||
if (response.getStatusLine().getStatusCode() != 201){
|
||||
if (response.getStatusLine().getStatusCode() != 201) {
|
||||
logger.error("Failed to send message to editor : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
}
|
||||
|
@ -494,7 +521,7 @@ public class SocialCommunications {
|
|||
reqMessage.put("subject", subject);
|
||||
reqMessage.put("body", messageToReviewer);
|
||||
recipients = new JSONArray();
|
||||
for(String reviewer: reviewers){
|
||||
for (String reviewer : reviewers) {
|
||||
JSONObject recip = new JSONObject();
|
||||
recip.put("id", reviewer);
|
||||
recipients.add(recip);
|
||||
|
@ -509,12 +536,12 @@ public class SocialCommunications {
|
|||
response = client.execute(postRequest);
|
||||
mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||
|
||||
if (response.getStatusLine().getStatusCode() != 201){
|
||||
if (response.getStatusLine().getStatusCode() != 201) {
|
||||
logger.error("Failed to send message to reviewers : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
}
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to send messages", e);
|
||||
}
|
||||
}
|
||||
|
@ -522,11 +549,8 @@ public class SocialCommunications {
|
|||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void sendEmailAdministratorsOnOperationReverted(
|
||||
String serviceUrl,
|
||||
RevertableOperationInfo rInfo,
|
||||
long groupId
|
||||
) throws Exception {
|
||||
public static void sendEmailAdministratorsOnOperationReverted(String serviceUrl, RevertableOperationInfo rInfo,
|
||||
long groupId) throws Exception {
|
||||
|
||||
// get the list of GRSF Reviewers to alert them as well
|
||||
RoleManager roleManager = new LiferayRoleManager();
|
||||
|
@ -536,9 +560,9 @@ public class SocialCommunications {
|
|||
|
||||
List<String> reviewers = new ArrayList<String>(reviewersGcube.size());
|
||||
|
||||
for(GCubeUser gU: reviewersGcube){
|
||||
for (GCubeUser gU : reviewersGcube) {
|
||||
// if the user is a reviewer, then send the email just once
|
||||
if(!gU.getUsername().equals(rInfo.getUserNameOriginalAdmin()))
|
||||
if (!gU.getUsername().equals(rInfo.getUserNameOriginalAdmin()))
|
||||
reviewers.add(gU.getUsername());
|
||||
}
|
||||
|
||||
|
@ -548,26 +572,31 @@ public class SocialCommunications {
|
|||
String currentScope = ScopeProvider.instance.get();
|
||||
String tokenUser = SecurityTokenProvider.instance.get();
|
||||
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
|
||||
logger.info("Current scope for writeProductPost is " + currentScope + " and token is "
|
||||
+ tokenUser.substring(0, 10) + "***************");
|
||||
String basePath = serviceUrl;
|
||||
|
||||
if(basePath == null){
|
||||
if (basePath == null) {
|
||||
|
||||
logger.error("Unable to write a post because there is no social networking service available");
|
||||
throw new Exception("Unable to discover the social networking service");
|
||||
|
||||
}else{
|
||||
} else {
|
||||
|
||||
basePath = basePath.endsWith("/") ? basePath : basePath + "/";
|
||||
|
||||
try(CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();){
|
||||
try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
|
||||
.build();) {
|
||||
|
||||
String applicationToken = requireApplicationToken(serviceUrl);
|
||||
|
||||
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl()).replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin()).
|
||||
replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
|
||||
String messageToReviewer = EMAIL_REVIEWER_REVERT.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin()).replace("RECORD_URL", rInfo.getRecordUrl()).
|
||||
replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin());
|
||||
String messageToEditor = EMAIL_EDITOR_REVERT.replace("RECORD_URL", rInfo.getRecordUrl())
|
||||
.replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin())
|
||||
.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin());
|
||||
String messageToReviewer = EMAIL_REVIEWER_REVERT
|
||||
.replace("ADMIN_WHO_CHANGED", rInfo.getFullNameCurrentAdmin())
|
||||
.replace("RECORD_URL", rInfo.getRecordUrl())
|
||||
.replace("ORIGINAL_USER", rInfo.getFullNameOriginalAdmin());
|
||||
String subject = "Revert merge request on GRSF Record";
|
||||
|
||||
messageToEditor = messageToEditor.replace("<br>", "\n");
|
||||
|
@ -591,7 +620,7 @@ public class SocialCommunications {
|
|||
|
||||
Map<String, Object> mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||
|
||||
if (response.getStatusLine().getStatusCode() != 201){
|
||||
if (response.getStatusLine().getStatusCode() != 201) {
|
||||
logger.error("Failed to send message to editor : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
}
|
||||
|
@ -603,7 +632,7 @@ public class SocialCommunications {
|
|||
reqMessage.put("subject", subject);
|
||||
reqMessage.put("body", messageToReviewer);
|
||||
recipients = new JSONArray();
|
||||
for(String reviewer: reviewers){
|
||||
for (String reviewer : reviewers) {
|
||||
JSONObject recip = new JSONObject();
|
||||
recip.put("id", reviewer);
|
||||
recipients.add(recip);
|
||||
|
@ -615,12 +644,12 @@ public class SocialCommunications {
|
|||
response = client.execute(postRequest);
|
||||
mapResponseWritePost = getResponseEntityAsJSON(response);
|
||||
|
||||
if (response.getStatusLine().getStatusCode() != 201){
|
||||
if (response.getStatusLine().getStatusCode() != 201) {
|
||||
logger.error("Failed to send message to editor : HTTP error code : "
|
||||
+ response.getStatusLine().getStatusCode() + mapResponseWritePost.get("message"));
|
||||
}
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to send messages", e);
|
||||
throw new Exception(e);
|
||||
}
|
||||
|
@ -630,24 +659,28 @@ public class SocialCommunications {
|
|||
|
||||
/**
|
||||
* Create the url to be send for reverting the operation
|
||||
* @param httpSession
|
||||
*
|
||||
* @param httpSession
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String getEncodedUrlManage(RevertableOperations operation, String administrator, long timestamp, String uuid, String clientCurrenturl) throws Exception{
|
||||
public static String getEncodedUrlManage(RevertableOperations operation, String administrator, long timestamp,
|
||||
String uuid, String clientCurrenturl) throws Exception {
|
||||
logger.info("Request for revert link. Client current url is " + clientCurrenturl);
|
||||
RevertOperationUrl operationUrl = new RevertOperationUrl(clientCurrenturl, administrator, timestamp, uuid, operation);
|
||||
RevertOperationUrl operationUrl = new RevertOperationUrl(clientCurrenturl, administrator, timestamp, uuid,
|
||||
operation);
|
||||
String shortUrl = operationUrl.getShortUrl();
|
||||
return shortUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the json response to a map
|
||||
*
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response){
|
||||
public static Map<String, Object> getResponseEntityAsJSON(HttpResponse response) {
|
||||
|
||||
Map<String, Object> toReturn = null;
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
@ -660,7 +693,7 @@ public class SocialCommunications {
|
|||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
toReturn = objectMapper.readValue(jsonString, HashMap.class);
|
||||
logger.debug("Map is " + toReturn);
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Failed to read json object", e);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -51,6 +51,7 @@ import com.liferay.portal.service.UserLocalServiceUtil;
|
|||
|
||||
/**
|
||||
* Utility methods for GRSF Management panel widget.
|
||||
*
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
*/
|
||||
public class Utils {
|
||||
|
@ -59,34 +60,36 @@ public class Utils {
|
|||
private static final String REGEX_UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
|
||||
/**
|
||||
* Return a map for converting a key to a namespace:key format by reading a generic resource.
|
||||
* @param httpSession
|
||||
* Return a map for converting a key to a namespace:key format by reading a
|
||||
* generic resource.
|
||||
*
|
||||
* @param httpSession
|
||||
* @return a map
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, String> getFieldToFieldNameSpaceMapping(HttpSession httpSession, String resourceName){
|
||||
public static Map<String, String> getFieldToFieldNameSpaceMapping(HttpSession httpSession, String resourceName) {
|
||||
|
||||
// check if this information is available in session
|
||||
String sessionKey = ScopeProvider.instance.get() + resourceName;
|
||||
if(httpSession.getAttribute(sessionKey) != null)
|
||||
if (httpSession.getAttribute(sessionKey) != null)
|
||||
return (Map<String, String>) httpSession.getAttribute(sessionKey);
|
||||
|
||||
Map<String, String> namespacesMap = new HashMap<String, String>(); // e.g. fishery_identity:Short Title -> Short Title
|
||||
Map<String, String> namespacesMap = new HashMap<String, String>(); // e.g. fishery_identity:Short Title -> Short
|
||||
// Title
|
||||
try {
|
||||
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
|
||||
"where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
|
||||
" eq '" + resourceName + "'" +
|
||||
"return $profile");
|
||||
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource "
|
||||
+ "where $profile/Profile/SecondaryType/string() eq '" + "ApplicationProfile"
|
||||
+ "' and $profile/Profile/Name/string() " + " eq '" + resourceName + "'" + "return $profile");
|
||||
|
||||
DiscoveryClient<String> client = client();
|
||||
List<String> appProfile = client.submit(q);
|
||||
|
||||
if (appProfile == null || appProfile.size() == 0)
|
||||
if (appProfile == null || appProfile.size() == 0)
|
||||
throw new Exception("Your applicationProfile is not registered in the infrastructure");
|
||||
else {
|
||||
|
||||
String elem = appProfile.get(0);
|
||||
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
|
||||
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
|
||||
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
|
||||
XPathHelper helper = new XPathHelper(node);
|
||||
|
||||
|
@ -94,17 +97,18 @@ public class Utils {
|
|||
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
|
||||
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
|
||||
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
|
||||
if(sizeKeys != sizeKeysModifed)
|
||||
if (sizeKeys != sizeKeysModifed)
|
||||
throw new Exception("Malformed XML");
|
||||
logger.debug("Size is " + sizeKeys);
|
||||
for (int i = 0; i < sizeKeys; i++) {
|
||||
namespacesMap.put(nodeListModifiedKeys.item(i).getTextContent(), nodeListKeys.item(i).getTextContent());
|
||||
namespacesMap.put(nodeListModifiedKeys.item(i).getTextContent(),
|
||||
nodeListKeys.item(i).getTextContent());
|
||||
}
|
||||
}
|
||||
logger.debug("Map is " + namespacesMap);
|
||||
|
||||
// put them into session for speeding up the operations
|
||||
httpSession.setAttribute(sessionKey, namespacesMap);
|
||||
httpSession.setAttribute(sessionKey, namespacesMap);
|
||||
return namespacesMap;
|
||||
} catch (Exception e) {
|
||||
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
|
||||
|
@ -113,7 +117,9 @@ public class Utils {
|
|||
}
|
||||
|
||||
/**
|
||||
* Replace the extras' keys if needed, e.g. fishery_identity:Short Title -> Short Title
|
||||
* Replace the extras' keys if needed, e.g. fishery_identity:Short Title ->
|
||||
* Short Title
|
||||
*
|
||||
* @param extrasAsPairs
|
||||
* @param namespaces
|
||||
* @return a map with replaced key value pairs
|
||||
|
@ -129,7 +135,7 @@ public class Utils {
|
|||
String replacedKey = namespaces.containsKey(pairKey) ? namespaces.get(pairKey) : pairKey;
|
||||
|
||||
List<String> values = null;
|
||||
if(toReturn.containsKey(replacedKey))
|
||||
if (toReturn.containsKey(replacedKey))
|
||||
values = toReturn.get(replacedKey);
|
||||
else
|
||||
values = new ArrayList<String>(1);
|
||||
|
@ -143,10 +149,11 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Get the extras of this dataset as hashmap
|
||||
*
|
||||
* @param extrasAsPairs
|
||||
* @return
|
||||
*/
|
||||
public static Map<String, List<String>> getExtrasAsHashMap(List<CkanPair> extrasAsPairs){
|
||||
public static Map<String, List<String>> getExtrasAsHashMap(List<CkanPair> extrasAsPairs) {
|
||||
|
||||
Map<String, List<String>> toReturn = new HashMap<String, List<String>>();
|
||||
|
||||
|
@ -155,7 +162,7 @@ public class Utils {
|
|||
String pairValue = ckanPair.getValue();
|
||||
|
||||
List<String> values = null;
|
||||
if(toReturn.containsKey(pairKey))
|
||||
if (toReturn.containsKey(pairKey))
|
||||
values = toReturn.get(pairKey);
|
||||
else
|
||||
values = new ArrayList<String>(1);
|
||||
|
@ -169,68 +176,66 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Send an update for this bean
|
||||
*
|
||||
* @param baseUrl
|
||||
* @param bean
|
||||
* @param username
|
||||
* @param catalogue
|
||||
* @param username
|
||||
* @param catalogue
|
||||
* @return true on success, false otherwise
|
||||
*/
|
||||
public static void updateRecord(
|
||||
String serviceUrl,
|
||||
final ManageProductBean bean,
|
||||
final DataCatalogue catalogue,
|
||||
final String username,
|
||||
final String fullName,
|
||||
final HttpServletRequest httpServletRequest,
|
||||
final long groupId,
|
||||
final String context,
|
||||
final String token) throws Exception{
|
||||
public static void updateRecord(String serviceUrl, final ManageProductBean bean, final DataCatalogue catalogue,
|
||||
final String username, final String fullName, final HttpServletRequest httpServletRequest,
|
||||
final long groupId, final String context, final String token) throws Exception {
|
||||
|
||||
if(serviceUrl == null)
|
||||
if (serviceUrl == null)
|
||||
throw new IllegalArgumentException("GRSF Updater service url cannot be null");
|
||||
|
||||
if(bean == null)
|
||||
if (bean == null)
|
||||
throw new IllegalArgumentException("Item bean to manage cannot be null");
|
||||
|
||||
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build();){
|
||||
|
||||
//ADDED BY FRANCESCO
|
||||
if(Utils.isIntoPortal()) {
|
||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();) {
|
||||
|
||||
// ADDED BY FRANCESCO
|
||||
if (Utils.isIntoPortal()) {
|
||||
|
||||
// send update to the knowledge base
|
||||
GRSFUpdaterServiceClient.updateKB(httpClient, serviceUrl, bean, catalogue, username, fullName);
|
||||
|
||||
|
||||
// if there are merges, update the status of the other involved records
|
||||
if(bean.isMergesInvolved())
|
||||
updateStatusInvolvedRecords(bean, catalogue);
|
||||
|
||||
if (bean.isMergesInvolved())
|
||||
updateStatusInvolvedRecords(bean, username, catalogue);
|
||||
|
||||
}
|
||||
|
||||
// require social networking url
|
||||
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
||||
|
||||
// and the user current browser url
|
||||
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other parameters
|
||||
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore
|
||||
// other
|
||||
// parameters
|
||||
|
||||
// manage interactions through a separated thread but set there security token and context (and then reset them)
|
||||
// manage interactions through a separated thread but set there security token
|
||||
// and context (and then reset them)
|
||||
Thread t = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
ScopeProvider.instance.set(context);
|
||||
SecurityTokenProvider.instance.set(token);
|
||||
try{
|
||||
try {
|
||||
|
||||
// send email to Editors and Reviewers
|
||||
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
|
||||
SocialCommunications.sendEmailAdministrators(baseUrlSocial, bean, catalogue, username, fullName,
|
||||
groupId, currentBrowserUrl, bean.isMergesInvolved());
|
||||
|
||||
// create a post about the operation
|
||||
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false, currentBrowserUrl);
|
||||
// create a post about the operation
|
||||
SocialCommunications.writeProductPost(baseUrlSocial, bean, username, fullName, false,
|
||||
currentBrowserUrl);
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Something failed while alerting editors/reviewers", e);
|
||||
}finally{
|
||||
} finally {
|
||||
ScopeProvider.instance.reset();
|
||||
SecurityTokenProvider.instance.reset();
|
||||
}
|
||||
|
@ -238,7 +243,7 @@ public class Utils {
|
|||
});
|
||||
t.start();
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Unable to update this Item ", e);
|
||||
throw e;
|
||||
}
|
||||
|
@ -246,14 +251,16 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Revert operation and alert admins/vre users
|
||||
*
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
* @param httpClient
|
||||
* @param baseUrl
|
||||
* @param fullName
|
||||
* @param uuid
|
||||
*/
|
||||
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl, HttpServletRequest httpServletRequest,
|
||||
final RevertableOperationInfo rInfo, final String token, final String context, final long groupId) throws Exception{
|
||||
public static void revertOperation(CloseableHttpClient httpClient, String baseUrl,
|
||||
HttpServletRequest httpServletRequest, final RevertableOperationInfo rInfo, final String token,
|
||||
final String context, final long groupId) throws Exception {
|
||||
|
||||
GRSFUpdaterServiceClient.revertOperation(httpClient, baseUrl, rInfo.getFullNameCurrentAdmin(), rInfo.getUuid());
|
||||
|
||||
|
@ -261,16 +268,18 @@ public class Utils {
|
|||
final String baseUrlSocial = SocialCommunications.getBaseUrlSocialService(httpServletRequest);
|
||||
|
||||
// and the user current browser url
|
||||
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other parameters
|
||||
|
||||
// manage interactions through a separated thread but set there security token and context (and then reset them)
|
||||
final String currentBrowserUrl = Utils.getCurrentClientUrl(httpServletRequest).split("\\?")[0]; // ignore other
|
||||
// parameters
|
||||
|
||||
// manage interactions through a separated thread but set there security token
|
||||
// and context (and then reset them)
|
||||
Thread t = new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
ScopeProvider.instance.set(context);
|
||||
SecurityTokenProvider.instance.set(token);
|
||||
try{
|
||||
try {
|
||||
|
||||
// write post about this
|
||||
SocialCommunications.writePostOnRevert(baseUrlSocial, rInfo, false, currentBrowserUrl);
|
||||
|
@ -278,9 +287,9 @@ public class Utils {
|
|||
// alert who's involved
|
||||
SocialCommunications.sendEmailAdministratorsOnOperationReverted(baseUrlSocial, rInfo, groupId);
|
||||
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
logger.error("Something failed while alerting editors/reviewers", e);
|
||||
}finally{
|
||||
} finally {
|
||||
ScopeProvider.instance.reset();
|
||||
SecurityTokenProvider.instance.reset();
|
||||
}
|
||||
|
@ -292,23 +301,26 @@ public class Utils {
|
|||
}
|
||||
|
||||
/**
|
||||
* Update the status of the involved records to "to be merged"
|
||||
* @param bean
|
||||
* @param catalogue
|
||||
* @param username
|
||||
* @param fullName
|
||||
* @throws Exception
|
||||
* Update the status of the involved records to "to be merged".
|
||||
*
|
||||
* @param bean the bean
|
||||
* @param username the username
|
||||
* @param catalogue the catalogue
|
||||
* @throws Exception the exception
|
||||
*/
|
||||
private static void updateStatusInvolvedRecords(ManageProductBean bean, DataCatalogue catalogue) throws Exception {
|
||||
private static void updateStatusInvolvedRecords(ManageProductBean bean, String username, DataCatalogue catalogue)
|
||||
throws Exception {
|
||||
|
||||
String context = ScopeProvider.instance.get();
|
||||
String sysApi = fetchSysAPI(context);
|
||||
for(SimilarGRSFRecord s: bean.getSimilarGrsfRecords()){
|
||||
if(s.isSuggestedMerge()){
|
||||
// String context = ScopeProvider.instance.get();
|
||||
// String sysApi = fetchSysAPI(context);
|
||||
for (SimilarGRSFRecord s : bean.getSimilarGrsfRecords()) {
|
||||
if (s.isSuggestedMerge()) {
|
||||
String productId = s.getKnowledgeBaseId();
|
||||
Map<String, List<String>> updateStatus = new HashMap<String, List<String>>(1);
|
||||
updateStatus.put(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY, Arrays.asList(Status.To_be_Merged.getOrigName()));
|
||||
catalogue.patchProductCustomFields(productId, sysApi, updateStatus, true);
|
||||
updateStatus.put(Constants.STATUS_OF_THE_GRSF_RECORD_CUSTOM_KEY,
|
||||
Arrays.asList(Status.To_be_Merged.getOrigName()));
|
||||
// Fixing bug #23561, passing username (instead of sysAPI)
|
||||
catalogue.patchProductCustomFields(productId, username, updateStatus, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -316,45 +328,48 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Get the scope in which ckan information needs to be discovered from the url
|
||||
*
|
||||
* @param httpServletRequest
|
||||
* @return
|
||||
*/
|
||||
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){
|
||||
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest) {
|
||||
|
||||
if(httpServletRequest == null)
|
||||
if (httpServletRequest == null)
|
||||
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||
|
||||
String scopeToReturn = null;
|
||||
try{
|
||||
try {
|
||||
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
|
||||
logger.debug("Client url is " + clientUrl);
|
||||
|
||||
// check if this information is in session, otherwise set it and return
|
||||
HttpSession session = httpServletRequest.getSession();
|
||||
|
||||
if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){
|
||||
if ((scopeToReturn = (String) session.getAttribute(clientUrl)) != null) {
|
||||
logger.debug("Scope to return is " + scopeToReturn);
|
||||
}else{
|
||||
} else {
|
||||
// ask to the ckan library and set it
|
||||
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
|
||||
logger.debug("Scope to return is " + scopeToReturn);
|
||||
session.setAttribute(clientUrl, scopeToReturn);
|
||||
}
|
||||
}catch(Exception e){
|
||||
} catch (Exception e) {
|
||||
scopeToReturn = getCurrentContext(httpServletRequest, true);
|
||||
logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
|
||||
logger.warn(
|
||||
"Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
|
||||
}
|
||||
return scopeToReturn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Needed to get the url of the client
|
||||
*
|
||||
* @param httpServletRequest the httpServletRequest object
|
||||
* @return the instance of the user
|
||||
* @return the instance of the user
|
||||
* @see the url at client side
|
||||
*/
|
||||
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
|
||||
if(httpServletRequest == null)
|
||||
if (httpServletRequest == null)
|
||||
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||
|
||||
return httpServletRequest.getHeader(Constants.GCUBE_REQUEST_URL);
|
||||
|
@ -362,19 +377,20 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Retrieve the current scope by using the portal manager
|
||||
* @param b
|
||||
*
|
||||
* @param b
|
||||
* @return a GcubeUser object
|
||||
*/
|
||||
public static String getCurrentContext(HttpServletRequest request, boolean setInThread){
|
||||
public static String getCurrentContext(HttpServletRequest request, boolean setInThread) {
|
||||
|
||||
if(request == null)
|
||||
if (request == null)
|
||||
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||
|
||||
PortalContext pContext = PortalContext.getConfiguration();
|
||||
String context = pContext.getCurrentScope(request);
|
||||
logger.debug("Returning context " + context);
|
||||
|
||||
if(context != null && setInThread)
|
||||
if (context != null && setInThread)
|
||||
ScopeProvider.instance.set(context);
|
||||
|
||||
return context;
|
||||
|
@ -382,11 +398,12 @@ public class Utils {
|
|||
|
||||
/**
|
||||
* Retrieve the current user by using the portal manager
|
||||
*
|
||||
* @return a GcubeUser object
|
||||
*/
|
||||
public static GCubeUser getCurrentUser(HttpServletRequest request){
|
||||
public static GCubeUser getCurrentUser(HttpServletRequest request) {
|
||||
|
||||
if(request == null)
|
||||
if (request == null)
|
||||
throw new IllegalArgumentException("HttpServletRequest is null!");
|
||||
|
||||
PortalContext pContext = PortalContext.getConfiguration();
|
||||
|
@ -396,17 +413,18 @@ public class Utils {
|
|||
}
|
||||
|
||||
/**
|
||||
* Exploits the fact that in GRSF the url of a record contains the name (which is unique) of the record itself.
|
||||
* Exploits the fact that in GRSF the url of a record contains the name (which
|
||||
* is unique) of the record itself.
|
||||
*
|
||||
* @param url the url
|
||||
* @param clg the clg
|
||||
* @param url the url
|
||||
* @param clg the clg
|
||||
* @param username the username
|
||||
* @return the dataset from url
|
||||
* @throws Exception the exception
|
||||
*/
|
||||
public static CkanDataset getDatasetFromUrl(String url, DataCatalogue clg, String username) throws Exception{
|
||||
public static CkanDataset getDatasetFromUrl(String url, DataCatalogue clg, String username) throws Exception {
|
||||
|
||||
if(url == null || url.isEmpty())
|
||||
if (url == null || url.isEmpty())
|
||||
return null;
|
||||
|
||||
// Parse url
|
||||
|
@ -425,14 +443,16 @@ public class Utils {
|
|||
}
|
||||
|
||||
/**
|
||||
* Exploits the fact that in GRSF the url of a record contains the name (which is unique) of the record itself
|
||||
* Exploits the fact that in GRSF the url of a record contains the name (which
|
||||
* is unique) of the record itself
|
||||
*
|
||||
* @param url
|
||||
* @param clg
|
||||
* @return
|
||||
*/
|
||||
public static String getDatasetKnowledgeBaseIdFromUrl(String url){
|
||||
public static String getDatasetKnowledgeBaseIdFromUrl(String url) {
|
||||
|
||||
if(url == null || url.isEmpty())
|
||||
if (url == null || url.isEmpty())
|
||||
return null;
|
||||
|
||||
// Parse url
|
||||
|
@ -450,39 +470,38 @@ public class Utils {
|
|||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get a {@link SimilarGRSFRecord} from a json string
|
||||
*
|
||||
* @param json
|
||||
* @return {@link SimilarGRSFRecord}
|
||||
* @throws ParseException
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static SimilarGRSFRecord similarGRSFRecordFromJson(String json, DataCatalogue ctl, String username, HttpSession httpSession) throws ParseException{
|
||||
public static SimilarGRSFRecord similarGRSFRecordFromJson(String json, DataCatalogue ctl, String username,
|
||||
HttpSession httpSession) throws ParseException {
|
||||
|
||||
if(json == null)
|
||||
if (json == null)
|
||||
return null;
|
||||
|
||||
JSONParser parser = new JSONParser();
|
||||
JSONObject object = (JSONObject)parser.parse(json);
|
||||
JSONObject object = (JSONObject) parser.parse(json);
|
||||
|
||||
String uuid = getDatasetKnowledgeBaseIdFromUrl((String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL));
|
||||
CkanDataset dataset = ctl.getDataset(uuid,username);
|
||||
|
||||
boolean isStock = dataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
|
||||
Map<String, String> fieldsNamespacesMap =
|
||||
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
|
||||
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(dataset.getExtras(), fieldsNamespacesMap);
|
||||
String uuid = getDatasetKnowledgeBaseIdFromUrl((String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL));
|
||||
CkanDataset dataset = ctl.getDataset(uuid, username);
|
||||
|
||||
return new SimilarGRSFRecord(
|
||||
uuid,
|
||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION),
|
||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_NAME),
|
||||
dataset.getTitle(),
|
||||
(String)object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL),
|
||||
boolean isStock = dataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||
.contains(Product_Type.STOCK.getOrigName());
|
||||
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
|
||||
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
|
||||
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(dataset.getExtras(),
|
||||
fieldsNamespacesMap);
|
||||
|
||||
return new SimilarGRSFRecord(uuid, (String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_DESCRIPTION),
|
||||
(String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_NAME), dataset.getTitle(),
|
||||
(String) object.get(Constants.SIMILAR_RECORDS_BEAN_FIELD_URL),
|
||||
extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0),
|
||||
extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0)
|
||||
);
|
||||
extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0));
|
||||
|
||||
}
|
||||
|
||||
|
@ -495,7 +514,7 @@ public class Utils {
|
|||
try {
|
||||
UserLocalServiceUtil.getService();
|
||||
return true;
|
||||
}catch (Exception ex) {
|
||||
} catch (Exception ex) {
|
||||
logger.debug("Development Mode ON");
|
||||
return false;
|
||||
}
|
||||
|
@ -504,53 +523,45 @@ public class Utils {
|
|||
/**
|
||||
* Get Connected bean from record.
|
||||
*
|
||||
* @param destUrl the dest url
|
||||
* @param clg the clg
|
||||
* @param username the username
|
||||
* @param destUrl the dest url
|
||||
* @param clg the clg
|
||||
* @param username the username
|
||||
* @param httpSession the http session
|
||||
* @return the connected bean
|
||||
* @throws ParseException the parse exception
|
||||
*/
|
||||
public static ConnectedBean connectedBeanRecordFromUrl(
|
||||
String destUrl,
|
||||
DataCatalogue clg,
|
||||
String username,
|
||||
HttpSession httpSession
|
||||
) throws ParseException {
|
||||
public static ConnectedBean connectedBeanRecordFromUrl(String destUrl, DataCatalogue clg, String username,
|
||||
HttpSession httpSession) throws ParseException {
|
||||
|
||||
if(destUrl == null)
|
||||
if (destUrl == null)
|
||||
return null;
|
||||
|
||||
String connectedBeanUuid = getDatasetKnowledgeBaseIdFromUrl(destUrl);
|
||||
CkanDataset destDataset = clg.getDataset(connectedBeanUuid,username);
|
||||
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY).contains(Product_Type.STOCK.getOrigName());
|
||||
Map<String, String> fieldsNamespacesMap =
|
||||
Utils.getFieldToFieldNameSpaceMapping(httpSession, isStock ?
|
||||
Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK : Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(destDataset.getExtras(), fieldsNamespacesMap);
|
||||
CkanDataset destDataset = clg.getDataset(connectedBeanUuid, username);
|
||||
boolean isStock = destDataset.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
|
||||
.contains(Product_Type.STOCK.getOrigName());
|
||||
Map<String, String> fieldsNamespacesMap = Utils.getFieldToFieldNameSpaceMapping(httpSession,
|
||||
isStock ? Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK
|
||||
: Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
|
||||
Map<String, List<String>> extrasWithoutNamespaces = Utils.replaceFieldsKey(destDataset.getExtras(),
|
||||
fieldsNamespacesMap);
|
||||
String semanticId = extrasWithoutNamespaces.get(Constants.GRSF_SEMANTIC_IDENTIFIER_CUSTOM_KEY).get(0);
|
||||
String destDomain = extrasWithoutNamespaces.get(Constants.DOMAIN_CUSTOM_KEY).get(0);
|
||||
String shortName = extrasWithoutNamespaces.get(Constants.SHORT_NAME_CUSTOM_KEY).get(0);
|
||||
String description = destDataset.getNotes();
|
||||
|
||||
return new ConnectedBean(
|
||||
connectedBeanUuid,
|
||||
description,
|
||||
shortName,
|
||||
destDataset.getTitle(),
|
||||
destUrl,
|
||||
semanticId,
|
||||
destDomain
|
||||
);
|
||||
return new ConnectedBean(connectedBeanUuid, description, shortName, destDataset.getTitle(), destUrl, semanticId,
|
||||
destDomain);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the sysadmin key from the IS for this catalogue
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String fetchSysAPI(String context) throws Exception{
|
||||
public static String fetchSysAPI(String context) throws Exception {
|
||||
DataCatalogueRunningCluster catalogueRunningInstance = new DataCatalogueRunningCluster(context);
|
||||
return catalogueRunningInstance.getSysAdminToken();
|
||||
}
|
||||
|
|
|
@ -1,35 +1,40 @@
|
|||
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
|
||||
|
||||
import org.gcube.datacatalogue.common.enums.Status;
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.gcube.datacatalogue.common.enums.Status;
|
||||
|
||||
/**
|
||||
* The Class GRSFRecordAlreadyManagedStatusException.
|
||||
*
|
||||
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
|
||||
*
|
||||
* Mar 21, 2019
|
||||
* Mar 21, 2019
|
||||
*/
|
||||
public class GRSFRecordAlreadyManagedStatusException extends Exception{
|
||||
public class GRSFRecordAlreadyManagedStatusException extends Exception implements Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -2034802685606929315L;
|
||||
private Status status;
|
||||
|
||||
|
||||
public GRSFRecordAlreadyManagedStatusException() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new GRSF record already managed status exception.
|
||||
*
|
||||
* @param theStatus the the status
|
||||
* @param arg0 the arg 0
|
||||
* @param arg0 the arg 0
|
||||
*/
|
||||
public GRSFRecordAlreadyManagedStatusException(Status theStatus, String arg0){
|
||||
public GRSFRecordAlreadyManagedStatusException(Status theStatus, String arg0) {
|
||||
super(arg0);
|
||||
this.status = theStatus;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the status.
|
||||
*
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
package org.gcube.datacatalogue.grsf_manage_widget.shared.ex;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* This is thrown when the Manage product is pushed on a product that has
|
||||
* a Record Type field of Source or none.
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
* This is thrown when the Manage product is pushed on a product that has a
|
||||
* Record Type field of Source or none.
|
||||
*
|
||||
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
|
||||
*/
|
||||
public class NoGRSFRecordException extends Exception {
|
||||
public class NoGRSFRecordException extends Exception implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 721315478405659218L;
|
||||
private String errorMessage;
|
||||
|
|
Loading…
Reference in New Issue